// Sidebar + Topbar

const NAV_ITEMS = [
  { id: "dashboard", label: "Dashboard", icon: Icons.Dashboard },
  { id: "portfolio", label: "Portfolio", icon: Icons.Portfolio },
  { id: "planner",   label: "Exit Planner", icon: Icons.Planner },
  { id: "simulator", label: "Simulator", icon: Icons.Simulator },
  { id: "regret",    label: "Regret Sim", icon: Icons.Regret },
  { id: "reports",   label: "Reports", icon: Icons.Reports },
  { id: "settings",  label: "Settings", icon: Icons.Settings },
];

function Sidebar({ current, onChange, mobileOpen, onMobileClose }) {
  const { state } = useStore();
  const collapsed = false;
  return (
    <>
      <aside className={`exos-sidebar ${mobileOpen ? "open" : ""}`}>
        <div className="exos-sidebar-brand">
          <div className="exos-brand-mark">
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              <path d="M3 3 L19 19" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
              <path d="M19 3 L12 10" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
              <path d="M3 19 L7 15" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
              <circle cx="12" cy="10" r="1.4" fill="var(--accent)" />
            </svg>
          </div>
          <div className="exos-brand-text">
            <div className="exos-brand-name">EXITOS</div>
            <div className="exos-brand-sub mono">v1.0 · local</div>
          </div>
        </div>

        <nav className="exos-nav">
          {NAV_ITEMS.map(item => {
            const Ico = item.icon;
            return (
              <button key={item.id}
                className={`exos-nav-item ${current === item.id ? "active" : ""}`}
                onClick={() => { onChange(item.id); onMobileClose?.(); }}>
                <span className="exos-nav-icon"><Ico size={16} /></span>
                <span>{item.label}</span>
                {item.id === "regret" && <span className="exos-nav-tag accent">moat</span>}
              </button>
            );
          })}
        </nav>

        <div className="exos-sidebar-foot">
          <div className="exos-foot-card">
            <div className="exos-foot-title">
              <Icons.Shield size={14} />
              <span>Stored locally</span>
            </div>
            <p className="exos-foot-text">Your portfolio lives in this browser only. Nothing is uploaded.</p>
          </div>
        </div>
      </aside>
      {mobileOpen && <div className="exos-sidebar-scrim" onClick={onMobileClose} />}
    </>
  );
}

function Topbar({ onMenu, onNavigate }) {
  const { state, prices } = useStore();
  const portfolio = React.useMemo(() => computePortfolio(state, prices), [state, prices]);
  const last = state.lastSavedAt;
  const [_, setTick] = React.useState(0);
  React.useEffect(() => { const id = setInterval(()=>setTick(t=>t+1), 30000); return ()=>clearInterval(id); }, []);
  const savedLabel = last ? `saved ${ago(last)}` : "·";

  return (
    <header className="exos-topbar">
      <button className="exos-icon-btn exos-mobile-only" onClick={onMenu}><Icons.Menu size={18} /></button>
      <div className="exos-topbar-summary">
        <div className="exos-topbar-stat">
          <span className="exos-label">Portfolio</span>
          <span className="mono" style={{ fontWeight: 500 }}>
            <Ticker value={portfolio.total} format={v => fmtCurrency(v, state.settings.currency, { compact: true })} flash={false} />
          </span>
        </div>
        <div className="exos-topbar-stat">
          <span className="exos-label">P/L</span>
          <span className="mono" style={{ color: portfolio.pnl >= 0 ? "var(--gain)" : "var(--loss)" }}>
            {fmtPct(portfolio.pnlPct)}
          </span>
        </div>
        <div className="exos-topbar-stat exos-hide-sm">
          <span className="exos-label">Holdings</span>
          <span className="mono">{portfolio.rows.length}</span>
        </div>
      </div>
      <div className="exos-spacer" />
      <div className="exos-topbar-actions">
        <span className="exos-saved mono">{savedLabel}</span>
        <Pill dot tone="gain" className="exos-hide-sm">LIVE</Pill>
      </div>
    </header>
  );
}

function ago(ts) {
  const s = Math.floor((Date.now() - ts) / 1000);
  if (s < 5) return "just now";
  if (s < 60) return `${s}s ago`;
  if (s < 3600) return `${Math.floor(s/60)}m ago`;
  return `${Math.floor(s/3600)}h ago`;
}

const SIDEBAR_STYLES = `
.exos-sidebar {
  background: var(--bg);
  border-right: 1px solid var(--line);
  display: flex; flex-direction: column;
  position: sticky; top: 0; height: 100vh;
  padding: 18px 12px 14px;
}
.exos-sidebar-brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 22px; }
.exos-brand-mark { width: 30px; height: 30px; display: grid; place-items: center; background: var(--bg-elev); border: 1px solid var(--line); border-radius: 8px; color: var(--text); }
.exos-brand-name { font-family: "Geist Mono", monospace; font-size: 13px; font-weight: 600; letter-spacing: 0.06em; }
.exos-brand-sub { font-size: 10px; color: var(--text-dim); letter-spacing: 0.08em; text-transform: uppercase; }

.exos-nav { display: flex; flex-direction: column; gap: 1px; }
.exos-nav-item {
  display: flex; align-items: center; gap: 10px;
  padding: 7px 10px; border-radius: 7px;
  font-size: 13px; color: var(--text-mute);
  background: transparent; border: 0; text-align: left; width: 100%; cursor: pointer;
  transition: background .12s, color .12s;
  font-weight: 500;
  white-space: nowrap; min-width: 0;
}
.exos-nav-item > span:not(.exos-nav-icon):not(.exos-nav-tag) { overflow: hidden; text-overflow: ellipsis; }
.exos-nav-item:hover { background: var(--bg-elev); color: var(--text); }
.exos-nav-item.active { background: var(--bg-elev); color: var(--text); }
.exos-nav-item.active .exos-nav-icon { color: var(--accent); }
.exos-nav-icon { display: inline-flex; color: var(--text-mute); transition: color .12s; width: 18px; }
.exos-nav-item:hover .exos-nav-icon { color: var(--text); }
.exos-nav-tag { margin-left: auto; font-size: 9px; letter-spacing: 0.1em; text-transform: uppercase; padding: 2px 6px; border-radius: 4px; background: var(--accent-soft); color: var(--accent); font-family: "Geist Mono", monospace; font-weight: 500; }

.exos-sidebar-foot { margin-top: auto; padding-top: 14px; }
.exos-foot-card { background: var(--bg-elev); border: 1px solid var(--line); border-radius: 10px; padding: 11px 12px; }
.exos-foot-title { display: flex; align-items: center; gap: 7px; font-size: 12px; font-weight: 500; color: var(--text); margin-bottom: 4px; }
.exos-foot-text { margin: 0; font-size: 11px; color: var(--text-mute); line-height: 1.45; }

.exos-topbar {
  display: flex; align-items: center; gap: 18px;
  padding: 12px 32px;
  padding-top: max(12px, env(safe-area-inset-top));
  border-bottom: 1px solid var(--line);
  background: var(--bg);
  position: sticky; top: 0; z-index: 10;
  backdrop-filter: blur(8px);
  background: oklch(from var(--bg) l c h / 0.85);
}
.exos-topbar-summary { display: flex; gap: 22px; align-items: center; }
.exos-topbar-stat { display: flex; flex-direction: column; gap: 1px; line-height: 1.2; }
.exos-topbar-stat .exos-label { font-size: 9px; }
.exos-topbar-actions { display: flex; align-items: center; gap: 12px; }
.exos-saved { font-size: 11px; color: var(--text-dim); }

.exos-mobile-only { display: none; }
.exos-sidebar-scrim { display: none; }

@media (max-width: 880px) {
  .exos-sidebar {
    position: fixed; left: 0; top: 0; bottom: 0; width: min(280px, 85vw); z-index: 50;
    transform: translateX(-100%); transition: transform .25s;
    border-right: 1px solid var(--line);
    padding-top: max(18px, env(safe-area-inset-top));
    padding-bottom: max(14px, env(safe-area-inset-bottom));
    -webkit-overflow-scrolling: touch;
  }
  .exos-sidebar.open { transform: none; box-shadow: var(--shadow-lg); }
  .exos-sidebar-scrim { display: block; position: fixed; inset: 0; background: oklch(0 0 0 / 0.5); z-index: 40; }
  .exos-mobile-only { display: inline-grid; }
  .exos-topbar { padding: 12px 16px; padding-top: max(12px, env(safe-area-inset-top)); gap: 12px; }
  .exos-hide-sm { display: none !important; }
  /* iOS: bigger hit targets on mobile */
  .exos-nav-item { padding: 11px 12px; font-size: 14px; }
  .exos-nav-icon { width: 20px; }
  .exos-icon-btn { width: 36px; height: 36px; }
  .exos-btn.sm { padding: 7px 10px; font-size: 12px; min-height: 32px; }
  .exos-btn.md { padding: 9px 14px; min-height: 38px; }
}
`;
(function(){ if (document.getElementById("exos-sidebar-styles")) return; const t = document.createElement("style"); t.id="exos-sidebar-styles"; t.textContent = SIDEBAR_STYLES; document.head.appendChild(t); })();

Object.assign(window, { Sidebar, Topbar, NAV_ITEMS });
