/* =========================================================================
   Live ICP Tracker — App shell, router, Tweaks wiring
   ========================================================================= */
const { useState: useStateApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "view": "internal",
  "layout": "table",
  "density": "comfortable",
  "enrichment": "standard"
}/*EDITMODE-END*/;

const NAV = [
  { key: "list", label: "Live ICP database", icon: "list" },
  { key: "signals", label: "Signal feed", icon: "signal" },
  { key: "roster", label: "Warm-intro roster", icon: "users" },
  { key: "spend", label: "CAC & spend", icon: "dollar" },
];

function Sidebar({ route, setRoute, onExternal, listTab, setListTab }) {
  const I = window.ICP;
  const counts = {
    list: I.META.workingShown,
    signals: I.ACCOUNTS.reduce((n, a) => n + a.signals.filter(s => s.heat === "hot").length, 0),
    roster: I.PARTNERS.length,
  };
  return (
    <aside className="rail">
      <div className="rail-brand">
        <img src="assets/malachyte-symbol-gradient.png" alt="" onError={e => { e.target.style.display = 'none'; }} />
        <div className="wm">Live ICP Tracker<small>Malachyte GTM</small></div>
      </div>

      <nav className="nav-group">
        <div className="nav-label">Workspace</div>
        {NAV.map(n => (
          <React.Fragment key={n.key}>
            <button className={"nav-item" + ((route.screen === n.key && !(n.key === "list" && listTab !== "ranked")) ? " active" : "")}
              onClick={() => { setRoute({ screen: n.key, account: null }); if (n.key === "list") setListTab("ranked"); }}>
              <Icon name={n.icon} className="ic" size={17} />
              <span>{n.label}</span>
              {counts[n.key] != null && <span className="count">{counts[n.key]}</span>}
            </button>
            {n.key === "list" && route.screen === "list" && (
              <div className="nav-sub">
                <button className={"nav-subitem" + (listTab === "saved" ? " active" : "")}
                  onClick={() => { setRoute({ screen: "list", account: null }); setListTab("saved"); }}>
                  Saved ICP lists
                </button>
                <button className={"nav-subitem" + (listTab === "tuner" ? " active" : "")}
                  onClick={() => { setRoute({ screen: "list", account: null }); setListTab("tuner"); }}>
                  ICP score tuner
                </button>
              </div>
            )}
          </React.Fragment>
        ))}
      </nav>

      <div className="nav-group">
        <div className="nav-label">Share</div>
        <button className="nav-item" onClick={onExternal}>
          <Icon name="share" className="ic" size={17} />
          <span>External partner view</span>
          <Icon name="external" size={13} style={{ marginLeft: "auto", color: "var(--fg-subtle)" }} />
        </button>
      </div>

      <div className="rail-foot">
        <div className="who">
          <img src="assets/malachyte-symbol-gradient.png" alt="Malachyte" style={{ width: 28, height: 28, borderRadius: "50%", objectFit: "cover", flexShrink: 0, background: "var(--bg-subtle, #F0EDE7)" }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Malachyte Team Account</div>
            <div className="subtle" style={{ fontSize: 11 }}>GTM · internal</div>
          </div>
          <Icon name="settings" size={16} style={{ color: "var(--fg-subtle)" }} />
        </div>
      </div>
    </aside>
  );
}

const TITLES = {
  list: { h: "Live ICP database", s: "One live, ranked list everyone trusts — pulled from HubSpot." },
  signals: { h: "Live signal feed", s: "In-market triggers, ranked by heat." },
  roster: { h: "Warm-intro & referral roster", s: "Our CAB network and the doors they open." },
  tuner: { h: "ICP score tuner", s: "Adjust the weights; the ranking re-sorts live." },
  spend: { h: "CAC & referral-spend tracker", s: "List, leads, and money in one place." },
};

function InternalApp({ tweaks, setTweak }) {
  const [route, setRoute] = useStateApp({ screen: "list", account: null });
  const [listTab, setListTab] = useStateApp("ranked"); // ranked | saved
  const I = window.ICP;
  const openAccount = (a) => setRoute(r => ({ ...r, account: a }));
  const closeAccount = () => setRoute(r => ({ ...r, account: null }));

  let body, title;
  if (route.account) {
    title = { h: route.account.brand, s: "Account Command Card · everything to win this account" };
    body = <CommandCard account={route.account} onBack={closeAccount} />;
  } else {
    title = TITLES[route.screen];
    if (route.screen === "list") {
      title = listTab === "saved"
        ? { h: "Live ICP database", s: "Saved ICP lists you’ve built from the ranked database." }
        : listTab === "tuner"
          ? TITLES.tuner
          : TITLES.list;
      body = listTab === "saved"
        ? <SavedListsView onOpen={openAccount} />
        : listTab === "tuner"
          ? <TunerView onOpen={openAccount} />
          : <ListView tweaks={tweaks} onOpen={openAccount} />;
    }
    else if (route.screen === "signals") body = <SignalsView onOpen={openAccount} />;
    else if (route.screen === "roster") body = <RosterView onOpen={openAccount} />;
    else if (route.screen === "spend") body = <SpendView />;
  }

  return (
    <div className="app" data-density={tweaks.density}>
      <Sidebar route={route} setRoute={setRoute} onExternal={() => setTweak("view", "external")} listTab={listTab} setListTab={setListTab} />
      <div className="main">
        <header className="topbar">
          {route.account && <button className="btn ghost sm" onClick={closeAccount} style={{ marginLeft: -6 }}><Icon name="chevL" size={16} /></button>}
          <div>
            <h1>{title.h}</h1>
            <div className="sub">{title.s}</div>
          </div>
          <div className="spacer"></div>
          {route.screen === "list" && !route.account && listTab === "ranked" && (
            <div className="seg" title="List layout (also in Tweaks)">
              {[["table", "grid"], ["cards", "layers"], ["tiers", "columns"]].map(([k, ic]) => (
                <button key={k} className={tweaks.layout === k ? "on" : ""} onClick={() => setTweak("layout", k)} title={k}>
                  <Icon name={ic} size={14} style={{ verticalAlign: -2, marginRight: 4 }} />{k[0].toUpperCase() + k.slice(1)}
                </button>
              ))}
            </div>
          )}
        </header>
        <div className="scroll">{body}</div>
      </div>
    </div>
  );
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  return (
    <React.Fragment>
      {tweaks.view === "external"
        ? <ExternalView />
        : <InternalApp tweaks={tweaks} setTweak={setTweak} />}

      {/* floating switch back when external */}
      {tweaks.view === "external" && (
        <button className="btn" style={{ position: "fixed", left: 20, bottom: 20, zIndex: 50, boxShadow: "var(--shadow-lg)", background: "var(--c-charcoal)", color: "#fff", borderColor: "var(--c-charcoal)" }}
          onClick={() => setTweak("view", "internal")}>
          <Icon name="chevL" size={15} />Back to internal tool
        </button>
      )}

      <TweaksPanel>
        <TweakSection label="View" />
        <TweakRadio label="Audience" value={tweaks.view}
          options={[{ value: "internal", label: "Internal" }, { value: "external", label: "Partner" }]}
          onChange={v => setTweak("view", v)} />
        <TweakSection label="Ranked list" />
        <TweakRadio label="Layout" value={tweaks.layout}
          options={[{ value: "table", label: "Table" }, { value: "cards", label: "Cards" }, { value: "tiers", label: "Tiers" }]}
          onChange={v => setTweak("layout", v)} />
        <TweakRadio label="Density" value={tweaks.density}
          options={[{ value: "comfortable", label: "Comfortable" }, { value: "compact", label: "Compact" }]}
          onChange={v => setTweak("density", v)} />
        <TweakRadio label="Enrichment / row" value={tweaks.enrichment}
          options={[{ value: "minimal", label: "Minimal" }, { value: "standard", label: "Standard" }, { value: "rich", label: "Rich" }]}
          onChange={v => setTweak("enrichment", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

// Pull live HubSpot-synced data before mounting so the UI renders with real accounts.
(async () => {
  if (window.ICP && window.ICP.loadLive) {
    await window.ICP.loadLive();
  }
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
})();
