// OrgFlowsHero.jsx
// Inlines the CTO Console "token flows · org breakdown" view as a hero
// for the landing page. Self-contained: sidebar, topbar, flow controls, sankey.
// Depends on global window.SankeyView (from Sankey.jsx) and window.TM (data).

const { useState: useStateOFH } = React;

function _Pill({ children, active, onClick, danger }) {
  return (
    <button onClick={onClick}
      style={{
        fontFamily: "var(--font-mono)",
        fontSize: 11,
        height: 26,
        padding: "0 12px",
        borderRadius: "var(--radius-pill)",
        background: active ? "var(--accent-faint)" : "var(--bg-2)",
        border: `1px solid ${active ? "var(--accent)" : "var(--border)"}`,
        color: danger ? "var(--danger)" : active ? "var(--accent)" : "var(--fg-2)",
        cursor: "pointer",
        transition: "all var(--dur-fast) var(--ease)",
      }}>
      {active ? "● " : ""}{children}
    </button>
  );
}

function _FlowControls({ presetId, setPresetId, windowKey, setWindowKey, showShadow, setShowShadow }) {
  const presets = window.SANKEY_PRESETS || [];
  return (
    <div style={ofhStyles.fcBar}>
      <div style={ofhStyles.fcGroup}>
        <span style={ofhStyles.fcLabel}>// breakdown</span>
        {presets.map((p) =>
          <_Pill key={p.id} active={presetId === p.id} onClick={() => setPresetId(p.id)}>{p.name}</_Pill>
        )}
      </div>
      <div style={ofhStyles.fcSpacer} />
      <div style={ofhStyles.fcGroup}>
        <span style={ofhStyles.fcLabel}>// window</span>
        {[["7d", "7d"], ["30d", "30d"], ["90d", "90d"], ["qtd", "QTD"]].map(([id, lbl]) =>
          <_Pill key={id} active={windowKey === id} onClick={() => setWindowKey(id)}>{lbl}</_Pill>
        )}
      </div>
      <div style={ofhStyles.fcSpacer} />
      <_Pill danger active={showShadow} onClick={() => setShowShadow(!showShadow)}>shadow ai</_Pill>
    </div>
  );
}

function OrgFlowsHero() {
  const [presetId, setPresetId] = useStateOFH("org");
  const [windowKey, setWindowKey] = useStateOFH("7d");
  const [showShadow, setShowShadow] = useStateOFH(true);
  const sankeyRef = React.useRef(null);
  const [sankeyW, setSankeyW] = useStateOFH(1060);
  const isMobile = window.useMediaQuery ? window.useMediaQuery('(max-width: 768px)') : false;

  React.useEffect(() => {
    if (!sankeyRef.current) return;
    const ro = new ResizeObserver((entries) => {
      for (const e of entries) {
        const w = Math.floor(e.contentRect.width);
        if (w > 0) setSankeyW(w);
      }
    });
    ro.observe(sankeyRef.current);
    return () => ro.disconnect();
  }, []);

  const items = [
    { id: "flows",    label: "token flows",       icon: "≋", active: true },
    { id: "overview", label: "org overview",      icon: "◇" },
    { id: "teams",    label: "team leaderboard",  icon: "▤" },
    { id: "people",   label: "individuals",       icon: "○" },
    { id: "models",   label: "model spend",       icon: "✦" },
    { id: "shadow",   label: "shadow ai",         icon: "!", danger: true },
  ];

  return (
    <div style={{ ...ofhStyles.app, gridTemplateColumns: isMobile ? '1fr' : '220px 1fr', minHeight: isMobile ? 0 : 760 }}>
      {/* Sidebar — decorative product chrome, hidden on mobile */}
      {!isMobile && <aside style={ofhStyles.side}>
        <div style={ofhStyles.brand}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Mark size={20} />
            <span style={{
              fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18,
              letterSpacing: "-0.025em", color: "var(--fg-0)",
            }}>tokenmaxxer</span>
          </div>
          <div style={ofhStyles.brandSub}>console</div>
        </div>
        <nav style={ofhStyles.nav}>
          {items.map((it) =>
            <button key={it.id}
              style={{
                ...ofhStyles.navItem,
                ...(it.active ? ofhStyles.navItemActive : null),
                ...(it.danger ? { color: "var(--danger)" } : null),
              }}>
              <span style={ofhStyles.navIcon}>{it.icon}</span>
              <span>{it.label}</span>
              {it.active && <span style={ofhStyles.navTick}>●</span>}
            </button>
          )}
        </nav>
        <div style={ofhStyles.sideFooter}>
          <div style={ofhStyles.user}>
            <div style={ofhStyles.av}>RC</div>
            <div>
              <div style={ofhStyles.uname}>r.calderon</div>
              <div style={ofhStyles.urole}>cto · helio</div>
            </div>
          </div>
        </div>
      </aside>}

      {/* Main column */}
      <div style={ofhStyles.main}>
        <header style={{ ...ofhStyles.topbar, padding: isMobile ? '0 14px' : '0 24px' }}>
          <div style={ofhStyles.crumbs}>
            {!isMobile && <span style={ofhStyles.crumbMute}>helio</span>}
            {!isMobile && <span style={ofhStyles.slash}>/</span>}
            <span style={ofhStyles.crumb}>console</span>
            <span style={ofhStyles.slash}>·</span>
            <span style={ofhStyles.crumbAcc}>token flows</span>
          </div>
          <div style={ofhStyles.actions}>
            {!isMobile && <button style={ofhStyles.btn}>⌘K</button>}
            {!isMobile && <button style={ofhStyles.btn}>export csv</button>}
            <button style={ofhStyles.btnP}>open report →</button>
          </div>
        </header>

        <div style={{ ...ofhStyles.content, padding: isMobile ? 12 : 20 }}>
          <_FlowControls
            presetId={presetId} setPresetId={setPresetId}
            windowKey={windowKey} setWindowKey={setWindowKey}
            showShadow={showShadow} setShowShadow={setShowShadow}
          />
          <div ref={sankeyRef} style={{ marginTop: 16 }}>
            {window.SankeyView ? (
              <window.SankeyView
                presetId={presetId}
                windowKey={windowKey}
                width={sankeyW}
                height={isMobile ? 360 : 560}
              />
            ) : (
              <div style={ofhStyles.fallback}>// loading flows…</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

const ofhStyles = {
  app: {
    display: "grid", gridTemplateColumns: "220px 1fr",
    background: "var(--bg-0)",
    border: "1px solid var(--border)",
    borderRadius: "var(--radius-md)",
    overflow: "hidden",
    boxShadow: "var(--shadow-md)",
    minHeight: 760,
  },
  // --- sidebar
  side: { background: "var(--bg-1)", borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column" },
  brand: { padding: "16px 16px 12px", borderBottom: "1px solid var(--border)" },
  brandSub: { fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)", marginTop: 6, textTransform: "uppercase", letterSpacing: "0.08em" },
  nav: { padding: 8, flex: 1, display: "flex", flexDirection: "column", gap: 2 },
  navItem: { display: "flex", alignItems: "center", gap: 12, padding: "9px 12px", borderRadius: "var(--radius-sm)", background: "transparent", border: 0, color: "var(--fg-2)", fontFamily: "var(--font-body)", fontSize: 13, cursor: "pointer", textAlign: "left", transition: "all var(--dur-fast) var(--ease)" },
  navItemActive: { background: "var(--bg-2)", color: "var(--fg-0)" },
  navIcon: { fontFamily: "var(--font-mono)", width: 14, color: "var(--fg-3)" },
  navTick: { marginLeft: "auto", color: "var(--accent)", fontSize: 8 },
  sideFooter: { borderTop: "1px solid var(--border)", padding: 12 },
  user: { display: "flex", alignItems: "center", gap: 10 },
  av: { width: 32, height: 32, borderRadius: "50%", background: "var(--bg-3)", border: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-1)", fontWeight: 600 },
  uname: { fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-1)" },
  urole: { fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)" },
  // --- main
  main: { display: "flex", flexDirection: "column", minWidth: 0 },
  topbar: { height: 56, padding: "0 24px", background: "rgba(11,13,15,0.85)", backdropFilter: "blur(12px)", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" },
  crumbs: { display: "flex", alignItems: "baseline", gap: 8, fontFamily: "var(--font-mono)", fontSize: 12 },
  crumbMute: { color: "var(--fg-3)" },
  crumb: { color: "var(--fg-1)" },
  crumbAcc: { color: "var(--accent)" },
  slash: { color: "var(--fg-4)" },
  actions: { display: "flex", gap: 8 },
  btn: { fontFamily: "var(--font-body)", fontSize: 12, height: 30, padding: "0 12px", borderRadius: "var(--radius-sm)", background: "var(--bg-2)", border: "1px solid var(--border)", color: "var(--fg-1)", cursor: "pointer" },
  btnP: { fontFamily: "var(--font-body)", fontSize: 12, height: 30, padding: "0 14px", borderRadius: "var(--radius-sm)", background: "var(--accent)", color: "var(--accent-fg)", border: 0, cursor: "pointer", fontWeight: 500 },
  content: { padding: 20, flex: 1 },
  // --- flow controls
  fcBar: { display: "flex", alignItems: "center", gap: 12, padding: 12, background: "var(--bg-1)", border: "1px solid var(--border)", borderRadius: "var(--radius-md)", flexWrap: "wrap" },
  fcGroup: { display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" },
  fcSpacer: { flex: "0 0 1px", height: 18, background: "var(--border)", margin: "0 4px" },
  fcLabel: { fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginRight: 4 },
  fallback: { padding: 40, textAlign: "center", fontFamily: "var(--font-mono)", color: "var(--fg-3)" },
};

window.OrgFlowsHero = OrgFlowsHero;
