// Main app — private label seller's FBA profit calculator
const { useState: aUseState, useEffect: aUseEffect, useRef: aUseRef, useMemo: aUseMemo } = React;

// ── Popover rendered via portal into document.body — escapes any stacking context ──
function Popover({ anchorRef, onClose, align = "right", width, children }) {
  const [coords, setCoords] = aUseState(null);

  aUseEffect(() => {
    if (!anchorRef.current) return;
    const update = () => {
      const rect = anchorRef.current.getBoundingClientRect();
      const left = align === "right"
        ? Math.max(8, rect.right - (width || 360))
        : rect.left;
      setCoords({
        top: rect.bottom + 8,
        left,
        width: width || 360,
      });
    };
    update();
    window.addEventListener("scroll", update, true);
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update, true);
      window.removeEventListener("resize", update);
    };
  }, [anchorRef, align, width]);

  aUseEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  if (!coords) return null;

  return ReactDOM.createPortal(
    <>
      <div className="popover-backdrop" onClick={onClose} />
      <div
        className="popover-menu"
        style={{
          top: coords.top + "px",
          left: coords.left + "px",
          width: coords.width + "px",
        }}
        onClick={e => e.stopPropagation()}
      >
        {children}
      </div>
    </>,
    document.body
  );
}

function App() {
  const { MARKETPLACES, CATEGORIES, SIZE_TIERS, PRODUCT_TEMPLATES, SCENARIO_COLORS } = window.FBA;
  const { autoReferral, autoFbaFee, autoStorageMonthly, detectFromName } = window.FBA.calc;

  // ── Default input for a fresh scenario ──
  function makeDefaultInput(marketplace = "US", overrides = {}) {
    const mkt = MARKETPLACES[marketplace];
    return {
      marketplace,
      title: "Stainless Steel Insulated Water Bottle 32 oz",
      image: "bottle",
      category: "home",
      sizeTier: "large_std_2lb",
      autoDetected: { category: true, sizeTier: true },
      weight: 1.4, length: 11, width: 3.5, height: 3.5,
      unitCost: 3.80,
      shippingPerUnit: 0.75,
      prepPerUnit: 0.30,
      dutyPct: 2,
      orderQty: 500,
      sellPrice: 24.99,
      discountPct: 0,
      referralPct: autoReferral("home", 24.99) * 100,
      fbaFee: autoFbaFee("large_std_2lb"),
      storageMonthly: autoStorageMonthly("large_std_2lb"),
      monthsInStorage: 1,
      longTermStorage: 0,
      acosPct: 14,
      ppcSharePct: 20,
      returnRatePct: 2,
      returnHandlingCost: 1.50,
      vatPct: mkt.vat,
      unitsPerDay: 12,
      ...overrides,
    };
  }

  // ── Scenarios ──
  const [scenarios, setScenarios] = aUseState(() => [
    { id: "A", name: "Base case",  color: SCENARIO_COLORS[0], input: makeDefaultInput("US") },
    { id: "B", name: "Premium",    color: SCENARIO_COLORS[1], input: makeDefaultInput("US", { sellPrice: 34.99, unitCost: 5.20, acosPct: 12, unitsPerDay: 9 }) },
    { id: "C", name: "Value SKU",  color: SCENARIO_COLORS[2], input: makeDefaultInput("US", { sellPrice: 19.99, unitCost: 2.80, acosPct: 18, unitsPerDay: 22 }) },
  ]);
  const [activeId, setActiveId] = aUseState("A");
  const [compareMode, setCompareMode] = aUseState(false);
  const [marketplace, setMarketplace] = aUseState("US");
  const [showMarketMenu, setShowMarketMenu] = aUseState(false);
  const [showTemplateMenu, setShowTemplateMenu] = aUseState(false);
  const [savedToast, setSavedToast] = aUseState("");
  const detectDebounceRef = aUseRef(null);
  const [detecting, setDetecting] = aUseState(false);
  const tmplBtnRef = aUseRef(null);
  const marketBtnRef = aUseRef(null);

  const active = scenarios.find(s => s.id === activeId) || scenarios[0];
  const mkt = MARKETPLACES[marketplace];

  // ── Product-identity fields are shared across scenarios; pricing/cost/marketing are per-scenario.
  //    Compare mode is for "different strategies for the same product".
  const SHARED_FIELDS = new Set([
    "title", "image", "category", "sizeTier",
    "weight", "length", "width", "height",
    "autoDetected", "referralPct", "fbaFee", "storageMonthly",
  ]);

  // ── Update scenario inputs ──
  const updateActive = (patch) => {
    const sharedPatch = {};
    const localPatch = {};
    for (const [k, v] of Object.entries(patch)) {
      if (SHARED_FIELDS.has(k)) sharedPatch[k] = v;
      else localPatch[k] = v;
    }
    setScenarios(prev => prev.map(s => ({
      ...s,
      input: {
        ...s.input,
        ...sharedPatch,
        ...(s.id === activeId ? localPatch : {}),
      },
    })));
  };

  // ── Marketplace change applies to all scenarios (VAT auto) ──
  const changeMarketplace = (code) => {
    setMarketplace(code);
    const m = MARKETPLACES[code];
    setScenarios(prev => prev.map(s => ({
      ...s,
      input: { ...s.input, marketplace: code, vatPct: m.vat },
    })));
    setShowMarketMenu(false);
  };

  // ── Smart-detect category & size tier as user types product name ──
  const onTitleChange = (raw) => {
    updateActive({ title: raw });
    if (detectDebounceRef.current) clearTimeout(detectDebounceRef.current);
    setDetecting(true);
    detectDebounceRef.current = setTimeout(() => {
      const { category, sizeTier } = detectFromName(raw);
      const patch = {};
      const ad = { ...(active.input.autoDetected || {}) };

      // Only override category if it was auto-detected before (user hasn't manually picked)
      if (category && (active.input.autoDetected?.category !== false)) {
        if (category !== active.input.category) {
          patch.category = category;
          patch.referralPct = +(autoReferral(category, +active.input.sellPrice || 0) * 100).toFixed(2);
          ad.category = true;
        }
      }
      if (sizeTier && (active.input.autoDetected?.sizeTier !== false)) {
        if (sizeTier !== active.input.sizeTier) {
          patch.sizeTier = sizeTier;
          patch.fbaFee = autoFbaFee(sizeTier);
          patch.storageMonthly = autoStorageMonthly(sizeTier);
          patch.weight = SIZE_TIERS[sizeTier]?.weight ?? active.input.weight;
          ad.sizeTier = true;
        }
      }
      if (Object.keys(patch).length > 0) {
        patch.autoDetected = ad;
        updateActive(patch);
      }
      setDetecting(false);
    }, 350);
  };

  // ── Apply a quick-pick template ──
  const applyTemplate = (slug) => {
    const t = PRODUCT_TEMPLATES.find(x => x.slug === slug);
    if (!t) return;
    updateActive({
      title: t.title,
      image: t.image,
      category: t.category,
      sizeTier: t.sizeTier,
      autoDetected: { category: true, sizeTier: true },
      weight: t.weight, length: t.length, width: t.width, height: t.height,
      sellPrice: t.sellPrice,
      unitCost: t.suggestedCost,
      referralPct: +(autoReferral(t.category, t.sellPrice) * 100).toFixed(2),
      fbaFee: autoFbaFee(t.sizeTier),
      storageMonthly: autoStorageMonthly(t.sizeTier),
    });
    flashToast(`Loaded ${t.label} template`);
    setShowTemplateMenu(false);
  };

  const flashToast = (msg) => {
    setSavedToast(msg);
    setTimeout(() => setSavedToast(""), 2200);
  };

  // ── Scenario actions ──
  const addScenario = () => {
    if (scenarios.length >= 4) { flashToast("Max 4 scenarios"); return; }
    const id = String.fromCharCode(65 + scenarios.length);
    const newS = {
      id,
      name: `Scenario ${id}`,
      color: SCENARIO_COLORS[scenarios.length % SCENARIO_COLORS.length],
      input: { ...active.input },
    };
    setScenarios([...scenarios, newS]);
    setActiveId(id);
  };
  const removeScenario = (id) => {
    if (scenarios.length <= 1) return;
    const next = scenarios.filter(s => s.id !== id);
    setScenarios(next);
    if (activeId === id) setActiveId(next[0].id);
  };
  const renameScenario = (id, name) => {
    setScenarios(prev => prev.map(s => s.id === id ? { ...s, name } : s));
  };
  const duplicateScenario = (id) => {
    if (scenarios.length >= 4) { flashToast("Max 4 scenarios"); return; }
    const src = scenarios.find(s => s.id === id);
    const newId = String.fromCharCode(65 + scenarios.length);
    setScenarios([...scenarios, {
      id: newId,
      name: src.name + " copy",
      color: SCENARIO_COLORS[scenarios.length % SCENARIO_COLORS.length],
      input: { ...src.input },
    }]);
    setActiveId(newId);
  };

  // ── CSV export ──
  const exportCsv = () => {
    const rows = [
      ["FBA Profit Calculator — Private Label export"],
      ["Marketplace", mkt.name + " (" + mkt.currency + ")"],
      ["Generated", new Date().toISOString().slice(0, 16).replace("T", " ")],
      [],
      ["Scenario", "Product", "Category", "Size tier", "Sell price", "Landed cost", "Total fees", "Profit/unit", "Margin %", "ROI %", "Break-even units", "Monthly profit", "Annual profit"],
    ];
    scenarios.forEach(s => {
      const r = window.FBA.calc.compute(s.input);
      rows.push([
        s.name, s.input.title, CATEGORIES[s.input.category]?.name || "",
        SIZE_TIERS[s.input.sizeTier]?.name || "",
        s.input.sellPrice, r.landed.toFixed(2), r.totalFees.toFixed(2),
        r.profit.toFixed(2), (r.margin * 100).toFixed(1), (r.roi * 100).toFixed(1),
        isFinite(r.breakEvenUnits) ? Math.ceil(r.breakEvenUnits) : "",
        r.monthlyProfit.toFixed(0), r.annualProfit.toFixed(0),
      ]);
    });
    const csv = rows.map(row => row.map(v => {
      const s = String(v ?? "");
      return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    }).join(",")).join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = "fba-scenarios.csv"; a.click();
    URL.revokeObjectURL(url);
    flashToast("Exported to CSV");
  };

  return (
    <div className="app" data-screen-label="Calculator">
      {/* ─── Header ─── */}
      <header className="app-header">
        <div className="header-deco" aria-hidden="true">
          <svg viewBox="0 0 600 200" preserveAspectRatio="none">
            <defs>
              <linearGradient id="hdr-arc" x1="0" x2="1">
                <stop offset="0" stopColor="#FF9900" stopOpacity="0" />
                <stop offset="1" stopColor="#FF9900" stopOpacity=".5" />
              </linearGradient>
              <linearGradient id="hdr-line" x1="0" x2="1">
                <stop offset="0" stopColor="#FF9900" stopOpacity="0" />
                <stop offset=".5" stopColor="#FF9900" stopOpacity=".15" />
                <stop offset="1" stopColor="#FF9900" stopOpacity="0" />
              </linearGradient>
            </defs>
            <path d="M0 160 Q150 80 300 120 T600 60" stroke="url(#hdr-arc)" strokeWidth="2.5" fill="none" />
            <path d="M0 100 Q200 40 400 90 T700 50" stroke="url(#hdr-line)" strokeWidth="1.5" fill="none" />
            <g opacity=".18">
              <circle cx="510" cy="40" r="2" fill="#FF9900" />
              <circle cx="550" cy="70" r="2" fill="#FF9900" />
              <circle cx="480" cy="90" r="1.5" fill="#FF9900" />
              <circle cx="520" cy="130" r="2" fill="#FF9900" />
              <circle cx="570" cy="150" r="1.5" fill="#FF9900" />
            </g>
          </svg>
        </div>

        <div className="header-row">
          <div className="brand">
            <BrandMark />
            <div className="brand-text">
              <div className="brand-name">FBA Profit <span className="accent">Calculator</span></div>
              <div className="brand-sub">For Private Label sellers · {Object.keys(MARKETPLACES).length} global marketplaces</div>
            </div>
          </div>

          <div className="header-spacer" />

          <div className="header-tools">
            <a
              className="hdr-btn hdr-link"
              href="https://highrisewholesale.com/highrise-wholesale-landing.html"
              target="_blank"
              rel="noopener noreferrer"
              title="Highrise Wholesale"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12l9-9 9 9"/><path d="M5 10v10h14V10"/><path d="M10 20v-6h4v6"/></svg>
              Highrise Wholesale
              <svg className="hdr-link-ext" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7"/><path d="M8 7h9v9"/></svg>
            </a>

            {/* Templates dropdown */}
            <div className="tmpl-wrap">
              <button ref={tmplBtnRef} className="hdr-btn tmpl-btn" onClick={() => setShowTemplateMenu(s => !s)}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
                Templates
              </button>
              {showTemplateMenu && (
                <Popover anchorRef={tmplBtnRef} onClose={() => setShowTemplateMenu(false)} width={340}>
                  <div className="market-menu-title">Start from a product template</div>
                  <div className="tmpl-list">
                    {PRODUCT_TEMPLATES.map(t => (
                      <button key={t.slug} className="tmpl-item" onClick={() => applyTemplate(t.slug)}>
                        <span className="tmpl-glyph"><window.UI.ProductGlyph kind={t.image} size={36} /></span>
                        <span className="tmpl-info">
                          <span className="tmpl-label">{t.label}</span>
                          <span className="tmpl-meta">{CATEGORIES[t.category]?.name} · {mkt.symbol}{t.sellPrice}</span>
                        </span>
                      </button>
                    ))}
                  </div>
                </Popover>
              )}
            </div>

            <button className="hdr-btn" onClick={() => setCompareMode(c => !c)}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="7" height="16" rx="1"/><rect x="14" y="4" width="7" height="16" rx="1"/></svg>
              {compareMode ? "Exit compare" : "Compare"}
            </button>
            <button className="hdr-btn" onClick={exportCsv}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v12"/><path d="M7 10l5 5 5-5"/><path d="M5 21h14"/></svg>
              Export CSV
            </button>

            {/* Marketplace switcher */}
            <div className="market-wrap">
              <button ref={marketBtnRef} className="market-btn" onClick={() => setShowMarketMenu(s => !s)}>
                <span className="market-code">{mkt.code}</span>
                <span className="market-cur">{mkt.currency}</span>
                <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M1 3l4 4 4-4z"/></svg>
              </button>
              {showMarketMenu && (
                <Popover anchorRef={marketBtnRef} onClose={() => setShowMarketMenu(false)} width={360}>
                  <div className="market-menu-title">Marketplace</div>
                  <div className="market-menu-grid">
                    {Object.values(MARKETPLACES).map(m => (
                      <button
                        key={m.code}
                        className={"market-item " + (m.code === marketplace ? "active" : "")}
                        onClick={() => changeMarketplace(m.code)}
                      >
                        <span className="market-item-code">{m.code}</span>
                        <span className="market-item-name">{m.name}</span>
                        <span className="market-item-cur mono">{m.symbol}</span>
                      </button>
                    ))}
                  </div>
                </Popover>
              )}
            </div>
          </div>
        </div>

        <div className="header-features">
          <div className="hdr-feature">
            <span className="hdr-feature-icon">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></svg>
            </span>
            <span className="hdr-feature-text"><b>{Object.keys(MARKETPLACES).length} marketplaces</b> · live currency</span>
          </div>
          <div className="hdr-divider" />
          <div className="hdr-feature">
            <span className="hdr-feature-icon">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>
            </span>
            <span className="hdr-feature-text"><b>Auto-detect</b> category &amp; fees from name</span>
          </div>
          <div className="hdr-divider" />
          <div className="hdr-feature">
            <span className="hdr-feature-icon">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18"/><path d="M7 14l4-4 3 3 5-7"/></svg>
            </span>
            <span className="hdr-feature-text"><b>Full P&amp;L</b> · PPC, storage, returns, VAT</span>
          </div>
          <div className="hdr-divider" />
          <div className="hdr-feature">
            <span className="hdr-feature-icon">
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="7" height="16" rx="1"/><rect x="14" y="4" width="7" height="16" rx="1"/></svg>
            </span>
            <span className="hdr-feature-text"><b>Side-by-side</b> scenario comparison</span>
          </div>
        </div>
      </header>

      {/* ─── Scenarios bar ─── */}
      <div className="scenario-bar">
        <div className="scenario-tabs">
          {scenarios.map(s => (
            <ScenarioTab
              key={s.id}
              scenario={s}
              active={s.id === activeId}
              onClick={() => setActiveId(s.id)}
              onRename={(name) => renameScenario(s.id, name)}
              onDuplicate={() => duplicateScenario(s.id)}
              onRemove={() => removeScenario(s.id)}
              canRemove={scenarios.length > 1}
            />
          ))}
          {scenarios.length < 4 && (
            <button className="scenario-add" onClick={addScenario}>
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 1v10M1 6h10"/></svg>
              Add scenario
            </button>
          )}
        </div>
        <div className="scenario-meta">
          <span className="scenario-product">{active.input.title || "Untitled product"}</span>
          <span className="scenario-dot">·</span>
          <span className="scenario-product mono">{CATEGORIES[active.input.category]?.name || "—"}</span>
        </div>
      </div>

      {/* ─── Main body ─── */}
      <div className="app-body">
        <div className="pane-left">
          <window.Inputs
            input={active.input}
            update={updateActive}
            mkt={mkt}
            onTitleChange={onTitleChange}
            detecting={detecting}
            templates={PRODUCT_TEMPLATES}
            applyTemplate={applyTemplate}
          />
        </div>
        <div className="pane-right">
          <window.Results scenarios={scenarios} activeId={activeId} compareMode={compareMode} mkt={mkt} />
        </div>
      </div>

      {/* ─── Toast ─── */}
      {savedToast && <div className="toast">{savedToast}</div>}
    </div>
  );
}

// ── Scenario tab with edit/delete menu ──
function ScenarioTab({ scenario, active, onClick, onRename, onDuplicate, onRemove, canRemove }) {
  const [editing, setEditing] = aUseState(false);
  const [menuOpen, setMenuOpen] = aUseState(false);
  const inputRef = aUseRef(null);

  aUseEffect(() => {
    if (editing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [editing]);

  const r = window.FBA.calc.compute(scenario.input);

  return (
    <div className={"scenario-tab " + (active ? "active" : "")} onClick={onClick}>
      <span className="scenario-dot-mark" style={{ background: scenario.color }} />
      {editing ? (
        <input
          ref={inputRef}
          className="scenario-edit"
          value={scenario.name}
          onChange={e => onRename(e.target.value)}
          onBlur={() => setEditing(false)}
          onKeyDown={e => { if (e.key === "Enter") setEditing(false); }}
          onClick={e => e.stopPropagation()}
        />
      ) : (
        <span className="scenario-name" onDoubleClick={(e) => { e.stopPropagation(); setEditing(true); }}>{scenario.name}</span>
      )}
      <span className={"scenario-margin mono " + (r.margin >= 0.15 ? "good" : r.margin >= 0 ? "warn" : "bad")}>
        {(r.margin * 100).toFixed(0)}%
      </span>
      <div className="scenario-menu-wrap" onClick={e => e.stopPropagation()}>
        <button className="scenario-menu-btn" onClick={() => setMenuOpen(o => !o)}>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor"><circle cx="2" cy="6" r="1.2"/><circle cx="6" cy="6" r="1.2"/><circle cx="10" cy="6" r="1.2"/></svg>
        </button>
        {menuOpen && (
          <>
            <div className="market-backdrop" onClick={() => setMenuOpen(false)} />
            <div className="scenario-menu">
              <button onClick={() => { setEditing(true); setMenuOpen(false); }}>Rename</button>
              <button onClick={() => { onDuplicate(); setMenuOpen(false); }}>Duplicate</button>
              {canRemove && <button className="danger" onClick={() => { onRemove(); setMenuOpen(false); }}>Delete</button>}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── Brand mark — orange smile arc on navy, Amazon-flavored ──
function BrandMark() {
  return (
    <svg className="brand-mark" viewBox="0 0 40 40" width="56" height="56">
      <rect width="40" height="40" rx="8" fill="#0F1B2D" />
      <path d="M8 22c4 5 20 5 24 0" stroke="#FF9900" strokeWidth="2.6" strokeLinecap="round" fill="none" />
      <path d="M28 18l4 4-4 4" stroke="#FF9900" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" fill="none" />
      <text x="20" y="16" textAnchor="middle" fontFamily="'JetBrains Mono', monospace" fontSize="9" fontWeight="700" fill="#fff">$</text>
    </svg>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
