// mailroom-shell.jsx — global chrome: ink-blue top status bar + collapsible left
// rail + right-side drawer + page header. Exports: TopBar, LeftRail, Drawer,
// PageHeader, AppShell.

const NAV = [
  { id: "dashboard", icon: "grid", label: "Mission Control" },
  { id: "campaigns", icon: "campaigns", label: "Campaigns" },
  { id: "replies", icon: "replies", label: "Replies", badge: 6 },
  { id: "suppression", icon: "ban", label: "Suppression" },
  { id: "domains", icon: "server", label: "Domains & Mailboxes" },
  { id: "analytics", icon: "analytics", label: "Analytics" },
  { id: "settings", icon: "settings", label: "Settings" },
];

/* ---------------- Top status bar (ink-blue console, 40px) ---------------- */
function TopBar({ pipeline = "running", awaiting = 3, warmHeat = 84, suppression = 1284, setView }) {
  const t = useT();
  const lineDim = hexA("#ffffff", 0.12);
  const seg = (children, onClick) => (
    <div onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 7, padding: "0 14px",
      height: "100%", borderLeft: `1px solid ${lineDim}`, cursor: onClick ? "pointer" : "default" }}>{children}</div>
  );
  const heatColor = warmHeat >= 80 ? t.good : warmHeat >= 45 ? t.warn : t.bad;
  const pipeMap = {
    running: { tone: "good", label: "running", pulse: true },
    paused: { tone: "warn", label: "paused", pulse: false },
    awaiting: { tone: "marker", label: "awaiting approval", pulse: true },
  };
  const pip = pipeMap[pipeline] || pipeMap.running;
  return (
    <div style={{ display: "flex", alignItems: "center", height: 40, flex: "0 0 auto",
      background: t.console, color: t.consoleText, fontFamily: t.font,
      borderBottom: `1px solid ${t.dark ? t.border : "#0b1424"}` }}>
      {/* wordmark */}
      <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "0 14px 0 16px" }}>
        <span style={{ width: 18, height: 18, borderRadius: 4, background: t.accent, display: "flex",
          alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
          <Icon name="mail" size={11} color="#fff" sw={2.2} />
        </span>
        <span style={{ fontFamily: t.head, fontWeight: 700, fontSize: 14, letterSpacing: "-.01em" }}>Mailroom</span>
      </div>
      {/* live pipeline pill */}
      {seg(
        <>
          <span style={{ width: 6, height: 6, borderRadius: 999, background:
            pip.tone === "good" ? t.good : pip.tone === "warn" ? t.warn : t.marker,
            animation: pip.pulse ? "mrPulse 1.4s ease-in-out infinite" : "none" }} />
          <span style={{ fontSize: 11.5, color: t.consoleMuted }}>pipeline</span>
          <span style={{ fontFamily: t.mono, fontSize: 12, fontWeight: 700, color: t.consoleText }}>{pip.label}</span>
        </>
      )}
      {/* awaiting approval count */}
      {seg(
        <>
          <Icon name="flag" size={13} color={awaiting ? t.marker : t.consoleMuted} />
          <span style={{ fontSize: 11.5, color: t.consoleMuted }}>awaiting you</span>
          <span style={{ fontFamily: t.mono, fontSize: 12, fontWeight: 700,
            color: awaiting ? t.marker : t.consoleText }}>{String(awaiting).padStart(2, "0")}</span>
        </>,
        () => setView && setView("dashboard")
      )}
      <div style={{ flex: 1 }} />
      {/* warmup heat */}
      {seg(
        <>
          <Icon name="flame" size={13} color={heatColor} />
          <span style={{ fontSize: 11.5, color: t.consoleMuted }}>warmup</span>
          <span style={{ fontFamily: t.mono, fontSize: 12, fontWeight: 700, color: heatColor }}>{warmHeat}</span>
          <span style={{ display: "flex", gap: 1.5, marginLeft: 2 }}>
            {[0, 1, 2, 3, 4].map((i) => (
              <span key={i} style={{ width: 3, height: 11, borderRadius: 1,
                background: i < Math.round(warmHeat / 20) ? heatColor : hexA("#fff", 0.16) }} />
            ))}
          </span>
        </>
      )}
      {/* suppression */}
      {seg(
        <>
          <Icon name="ban" size={13} color={t.consoleMuted} />
          <span style={{ fontSize: 11.5, color: t.consoleMuted }}>suppressed</span>
          <span style={{ fontFamily: t.mono, fontSize: 12, fontWeight: 700, color: t.consoleText }}>{suppression.toLocaleString()}</span>
        </>,
        () => setView && setView("suppression")
      )}
      {/* settings */}
      <div style={{ borderLeft: `1px solid ${lineDim}`, height: "100%", display: "flex", alignItems: "center", padding: "0 8px" }}>
        <button onClick={() => setView && setView("settings")} title="Settings" style={{ width: 28, height: 28, borderRadius: 5,
          border: "none", background: "transparent", color: t.consoleMuted, cursor: "pointer", display: "flex",
          alignItems: "center", justifyContent: "center" }}>
          <Icon name="settings" size={16} />
        </button>
      </div>
    </div>
  );
}

/* ---------------- Left rail (collapsible) ---------------- */
function LeftRail({ view, setView, onNew, collapsed, setCollapsed }) {
  const t = useT();
  const W = collapsed ? 60 : 232;
  const item = (n) => {
    const on = view === n.id;
    return (
      <button key={n.id} onClick={() => setView(n.id)} title={collapsed ? n.label : undefined} style={{
        display: "flex", alignItems: "center", gap: 11, width: "100%", textAlign: "left",
        height: 40, padding: collapsed ? 0 : "0 11px", justifyContent: collapsed ? "center" : "flex-start",
        borderRadius: t.radiusSm, cursor: "pointer", border: "1px solid transparent",
        fontFamily: t.font, fontSize: 13.5, fontWeight: on ? 650 : 500,
        background: on ? t.card : "transparent", color: on ? t.text : t.textSec,
        boxShadow: on ? `inset 0 0 0 1px ${t.border}` : "none", position: "relative", transition: "all .1s",
      }}>
        {on && <span style={{ position: "absolute", left: collapsed ? 4 : -7, top: "50%", transform: "translateY(-50%)",
          width: 3, height: 20, borderRadius: 2, background: t.accent }} />}
        <Icon name={n.icon} size={18} color={on ? t.accent : t.textMuted} sw={on ? 1.95 : 1.6} />
        {!collapsed && <span style={{ flex: 1 }}>{n.label}</span>}
        {!collapsed && n.badge != null && (
          <span style={{ fontFamily: t.mono, fontSize: 10.5, fontWeight: 700, padding: "1px 6px",
            borderRadius: 999, background: on ? t.accent : t.markerTint, color: on ? "#fff" : t.markerInk,
            border: on ? "none" : `1px solid ${t.markerBorder}`, minWidth: 18, textAlign: "center" }}>{n.badge}</span>
        )}
        {collapsed && n.badge != null && (
          <span style={{ position: "absolute", top: 5, right: 8, width: 7, height: 7, borderRadius: 999,
            background: t.accent, border: `1.5px solid ${t.bg}` }} />
        )}
      </button>
    );
  };
  return (
    <aside style={{ width: W, flex: `0 0 ${W}px`, background: t.bg, borderRight: `1px solid ${t.border}`,
      display: "flex", flexDirection: "column", height: "100%", transition: "width .16s", overflow: "hidden" }}>
      {/* workspace */}
      <div style={{ padding: collapsed ? "12px 0" : "12px 14px 10px", display: "flex", alignItems: "center",
        gap: 10, justifyContent: collapsed ? "center" : "flex-start" }}>
        <div style={{ width: 30, height: 30, borderRadius: 7, background: t.console, color: t.consoleText,
          display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 14,
          fontFamily: t.mono, flex: "0 0 auto" }}>M</div>
        {!collapsed && (
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: t.text, lineHeight: 1.15, fontFamily: t.head }}>igtre.studio</div>
            <div style={{ fontSize: 11, color: t.textMuted, lineHeight: 1.3, fontFamily: t.mono }}>solo operator</div>
          </div>
        )}
      </div>

      <div style={{ padding: collapsed ? "4px 10px 10px" : "4px 14px 12px" }}>
        {collapsed
          ? <IconBtn icon="plus" onClick={onNew} style={{ width: "100%", background: t.accent, color: "#fff", height: 38 }} />
          : <Btn kind="primary" icon="plus" full onClick={onNew}>New campaign</Btn>}
      </div>

      <nav style={{ padding: collapsed ? "0 10px" : "0 14px", display: "flex", flexDirection: "column", gap: 2 }}>
        {NAV.map(item)}
      </nav>

      <div style={{ flex: 1 }} />

      {/* warmup mini-status */}
      {!collapsed && (
        <div style={{ margin: "0 14px 10px", padding: 13, borderRadius: t.radiusLg, background: t.card,
          border: `1px solid ${t.border}` }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
            <Label>Deliverability</Label>
            <Chip tone="good" icon="shield">98</Chip>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            <RailBar label="Mailboxes warm" val={84} t={t} />
            <RailBar label="Domains healthy" val={92} t={t} />
          </div>
          <div style={{ fontSize: 11, color: t.textMuted, marginTop: 10, display: "flex", alignItems: "center", gap: 5 }}>
            <Icon name="flame" size={12} color={t.warn} /> warmup run by Maildoso
          </div>
        </div>
      )}

      {/* account + collapse */}
      <div style={{ borderTop: `1px solid ${t.border}`, padding: collapsed ? "8px 0" : "10px 14px",
        display: "flex", alignItems: "center", gap: 10, justifyContent: collapsed ? "center" : "flex-start" }}>
        <span style={{ width: 30, height: 30, borderRadius: 999, flex: "0 0 auto", background: t.accentTint,
          color: t.accent, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700,
          fontSize: 12, fontFamily: t.mono, border: `1px solid ${t.accentBorder}` }}>MR</span>
        {!collapsed && (
          <>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 650, color: t.text, lineHeight: 1.2 }}>Mohit Rana</div>
              <div style={{ fontSize: 11, color: t.textMuted, fontFamily: t.mono, overflow: "hidden",
                textOverflow: "ellipsis", whiteSpace: "nowrap" }}>mohit@igtre.studio</div>
            </div>
            <IconBtn icon="panelLeft" size={16} onClick={() => setCollapsed(true)} title="Collapse" />
          </>
        )}
      </div>
      {collapsed && (
        <div style={{ padding: "0 0 10px", display: "flex", justifyContent: "center" }}>
          <IconBtn icon="panelLeft" size={16} onClick={() => setCollapsed(false)} title="Expand" />
        </div>
      )}
    </aside>
  );
}
function RailBar({ label, val, t }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: t.textSec, marginBottom: 4 }}>
        <span>{label}</span><span style={{ fontFamily: t.mono, color: t.text }}>{val}</span>
      </div>
      <WarmBar val={val} t={t} h={4} />
    </div>
  );
}

/* ---------------- Right-side drawer ---------------- */
function Drawer({ open, onClose, title, sub, width = 460, children, footer }) {
  const t = useT();
  return (
    <>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: hexA("#1c1814", t.dark ? 0.55 : 0.32),
        opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity .2s", zIndex: 40 }} />
      <div style={{ position: "absolute", top: 0, right: 0, bottom: 0, width, maxWidth: "92%", background: t.bg,
        borderLeft: `1px solid ${t.border}`, boxShadow: t.shadowLg, zIndex: 41, display: "flex", flexDirection: "column",
        transform: open ? "translateX(0)" : "translateX(102%)", transition: "transform .24s cubic-bezier(.32,.72,.3,1)" }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "16px 18px",
          borderBottom: `1px solid ${t.border}`, flex: "0 0 auto", background: t.card }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: t.head, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: "-.01em" }}>{title}</div>
            {sub && <div style={{ fontSize: 12.5, color: t.textMuted, marginTop: 3 }}>{sub}</div>}
          </div>
          <IconBtn icon="x" onClick={onClose} />
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: 18 }}>{children}</div>
        {footer && (
          <div style={{ flex: "0 0 auto", padding: "13px 18px", borderTop: `1px solid ${t.border}`,
            background: t.card, display: "flex", alignItems: "center", gap: 10 }}>{footer}</div>
        )}
      </div>
    </>
  );
}

/* ---------------- Page header ---------------- */
function PageHeader({ title, sub, children, tabs, tab, setTab }) {
  const t = useT();
  return (
    <div style={{ borderBottom: `1px solid ${t.border}`, background: t.bg, flex: "0 0 auto" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, padding: `0 ${t.pad}px`, height: 60 }}>
        <div style={{ minWidth: 0, flex: "0 1 auto" }}>
          <div style={{ fontFamily: t.head, fontSize: 19, fontWeight: 700, color: t.text, letterSpacing: "-.015em", whiteSpace: "nowrap" }}>{title}</div>
          {sub && <div style={{ fontSize: 12.5, color: t.textMuted, marginTop: 2 }}>{sub}</div>}
        </div>
        <div style={{ flex: 1 }} />
        {children}
      </div>
      {tabs && (
        <div style={{ display: "flex", gap: 2, padding: `0 ${t.pad}px` }}>
          {tabs.map((tb) => {
            const on = tab === tb.id;
            return (
              <button key={tb.id} onClick={() => setTab(tb.id)} style={{
                padding: "0 13px", height: 38, border: "none", background: "transparent", cursor: "pointer",
                fontFamily: t.font, fontSize: 13, fontWeight: on ? 650 : 500, color: on ? t.text : t.textMuted,
                borderBottom: `2px solid ${on ? t.accent : "transparent"}`, marginBottom: -1,
                display: "flex", alignItems: "center", gap: 7,
              }}>
                {tb.label}
                {tb.count != null && <span style={{ fontFamily: t.mono, fontSize: 11, fontWeight: 700,
                  padding: "0px 6px", borderRadius: 999, background: on ? t.accentTint : (t.dark ? t.sunken : t.bg),
                  color: on ? t.accentText : t.textMuted, border: `1px solid ${on ? t.accentBorder : t.border}` }}>{tb.count}</span>}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ---------------- App shell ---------------- */
function AppShell({ view, setView, onNew, collapsed, setCollapsed, topbar, children }) {
  const t = useT();
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", width: "100%",
      background: t.bg, color: t.text, fontFamily: t.font }}>
      <TopBar {...topbar} setView={setView} />
      <div style={{ display: "flex", flex: 1, minHeight: 0 }}>
        <LeftRail view={view} setView={setView} onNew={onNew} collapsed={collapsed} setCollapsed={setCollapsed} />
        <main style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", height: "100%", position: "relative" }}>
          {children}
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { TopBar, LeftRail, Drawer, PageHeader, AppShell });
