/* simple/app.jsx — the redesigned shell.
   Three tabs: HOME (see) · YOSHI (act) · ACTIVITY (verify).
   Proposals still flow through the ConfirmSheet primitive. Move and Trade
   open the ORIGINAL TransferFlow / TradeSheet, wired in through a push
   stack + the overlay set they expect, so they work exactly as before.
   The bell (top-right of Home) opens the original BriefsHub. */

const StatusBar = () => (
  <div className="statusbar">
    <span>9:41</span>
    <div className="sb-right">
      <svg width="18" height="12" viewBox="0 0 18 12"><g fill="currentColor">
        <rect x="0" y="8" width="3" height="4" /><rect x="5" y="5" width="3" height="7" /><rect x="10" y="2" width="3" height="10" /><rect x="15" y="0" width="3" height="12" />
      </g></svg>
      <svg width="16" height="12" viewBox="0 0 16 12" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M2 4 C5 1.5 11 1.5 14 4" /><path d="M4 6.5 C6 5 10 5 12 6.5" /><circle cx="8" cy="9.5" r="0.9" fill="currentColor" stroke="none" /></svg>
      <svg width="26" height="13" viewBox="0 0 26 13"><rect x="0.5" y="0.5" width="22" height="12" rx="3" fill="none" stroke="currentColor" strokeOpacity="0.5" /><rect x="2" y="2" width="18" height="9" rx="1.5" fill="currentColor" /><rect x="23.5" y="4" width="2" height="5" rx="1" fill="currentColor" fillOpacity="0.5" /></svg>
    </div>
  </div>
);
window.StatusBar = StatusBar;

const Toast = ({ msg }) => (
  <div style={{ position: "absolute", left: 16, right: 16, bottom: 0, zIndex: 350, background: "var(--terminal-fill)", color: "var(--terminal-ink)", padding: "12px 15px", display: "flex", alignItems: "center", gap: 9, animation: "count-up 240ms ease both", boxShadow: "0 8px 30px -10px rgba(0,0,0,0.5)" }}>
    <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--accent)", flex: "none" }} />
    <span style={{ fontFamily: "var(--f-display)", fontSize: typeSize(13), fontWeight: 500 }}>{msg}</span>
  </div>
);

const SIMPLE_TABS = [["home", "Home", "home"], ["yoshi", "Yoshi", null], ["activity", "Activity", "inbox"]];

const SimpleTabBar = ({ tab, onTab, badge }) => (
  <div className="tabbar" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
    {SIMPLE_TABS.map(([id, label, icon]) => {
      const on = id === tab;
      if (id === "yoshi") return (
        <button key={id} className="tab press" onClick={() => onTab(id)} style={{ overflow: "visible" }}>
          <span style={{
            position: "absolute", top: -26, left: "50%", transform: "translateX(-50%)",
            width: 58, height: 58, borderRadius: 999, background: "var(--bg-card)",
            border: on ? "1.5px solid var(--accent)" : "1px solid var(--rule)",
            boxShadow: "0 8px 22px -8px rgba(0,0,0,0.32), 0 2px 6px -2px rgba(0,0,0,0.18)",
            display: "grid", placeItems: "center",
          }}>
            <Logo size={26} />
          </span>
          <span className="tlabel" style={{ marginTop: 34, color: on ? "var(--ink)" : "var(--ink-3)", fontWeight: on ? 700 : 500 }}>{label}</span>
        </button>
      );
      return (
        <button key={id} className="tab press" onClick={() => onTab(id)}>
          {on && <span style={{ position: "absolute", top: -9, left: "50%", transform: "translateX(-50%)", width: 18, height: 2, background: "var(--accent)" }} />}
          <div style={{ position: "relative", height: 23, display: "flex", alignItems: "center" }}>
            <Icon name={icon} size={23} stroke={on ? 1.7 : 1.5} color={on ? "var(--ink)" : "var(--ink-3)"} />
          </div>
          <span className="tlabel" style={{ color: on ? "var(--ink)" : "var(--ink-3)", fontWeight: on ? 700 : 500 }}>{label}</span>
        </button>
      );
    })}
  </div>
);

const SimpleApp = () => {
  const [onboarded, setOnboarded] = useState(() => localStorage.getItem("yoshi_onboarded") === "1");
  const [palette, setPaletteState] = useState(() => localStorage.getItem("yoshi_palette") || "graphite");
  const [tab, setTab] = useState("home");
  const [stack, setStack] = useState([]);           // push stack: holding / account / card
  const [overlay, setOverlay] = useState(null);     // full-screen sheets
  const [confirming, setConfirming] = useState(null); // action in the ConfirmSheet
  const [proposals, setProposals] = useState(PROPOSALS);
  const [activityExtra, setActivityExtra] = useState([]);
  const [toast, setToast] = useState(null);
  const [chatInject, setChatInject] = useState(null);
  const [hasCard, setHasCard] = useState(() => localStorage.getItem("yoshi_card") === "1");

  useEffect(() => { document.getElementById("root").setAttribute("data-palette", palette); }, [palette]);
  useEffect(() => { window.setBellCount && window.setBellCount(window.totalBriefCount ? window.totalBriefCount(proposals.length) : proposals.length); }, [proposals]);
  const setPalette = (p) => { setPaletteState(p); localStorage.setItem("yoshi_palette", p); };
  const flash = (msg) => { setToast(msg); setTimeout(() => setToast((t) => (t === msg ? null : t)), 2600); };
  const getCard = () => { localStorage.setItem("yoshi_card", "1"); setHasCard(true); };

  const nav = useMemo(() => ({
    tab: (t) => { setStack([]); setOverlay(null); setConfirming(null); setTab(t); },
    sheet: (o) => setOverlay(o),
    closeSheet: () => setOverlay(null),
    push: (v) => setStack((s) => [...s, v]),
    pop: () => setStack((s) => s.slice(0, -1)),
    clearStack: () => setStack([]),
    // selecting a security: on phone, a held security opens its detail; a
    // market-only security opens the trade flow (unchanged mobile behavior)
    security: (id) => (typeof securityHolding === "function" && securityHolding(id)) ? setStack((s) => [...s, { type: "holding", id }]) : setOverlay({ type: "trade", id }),
    ask: (note, reply) => { setChatInject({ note, reply }); setStack([]); setOverlay(null); setConfirming(null); setTab("yoshi"); },
    automation: (id) => { setStack([]); setOverlay({ type: "automation", id }); },
    // Studio was retired in the redesign; its deep-links resolve to the
    // automations list (the one place a Studio "automate" call still maps to).
    studio: (view) => { setOverlay(view === "automations" ? { type: "automations" } : null); if (view !== "automations") nav.ask("Show me the markets", "Ask me about anything you hold or want to research — I'll pull the chart, the comparison, or the trade right here."); },
    accountsRoot: () => { setOverlay(null); setStack([]); setTab("home"); },
    openAccount: () => flash("Opening an account — out of prototype scope"),
    signOut: () => { localStorage.removeItem("yoshi_onboarded"); setOnboarded(false); setTab("home"); setStack([]); setOverlay(null); setConfirming(null); setProposals(PROPOSALS); setActivityExtra([]); },
  }), []);

  const findProp = (id) => proposals.find((p) => p.id === id) || PROPOSALS.find((p) => p.id === id);

  /* both doors of the ConfirmSheet end here — a completed action lands in Activity */
  const onExecuted = (a) => {
    if (a.activity) setActivityExtra((xs) => [{ ...a.activity, id: "x" + Date.now(), when: "Just now" }, ...xs]);
    if (a.id) setProposals((ps) => ps.filter((p) => p.id !== a.id));
    setConfirming(null);
    flash((a.kind === "automation" ? "Scheduled · " : "Executed · ") + a.title);
  };
  const onDeclined = (a, reason) => {
    if (a.id) setProposals((ps) => ps.filter((p) => p.id !== a.id));
    setConfirming(null);
    flash("Declined · " + reason);
  };
  const review = (p) => p && setConfirming({
    ...p,
    activity: p.activity || { icon: p.kind === "trade" ? "trade" : "swap", title: p.title, detail: p.legs.map((l) => l[1] && typeof l[1] === "object" ? l[1].ticker : l[1]).filter(Boolean).slice(0, 2).join(" · "), category: p.kind === "trade" ? "Investment" : "Transfer", by: p.agent, net: p.net },
  });
  const askAboutProposal = (a, text) => {
    setConfirming(null);
    const q = text && text.trim() ? text.trim() : `Question about "${a.title}"`;
    nav.ask(q, `Sure — ${a.why || "here's the thinking."} The short version: it moves you toward the mix you set, inside your limits, and nothing runs until you approve. What would you like changed?`);
  };

  if (!onboarded) {
    return (
      <ThemeCtx.Provider value={palette}>
        <StatusBar />
        <Onboarding onDone={() => { localStorage.setItem("yoshi_onboarded", "1"); setOnboarded(true); }} />
      </ThemeCtx.Provider>
    );
  }

  const screen = {
    home: <HomeTab nav={nav} proposals={proposals} onReview={review} />,
    yoshi: <YoshiTab nav={nav} proposals={proposals} onReview={review} inject={chatInject} onInjected={() => setChatInject(null)} flash={flash} />,
    activity: <ActivityTab nav={nav} extra={activityExtra} />,
  }[tab];

  const hideTabBar = !!overlay || !!confirming || stack.length > 0 || tab === "yoshi";

  return (
    <ThemeCtx.Provider value={palette}>
      <StatusBar />
      <div className="viewport">
        <div key={tab} className="tab-swap" style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column" }}>
          {screen}
        </div>

        {/* push stack — original holding / account / card detail screens */}
        {stack.map((v, i) => (
          <div key={i} className="push-enter" style={{ position: "absolute", inset: 0, background: "var(--bg)", display: "flex", flexDirection: "column", zIndex: 400 + i }}>
            {v.type === "holding" && <HoldingDetail id={v.id} nav={nav} />}
            {v.type === "account" && <AccountDetail acct={v.acct} nav={nav} />}
            {v.type === "card" && <CardDetail nav={nav} flash={flash} hasCard={hasCard} onGetCard={getCard} />}
          </div>
        ))}

        {toast && <Toast msg={toast} />}
      </div>

      {!hideTabBar && <SimpleTabBar tab={tab} onTab={nav.tab} badge={proposals.length} />}

      {/* the confirm primitive — proposal review + manual actions */}
      {confirming && (
        <ConfirmSheet action={confirming} onClose={() => setConfirming(null)}
          onApproved={onExecuted} onDeclined={onDeclined} onAsk={askAboutProposal} />
      )}

      {/* redesigned layers */}
      {overlay?.type === "profile" && <ProfileSheet palette={palette} setPalette={setPalette} nav={nav} onClose={nav.closeSheet} flash={flash} />}
      {overlay?.type === "holding" && <HoldingView id={overlay.id} nav={nav} onClose={nav.closeSheet} />}
      {overlay?.type === "holdings" && <HoldingsDetailSheet nav={nav} onClose={nav.closeSheet} />}
      {overlay?.type === "accounts" && <AccountsSheet nav={nav} onClose={nav.closeSheet} />}
      {overlay?.type === "receipt" && <ReceiptSheet tx={overlay.tx} nav={nav} onClose={nav.closeSheet} />}
      {overlay?.type === "automations" && <AutomationsListSheet nav={nav} onClose={nav.closeSheet} />}

      {/* original flows — kept exactly as they were */}
      {overlay?.type === "transfer" && <TransferFlow preset={overlay.from} intent={overlay.intent} initialRail={overlay.rail} rootTitle="Move" onClose={nav.closeSheet} nav={nav} flash={flash} />}
      {overlay?.type === "trade" && <TradeSheet id={overlay.id} side={overlay.side} hideMenu onClose={nav.closeSheet} nav={nav} />}
      {overlay?.type === "txn" && <TxnDetailSheet tx={overlay.tx} onClose={nav.closeSheet} nav={nav} />}
      {overlay?.type === "link" && <LinkSheet onClose={nav.closeSheet} />}
      {overlay?.type === "connect" && <ConnectAgentsSheet onClose={nav.closeSheet} nav={nav} />}
      {overlay?.type === "support" && <SupportFlow onClose={nav.closeSheet} nav={nav} />}
      {overlay?.type === "documents" && <DocumentsHub onClose={nav.closeSheet} nav={nav} flash={flash} initialAcct={overlay.acct} />}
      {overlay?.type === "briefs" && <BriefsHub onClose={nav.closeSheet} nav={nav} proposals={proposals} onApprove={(id) => { setOverlay(null); review(findProp(id)); }} initialBriefId={overlay.brief} initialBrief={overlay.briefData} />}
      {overlay?.type === "automation" && <AutomationSheet automation={AUTOMATIONS.find((a) => a.id === overlay.id)} onClose={nav.closeSheet} nav={nav} flash={flash} />}
    </ThemeCtx.Provider>
  );
};

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