// Layout primitives — sidebar, topbar, card, badges.
const { useState: uS, useEffect: uE, useMemo: uM, useRef: uR, useCallback: uC } = React;

// =================== Sidebar ===================
function Sidebar({ collapsed, onToggle, route, setRoute, plan = "Free", activeExchange = "binance", mode = "testnet" }) {
  const items = [
    { id: "dash",    label: "Dashboard",      Icon: IconHome },
    { id: "signals", label: "Signals",        Icon: IconSignal, badge: 3 },
    { id: "trades",  label: "Trade History",  Icon: IconList },
    { id: "risk",    label: "Risk & Guards",  Icon: IconShield },
    { id: "back",    label: "Backtester",     Icon: IconClock, soon: true },
    { id: "alerts",  label: "Alerts",         Icon: IconBell },
    { id: "logs",    label: "Logs",           Icon: IconTerm },
    { id: "build",   label: "Build & Roadmap",Icon: IconRocket },
    { id: "docs",    label: "Documentation",  Icon: IconLayers },
    { id: "set",     label: "Settings",       Icon: IconGear },
  ];
  const ex = EXCHANGES[activeExchange] || EXCHANGES.binance;
  const ExIcon = ex.Icon;
  const modeColor = mode === "live" ? "var(--loss)" : mode === "paper" ? "var(--info)" : "var(--warn)";
  const w = collapsed ? 72 : 240;
  return (
    <aside style={{
      width: w, flex: "0 0 " + w + "px", height: "100vh", position: "sticky", top: 0,
      borderRight: "1px solid var(--line)",
      background: "linear-gradient(180deg, rgba(15,19,32,0.6), rgba(7,9,15,0.6))",
      backdropFilter: "blur(20px)", display: "flex", flexDirection: "column",
      transition: "width .25s ease",
    }}>
      <div style={{ padding: collapsed ? "20px 0" : "22px 22px", display: "flex", alignItems: "center", gap: 10, justifyContent: collapsed ? "center" : "flex-start" }}>
        <div style={{ color: "var(--accent)" }}><IconLogo size={24} /></div>
        {!collapsed && (
          <div>
            <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: -0.2, lineHeight: 1 }}>Helix</div>
            <div style={{ fontSize: 10, color: "var(--text-3)", marginTop: 4, letterSpacing: 0.4, textTransform: "uppercase" }}>Auto-Trader v1.0</div>
          </div>
        )}
      </div>

      <nav style={{ padding: collapsed ? "8px" : "8px 12px", display: "flex", flexDirection: "column", gap: 2 }}>
        {items.map(({ id, label, Icon: I, badge, soon }) => {
          const active = route === id;
          return (
            <button key={id} onClick={() => setRoute(id)} className="focus-ring"
              style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: collapsed ? "10px" : "10px 12px",
                border: 0, borderRadius: 10, textAlign: "left",
                color: active ? "var(--text)" : "var(--text-2)",
                background: active ? "var(--accent-soft)" : "transparent",
                boxShadow: active ? "inset 0 0 0 1px " + "rgba(255,255,255,0.06)" : "none",
                fontSize: 14, justifyContent: collapsed ? "center" : "flex-start",
                transition: "background .15s, color .15s",
                cursor: "pointer",
              }}
              onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "rgba(255,255,255,0.04)"; }}
              onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}
            >
              <I size={18} />
              {!collapsed && <span style={{ flex: 1 }}>{label}</span>}
              {!collapsed && badge != null && (
                <span style={{ fontSize: 10, fontWeight: 600, padding: "2px 7px", borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent)" }}>{badge}</span>
              )}
              {!collapsed && soon && (
                <span style={{ fontSize: 9, fontWeight: 600, padding: "2px 6px", borderRadius: 4, background: "rgba(255,255,255,0.05)", color: "var(--text-3)", letterSpacing: 0.4, textTransform: "uppercase" }}>v2</span>
              )}
              {!collapsed && active && (
                <span style={{ width: 4, height: 18, background: "var(--accent)", borderRadius: 999 }} />
              )}
            </button>
          );
        })}
      </nav>

      {/* Bot status mini-card */}
      {!collapsed && (
        <div style={{
          margin: "8px 12px", padding: "12px 14px", borderRadius: 12,
          border: "1px solid var(--line)", background: "rgba(255,255,255,0.02)",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11, color: "var(--text-3)", letterSpacing: 0.4, textTransform: "uppercase", marginBottom: 8 }}>
            <span className="pulse-dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--profit)", color: "var(--profit)" }} />
            Bot online
          </div>
          <div style={{ fontSize: 12, color: "var(--text-2)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
              <span>Mode</span>
              <span style={{ color: modeColor, fontWeight: 600 }} className="mono">{mode.toUpperCase()}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
              <span>Exchange</span>
              <span style={{ color: "var(--text)", display: "inline-flex", alignItems: "center", gap: 5 }} className="mono">
                <ExIcon size={11} />{ex.name}
              </span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <span>Uptime</span>
              <span style={{ color: "var(--text)" }} className="mono">2d 03h</span>
            </div>
          </div>
        </div>
      )}

      <button onClick={onToggle} className="focus-ring"
        style={{
          margin: collapsed ? "auto 12px 12px" : "auto 16px 16px",
          padding: "8px 10px", borderRadius: 8, border: "1px solid var(--line)",
          background: "transparent", color: "var(--text-3)", display: "flex", alignItems: "center", gap: 6,
          justifyContent: "center", fontSize: 12,
        }}>
        <IconChevron size={14} style={{ transform: collapsed ? "none" : "scaleX(-1)" }} />
        {!collapsed && <span>Collapse</span>}
      </button>

      <div style={{
        margin: "0 12px 12px", padding: collapsed ? 8 : 14, borderRadius: 12,
        border: "1px solid var(--line)", background: "rgba(255,255,255,0.02)",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 32, height: 32, borderRadius: 10, flex: "0 0 32px",
            background: "linear-gradient(135deg, #00D4AA, #3B82F6)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontWeight: 600, fontSize: 13, color: "#0a0a0a",
          }}>AB</div>
          {!collapsed && (
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Amin Bassam</div>
              <div style={{ fontSize: 11, color: "var(--text-3)" }}>aminbassam@…</div>
            </div>
          )}
        </div>
      </div>
    </aside>
  );
}

// =================== Top bar ===================
function TopBar({ route, onNew, activeExchange = "binance" }) {
  const ex = EXCHANGES[activeExchange] || EXCHANGES.binance;
  const titles = {
    dash:    { eyebrow: "Overview",    title: "Dashboard" },
    signals: { eyebrow: "Webhooks",    title: "TradingView signals" },
    trades:  { eyebrow: "Execution",   title: "Trade history" },
    risk:    { eyebrow: "Safety",      title: "Risk & circuit breaker" },
    back:    { eyebrow: "Research",    title: "Backtester" },
    alerts:  { eyebrow: "Notifications", title: "Telegram alerts" },
    logs:    { eyebrow: "Diagnostics", title: "System logs" },
    build:   { eyebrow: "Project",     title: "Build & roadmap" },
    docs:    { eyebrow: "Reference",   title: "Documentation" },
    set:     { eyebrow: "Configuration", title: "Settings" },
  }[route] || { eyebrow: "Overview", title: "Dashboard" };

  return (
    <header style={{
      display: "flex", alignItems: "center", gap: 16,
      padding: "20px 32px", borderBottom: "1px solid var(--line)",
      background: "linear-gradient(180deg, rgba(15,19,32,0.4), transparent)",
      backdropFilter: "blur(8px)", position: "sticky", top: 0, zIndex: 5,
    }}>
      <div>
        <div style={{ fontSize: 11, color: "var(--text-3)", letterSpacing: 0.6, textTransform: "uppercase" }}>{titles.eyebrow}</div>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: -0.3 }}>{titles.title}</h1>
      </div>

      <div style={{ marginLeft: 32, position: "relative", width: 280 }}>
        <IconSearch size={16} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-3)" }} />
        <input placeholder="Search signals, trades, logs…" className="focus-ring"
          style={{
            width: "100%", padding: "9px 12px 9px 36px", borderRadius: 8,
            border: "1px solid var(--line)", background: "rgba(255,255,255,0.03)",
            color: "var(--text)", fontSize: 13, fontFamily: "inherit", outline: "none",
          }} />
        <kbd style={{
          position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
          fontSize: 10, padding: "2px 6px", borderRadius: 4, border: "1px solid var(--line)",
          color: "var(--text-3)", background: "rgba(255,255,255,0.04)", fontFamily: "JetBrains Mono",
        }}>⌘K</kbd>
      </div>

      <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
        <StatusPill label={ex.name} status="ok" Icon={ex.Icon} />
        <StatusPill label="TradingView" status="ok" />
        <StatusPill label="Telegram" status="ok" />

        <button className="focus-ring" style={{
          position: "relative", width: 38, height: 38, borderRadius: 10,
          border: "1px solid var(--line)", background: "rgba(255,255,255,0.02)",
          color: "var(--text-2)", display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <IconBell size={16} />
          <span style={{
            position: "absolute", top: 8, right: 8, width: 7, height: 7, borderRadius: 999,
            background: "var(--accent)", boxShadow: "0 0 0 2px var(--bg)",
          }} />
        </button>

        <button className="focus-ring" onClick={onNew} style={{
          padding: "10px 16px", borderRadius: 10, border: 0, background: "var(--accent)",
          color: "#06150F", fontWeight: 600, fontSize: 13, display: "flex", alignItems: "center", gap: 6,
          boxShadow: "0 0 0 1px rgba(0,212,170,0.25), 0 8px 24px -8px rgba(0,212,170,0.45)",
        }}>
          <IconBolt size={14} stroke={2.4} /> Emergency stop
        </button>
      </div>
    </header>
  );
}

function StatusPill({ label, status, Icon }) {
  const colors = { ok: "var(--profit)", warn: "var(--warn)", err: "var(--loss)" };
  const c = colors[status] || colors.ok;
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 7, padding: "7px 11px",
      borderRadius: 999, border: "1px solid var(--line)",
      background: "rgba(255,255,255,0.02)", fontSize: 11.5,
    }}>
      {Icon ? <Icon size={12} /> : <span className={status === "ok" ? "pulse-dot" : ""} style={{ width: 7, height: 7, borderRadius: 999, background: c, color: c }} />}
      <span style={{ color: "var(--text-2)" }}>{label}</span>
      {Icon && <span className={status === "ok" ? "pulse-dot" : ""} style={{ width: 6, height: 6, borderRadius: 999, background: c, color: c }} />}
    </div>
  );
}

// =================== Card primitive ===================
function Card({ title, subtitle, right, children, padded = true, style }) {
  return (
    <section style={{
      background: "linear-gradient(180deg, rgba(20,26,42,0.6), rgba(15,19,32,0.6))",
      border: "1px solid var(--line)", borderRadius: 16,
      boxShadow: "inset 0 1px 0 rgba(255,255,255,0.03), 0 1px 0 rgba(0,0,0,0.4)",
      overflow: "hidden", display: "flex", flexDirection: "column", minWidth: 0,
      ...style,
    }}>
      {(title || right) && (
        <div style={{
          display: "flex", alignItems: "center", gap: 12,
          padding: "18px var(--pad) 0", marginBottom: 4,
        }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            {title && <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: -0.1 }}>{title}</div>}
            {subtitle && <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>{subtitle}</div>}
          </div>
          {right}
        </div>
      )}
      <div style={{ padding: padded ? "16px var(--pad) var(--pad)" : 0, flex: 1, minWidth: 0 }}>
        {children}
      </div>
    </section>
  );
}

function Badge({ children, variant = "default" }) {
  const styles = {
    default: { bg: "rgba(255,255,255,0.06)", fg: "var(--text-2)" },
    accent:  { bg: "var(--accent-soft)", fg: "var(--accent)" },
    profit:  { bg: "rgba(25,229,166,0.14)", fg: "var(--profit)" },
    loss:    { bg: "rgba(242,63,92,0.14)", fg: "#FCA5A5" },
    warn:    { bg: "rgba(245,166,35,0.14)", fg: "#FBBF24" },
    info:    { bg: "rgba(96,165,250,0.14)", fg: "#93C5FD" },
  }[variant] || { bg: "rgba(255,255,255,0.06)", fg: "var(--text-2)" };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      padding: "3px 9px", borderRadius: 999,
      fontSize: 11, fontWeight: 500,
      background: styles.bg, color: styles.fg, lineHeight: 1.4,
    }}>{children}</span>
  );
}

function StatusDot({ status }) {
  const map = {
    Running: { c: "var(--profit)", pulse: true },
    Paused:  { c: "var(--warn)", pulse: false },
    Error:   { c: "var(--loss)", pulse: false },
    Idle:    { c: "var(--text-3)", pulse: false },
  };
  const s = map[status] || map.Idle;
  return <span className={s.pulse ? "pulse-dot" : ""} style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: s.c, color: s.c }} />;
}

// Section header inside a page (for non-card sections)
function PageSection({ title, subtitle, right, children }) {
  return (
    <section style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 12 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h2 style={{ margin: 0, fontSize: 15, fontWeight: 600, letterSpacing: -0.2 }}>{title}</h2>
          {subtitle && <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>{subtitle}</div>}
        </div>
        {right}
      </div>
      {children}
    </section>
  );
}

// Reusable input row
function FieldRow({ label, hint, children, danger }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(180px, 1fr) minmax(0, 2fr)", gap: 24, padding: "16px 0", borderBottom: "1px solid var(--line)" }}>
      <div>
        <div style={{ fontSize: 13, fontWeight: 500, color: danger ? "var(--loss)" : "var(--text)" }}>{label}</div>
        {hint && <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 4, lineHeight: 1.5 }}>{hint}</div>}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6, justifyContent: "center" }}>{children}</div>
    </div>
  );
}

// Compact input
function TextInput({ value, onChange, placeholder, mono, type = "text", suffix, style }) {
  return (
    <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
      <input value={value} onChange={(e) => onChange && onChange(e.target.value)}
        placeholder={placeholder} type={type} className="focus-ring"
        style={{
          width: "100%", padding: suffix ? "9px 70px 9px 12px" : "9px 12px", borderRadius: 8,
          border: "1px solid var(--line-strong)", background: "rgba(255,255,255,0.03)",
          color: "var(--text)", fontSize: 13, fontFamily: mono ? "JetBrains Mono" : "inherit",
          outline: "none", ...style,
        }} />
      {suffix && (
        <span style={{ position: "absolute", right: 12, fontSize: 11, color: "var(--text-3)", fontFamily: "JetBrains Mono" }}>{suffix}</span>
      )}
    </div>
  );
}

function Toggle({ value, onChange, label }) {
  return (
    <label style={{ display: "inline-flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
      <span onClick={() => onChange && onChange(!value)} style={{
        width: 36, height: 20, borderRadius: 999,
        background: value ? "var(--accent)" : "rgba(255,255,255,0.10)",
        position: "relative", transition: "background .2s",
      }}>
        <span style={{
          position: "absolute", top: 2, left: value ? 18 : 2, width: 16, height: 16, borderRadius: 999,
          background: "#fff", transition: "left .2s", boxShadow: "0 1px 3px rgba(0,0,0,0.3)",
        }} />
      </span>
      {label && <span style={{ fontSize: 13, color: "var(--text-2)" }}>{label}</span>}
    </label>
  );
}

function PrimaryBtn({ children, onClick, icon, danger, ghost, style }) {
  const bg = danger ? "var(--loss)" : ghost ? "rgba(255,255,255,0.04)" : "var(--accent)";
  const fg = danger ? "#fff" : ghost ? "var(--text)" : "#06150F";
  const bd = ghost ? "1px solid var(--line-strong)" : "0";
  return (
    <button onClick={onClick} className="focus-ring" style={{
      padding: "9px 16px", borderRadius: 8, border: bd, background: bg, color: fg,
      fontWeight: 600, fontSize: 13, display: "inline-flex", alignItems: "center", gap: 6, ...style,
    }}>
      {icon}{children}
    </button>
  );
}

function IconBtn({ children, title, onClick, danger }) {
  return (
    <button title={title} onClick={onClick} className="focus-ring" style={{
      width: 28, height: 28, borderRadius: 7, border: "1px solid var(--line)",
      background: "rgba(255,255,255,0.02)", color: danger ? "var(--loss)" : "var(--text-2)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      transition: "all .15s",
    }}
    onMouseEnter={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.06)"; e.currentTarget.style.color = danger ? "var(--loss)" : "var(--text)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.background = "rgba(255,255,255,0.02)"; e.currentTarget.style.color = danger ? "var(--loss)" : "var(--text-2)"; }}
    >{children}</button>
  );
}

const th = (align) => ({
  padding: "10px 12px", textAlign: align || "left",
  fontWeight: 500, fontSize: 11,
});
const td = (align) => ({
  padding: "14px 12px", textAlign: align || "left", verticalAlign: "middle",
});

Object.assign(window, {
  Sidebar, TopBar, StatusPill, Card, Badge, StatusDot,
  PageSection, FieldRow, TextInput, Toggle, PrimaryBtn, IconBtn, th, td,
});
