/* global React, Icon, AgentAvatar, Button */
const { useState: useShell } = React;

const NAV = [
  { group: "Setup", items: [
    { key: "onboarding", label: "Onboarding", icon: "user" },
    { key: "memory", label: "Memory", icon: "layers" },
  ]},
  { group: "Build", items: [
    { key: "resume", label: "Résumé studio", icon: "fileText" },
    { key: "summary", label: "Where you stand", icon: "target" },
  ]},
  { group: "Discover & apply", items: [
    { key: "board", label: "Job board", icon: "grid" },
    { key: "tailor", label: "Tailor & apply", icon: "sparkles" },
  ]},
  { group: "Get introduced", items: [
    { key: "network", label: "Network map", icon: "route" },
    { key: "events", label: "Events", icon: "calendar" },
  ]},
  { group: "Track", items: [
    { key: "tracker", label: "Job tracker", icon: "briefcase" },
    { key: "prep", label: "Interview prep", icon: "graduation" },
  ]},
];

const TITLES = {
  onboarding: "Setup", memory: "Memory", resume: "Résumé studio", summary: "Where you stand",
  board: "Job board", tailor: "Tailor & apply", tracker: "Job tracker", prep: "Interview prep",
  network: "Network map", events: "Events",
};

const railToggleStyle = {
  width: 26, height: 26, borderRadius: 7, flexShrink: 0,
  display: "grid", placeItems: "center", cursor: "pointer",
  border: "1px solid var(--ink-100)", background: "var(--paper)", color: "var(--fg-2)",
  transition: "background 120ms",
};

// Collapsible rail. Collapsed = slim icon strip; hovering it peeks the full rail
// open as an OVERLAY (content underneath does not reflow). Clicking the chevron
// while peeking pins it open; clicking it while expanded collapses it.
function Rail({ route, go, collapsed, onToggle }) {
  const [peek, setPeek] = useShell(false);
  const [suppress, setSuppress] = useShell(false); // blocks peek right after collapsing, until the mouse leaves
  const peekTimer = React.useRef(null);
  const open = !collapsed || (peek && !suppress);
  const fade = { opacity: open ? 1 : 0, transition: "opacity 140ms ease" };

  const handleToggle = () => {
    if (peekTimer.current) clearTimeout(peekTimer.current);
    setPeek(false);
    if (!collapsed) setSuppress(true);
    onToggle();
  };

  return (
    <div style={{ width: collapsed ? 64 : 208, flexShrink: 0, position: "relative", zIndex: 60, transition: "width 200ms cubic-bezier(0.2,0.7,0.1,1)" }}>
      <aside
        onMouseEnter={() => { peekTimer.current = setTimeout(() => setPeek(true), 110); }}
        onMouseLeave={() => { if (peekTimer.current) clearTimeout(peekTimer.current); setPeek(false); setSuppress(false); }}
        style={{
          position: "absolute", top: 0, bottom: 0, left: 0, width: open ? 208 : 64, boxSizing: "border-box",
          background: "var(--paper)", borderRight: "1px solid var(--ink-100)",
          display: "flex", flexDirection: "column", padding: "16px 12px", overflow: "hidden",
          boxShadow: collapsed && open ? "0 18px 48px rgba(31,27,22,0.16)" : "none",
          transition: "width 200ms cubic-bezier(0.2,0.7,0.1,1), box-shadow 200ms ease",
        }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "0 4px 16px" }}>
          <img src="../../assets/offerroom-mark.svg" alt="Offerroom" style={{ width: 28, height: 28, flexShrink: 0 }}/>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 500, letterSpacing: "-0.01em", whiteSpace: "nowrap", ...fade }}>Offerroom</span>
          <span style={{ flex: 1 }}/>
          <button onClick={handleToggle} title={collapsed ? "Pin sidebar open" : "Collapse sidebar"} aria-label={collapsed ? "Pin sidebar open" : "Collapse sidebar"}
            style={{ ...railToggleStyle, opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "background 120ms, opacity 140ms ease" }}
            onMouseEnter={e => e.currentTarget.style.background = "rgba(31,27,22,0.04)"}
            onMouseLeave={e => e.currentTarget.style.background = "var(--paper)"}>
            <Icon name="chevron" size={15} style={{ transform: collapsed ? "none" : "rotate(180deg)" }}/>
          </button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", overflowX: "hidden", display: "flex", flexDirection: "column", gap: 14 }}>
          {NAV.map((sec, si) => (
            <div key={sec.group}>
              <div style={{ position: "relative", height: 17, margin: "0 8px 4px" }}>
                <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "flex-end", fontSize: 10, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-3)", whiteSpace: "nowrap", ...fade }}>{sec.group}</div>
                {si > 0 && <div style={{ position: "absolute", top: 8, left: 2, right: 2, height: 1, background: "var(--ink-100)", opacity: open ? 0 : 1, transition: "opacity 140ms ease" }}/>}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 1 }}>
                {sec.items.map(it => {
                  const active = route === it.key;
                  return (
                    <button key={it.key} onClick={() => go(it.key)} title={!open ? it.label : undefined} className="cad-nav-btn" data-active={active ? "1" : "0"} style={{
                      display: "flex", alignItems: "center", gap: 10, padding: "8px 11px", borderRadius: 8, cursor: "pointer",
                      color: active ? "#5E0E0E" : "var(--fg-1)", overflow: "hidden", whiteSpace: "nowrap",
                      border: "none", fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: active ? 600 : 500, textAlign: "left",
                    }}>
                      <Icon name={it.icon} size={17} style={{ color: active ? "#8C1515" : "var(--fg-2)", flexShrink: 0 }}/>
                      <span style={fade}>{it.label}</span>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        <div title={!open ? "Working · Tailoring Ramp" : undefined} style={{ borderTop: "1px solid var(--ink-100)", marginTop: 8, display: "flex", alignItems: "center", gap: 10, padding: "12px 5px 0" }}>
          <AgentAvatar working={true} size={30}/>
          <div style={{ minWidth: 0, whiteSpace: "nowrap", ...fade }}>
            <div style={{ fontSize: 12.5, fontWeight: 600 }}>Working</div>
            <div style={{ fontSize: 11, color: "var(--cardinal)", display: "flex", alignItems: "center", gap: 5 }}><span className="cad-pulse-dot"/>Tailoring Ramp</div>
          </div>
        </div>
      </aside>
    </div>
  );
}

function Topbar({ route }) {
  return (
    <header style={{ height: 56, flexShrink: 0, borderBottom: "1px solid var(--ink-100)", background: "var(--paper)", display: "flex", alignItems: "center", padding: "0 22px", gap: 16 }}>
      <h1 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 19, letterSpacing: "-0.01em" }}>{TITLES[route]}</h1>
      <span style={{ flex: 1 }}/>
      <button style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 12px", borderRadius: 8, background: "var(--paper-sunken)", border: "1px solid var(--ink-100)", color: "var(--fg-2)", cursor: "pointer", fontSize: 13, minWidth: 230 }}>
        <Icon name="search" size={14}/><span>Ask Offerroom · run a command…</span>
        <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-3)" }}>⌘K</span>
      </button>
      <div style={{ width: 32, height: 32, borderRadius: 999, background: "#1F1B16", color: "#F6F4EF", display: "grid", placeItems: "center", fontSize: 12, fontWeight: 600 }}>MO</div>
    </header>
  );
}

// ---- Screen index: feature-map traceability ----
const INDEX_MAP = [
  { phase: "Setup", rows: [
    { node: "Upload résumé · auto-extract profile", route: "onboarding", screen: "Onboarding" },
    { node: "No-résumé profile form · LinkedIn", route: "onboarding", screen: "Onboarding" },
    { node: "Work-history dump → RAG + graph", route: "memory", screen: "Memory" },
  ]},
  { phase: "Build", rows: [
    { node: "Résumé agent · base résumé", route: "resume", screen: "Résumé studio" },
    { node: "LaTeX templates · format edit", route: "resume", screen: "Résumé studio" },
    { node: "Candidate summary · SWOT", route: "summary", screen: "Where you stand" },
    { node: "Role tiers · safe / progressive / dream", route: "summary", screen: "Where you stand" },
  ]},
  { phase: "Apply", rows: [
    { node: "Job inputs · paste JD / URL / board / extension", route: "tailor", screen: "Tailor · Job" },
    { node: "Résumé customiser · diff + provenance + autosave", route: "tailor", screen: "Tailor · Résumé" },
    { node: "Cover-letter agent · research + provenance", route: "tailor", screen: "Tailor · Cover" },
    { node: "Custom Q&A agent · drafts + voice nudge", route: "tailor", screen: "Tailor · Questions" },
    { node: "Form-filling agent · auto-submit", route: "tailor", screen: "Tailor · Apply" },
  ]},
  { phase: "Track", rows: [
    { node: "Job tracker · stages + verify", route: "tracker", screen: "Job tracker" },
    { node: "Analytics · weekly insights", route: "tracker", screen: "Job tracker" },
    { node: "Interview prep · behavioral + technical + dossier", route: "prep", screen: "Interview prep" },
  ]},
  { phase: "Discover & channels", rows: [
    { node: "Internal job board · match + sponsored", route: "board", screen: "Job board" },
    { node: "Chrome extension · save & queue to apply (form-fill in ~2m)", route: "tracker", screen: "Extension kit → Tracker" },
  ]},
  { phase: "Get introduced — unified network map (cases A–H)", rows: [
    { node: "Unified map · You → introducers → targets, one filterable graph", route: "network", screen: "Network map" },
    { node: "Super-connectors · ranked by targets unlocked, cross-type (H1, H3)", route: "network", screen: "Ranking rail" },
    { node: "Company cluster · collapsed count badge, expands to 4 personas (B)", route: "network", screen: "Cluster expand" },
    { node: "Path detail · you → introducer → target, score + proof (C, D)", route: "network", screen: "Path detail" },
    { node: "Intro composer · draft in your voice, approve-before-send (F1, F2)", route: "network", screen: "Composer" },
    { node: "Outreach tracker · sequence status, follow-ups, replies (F3, F4)", route: "network", screen: "Outreach" },
    { node: "Isolated target + type filter + zoom · legible at 20+ (H4, H2)", route: "network", screen: "Filter / zoom" },
    { node: "Sparse map · too few paths, widen network (H5)", route: "network", screen: "Tweaks → Density: sparse" },
    { node: "Locked / upsell · discovery free, intros Premium (pricing)", route: "network", screen: "Tweaks → Tier: free" },
    { node: "Way-in badge · cheap path check on job + tracker cards (A2)", route: "network", screen: "Badge → map" },
    { node: "Network sync · first-run / sync-required gate (G1)", route: "network", screen: "Hub → Re-sync" },
  ]},
  { phase: "Events — relevant-event discovery (cases A–F)", rows: [
    { node: "Events feed · filters + grouped by target companies vs profile (A, B, C)", route: "events", screen: "Events feed" },
    { node: "Company-appearing event · inferred data, verify-on-source chip (A2, F4)", route: "events", screen: "Career fair card" },
    { node: "Event detail · why-relevant, networking tie-in, register out (C, D, E)", route: "events", screen: "Card → detail" },
    { node: "Tracked events · interested → registered → attending → attended (E)", route: "events", screen: "Tracked view" },
    { node: "Closed / deadline-passed muted state + free-tier upsell (F5, pricing)", route: "events", screen: "Feed + Tweaks → Tier: free" },
  ]},
  { phase: "Reconciled with existing surfaces — not duplicated", rows: [
    { node: "Job tracker is the full-page view of the dashboard Pipeline (one data model)", route: "tracker", screen: "Tracker = Pipeline" },
    { node: "Memory is the manage view of the Context drawer's shared store", route: "memory", screen: "Memory ↔ Drawer" },
    { node: "Tailor & apply is launched from the Conversation pane, not a parallel app", route: "tailor", screen: "Chat → Tailor" },
  ]},
];

function ScreenIndex({ onClose, go }) {
  return (
    <div className="cad-fade" onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 90, background: "rgba(31,27,22,0.32)", display: "grid", placeItems: "center", padding: 28 }}>
      <div className="cad-rise" onClick={e => e.stopPropagation()} style={{ width: 760, maxHeight: "86vh", overflow: "auto", background: "#fff", borderRadius: 14, boxShadow: "0 32px 64px rgba(31,27,22,0.28)" }}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--ink-100)", display: "flex", alignItems: "center", gap: 12, position: "sticky", top: 0, background: "#fff", zIndex: 1 }}>
          <Icon name="map" size={18} style={{ color: "var(--cardinal)" }}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 500 }}>Feature map → screens</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-2)" }}>Every node from the business map, and the design that covers it. Click to jump.</div>
          </div>
          <button onClick={onClose} style={{ width: 30, height: 30, borderRadius: 6, border: "1px solid var(--ink-100)", background: "#fff", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="close" size={15}/></button>
        </div>
        <div style={{ padding: "8px 24px 22px" }}>
          {INDEX_MAP.map(sec => (
            <div key={sec.phase} style={{ marginTop: 18 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--fg-2)", marginBottom: 8 }}>{sec.phase}</div>
              <div style={{ border: "1px solid var(--ink-100)", borderRadius: 10, overflow: "hidden" }}>
                {sec.rows.map((r, i) => (
                  <button key={i} onClick={() => { go(r.route); onClose(); }} style={{
                    width: "100%", textAlign: "left", display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", cursor: "pointer",
                    background: "#fff", border: "none", borderBottom: i < sec.rows.length - 1 ? "1px solid var(--ink-50)" : "none", fontFamily: "var(--font-sans)",
                  }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--paper)"}
                    onMouseLeave={e => e.currentTarget.style.background = "#fff"}>
                    <Icon name="check" size={14} style={{ color: "#5A7150", flexShrink: 0 }}/>
                    <span style={{ flex: 1, fontSize: 13, color: "var(--fg-1)" }}>{r.node}</span>
                    <span style={{ fontSize: 11.5, color: "var(--fg-2)", fontFamily: "var(--font-mono)", flexShrink: 0 }}>{r.screen}</span>
                    <Icon name="arrow" size={14} style={{ color: "var(--fg-3)", flexShrink: 0 }}/>
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---- Screen index TRIGGER: a kit-review affordance, deliberately outside the
// product chrome so it never reads as a real product feature. ----
function ScreenIndexButton({ onOpen, collapsed }) {
  return (
    <button onClick={onOpen} title="Kit navigation, every demo screen mapped to the feature map" style={{
      position: "fixed", left: collapsed ? 80 : 224, bottom: 22, zIndex: 65,
      display: "inline-flex", alignItems: "center", gap: 8, padding: "7px 13px 7px 9px", borderRadius: 999,
      background: "rgba(246,244,239,0.9)", border: "1px dashed rgba(31,27,22,0.28)",
      color: "var(--fg-2)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 500,
      boxShadow: "0 4px 14px rgba(31,27,22,0.08)", backdropFilter: "blur(6px)", WebkitBackdropFilter: "blur(6px)",
      transition: "background 120ms, left 200ms cubic-bezier(0.2,0.7,0.1,1)",
    }}
      onMouseEnter={e => e.currentTarget.style.background = "rgba(255,255,255,0.97)"}
      onMouseLeave={e => e.currentTarget.style.background = "rgba(246,244,239,0.9)"}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--cardinal)", border: "1px solid rgba(140,21,21,0.25)", borderRadius: 4, padding: "1px 5px" }}>kit</span>
      <Icon name="map" size={14}/>
      Screen index
    </button>
  );
}

// ---- Global onboarding wizard: Step 1 → 4, Onboarding → Where you stand ----
const WIZARD_STEPS = [
  { key: "onboarding", n: 1, short: "Set up",          title: "Set up your profile" },
  { key: "memory",     n: 2, short: "Memory",          title: "Build your memory" },
  { key: "resume",     n: 3, short: "Résumé",          title: "Write your base résumé" },
  { key: "summary",    n: 4, short: "Where you stand",  title: "See where you stand" },
];
const WIZARD_INDEX = WIZARD_STEPS.reduce((m, s, i) => (m[s.key] = i, m), {});

// What the bottom-right button points at during first-time setup only.
const NEXT_OF = {
  onboarding: { to: "memory",  label: "Next · build memory" },
  memory:     { to: "resume",  label: "Next · base résumé" },
  resume:     { to: "summary", label: "Next · where you stand" },
  summary:    { to: "tailor",  label: "Start applying", milestone: true },
};

function WizardBar({ route, completed, go }) {
  const curIdx = route in WIZARD_INDEX ? WIZARD_INDEX[route] : -1;
  const doneCount = WIZARD_STEPS.filter(s => completed.includes(s.key)).length;
  const allDone = doneCount === WIZARD_STEPS.length;
  return (
    <div style={{ flexShrink: 0, borderBottom: "1px solid var(--ink-100)", background: "var(--paper)", padding: "9px 22px", display: "flex", alignItems: "center", gap: 16 }}>
      <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.07em", textTransform: "uppercase", color: allDone ? "var(--sage-text)" : "var(--fg-2)", whiteSpace: "nowrap" }}>
        {allDone ? "Setup complete" : "Getting started"}
      </span>
      <div style={{ display: "flex", alignItems: "center", gap: 0, flex: 1, minWidth: 0 }}>
        {WIZARD_STEPS.map((s, i) => {
          const done = completed.includes(s.key);
          const active = s.key === route;
          return (
            <React.Fragment key={s.key}>
              <button onClick={() => go(s.key)} title={s.title} className="cad-wiz-step" data-active={active ? "1" : "0"} style={{
                display: "inline-flex", alignItems: "center", gap: 8,
                border: "none", cursor: "pointer", padding: "5px 9px", borderRadius: 999, fontFamily: "var(--font-sans)",
              }}>
                <span style={{
                  width: 20, height: 20, borderRadius: 999, flexShrink: 0, display: "grid", placeItems: "center",
                  fontSize: 11, fontWeight: 600, fontVariantNumeric: "tabular-nums",
                  background: active ? "#8C1515" : done ? "#5A7150" : "#fff",
                  color: active || done ? "#fff" : "var(--fg-2)",
                  border: active || done ? "1px solid transparent" : "1px solid var(--ink-100)",
                }}>{done && !active ? <Icon name="check" size={11}/> : s.n}</span>
                <span className="wiz-step-label" style={{ fontSize: 12.5, fontWeight: active ? 600 : 500, color: active ? "#5E0E0E" : done ? "var(--fg-1)" : "var(--fg-2)", whiteSpace: "nowrap" }}>{s.short}</span>
              </button>
              {i < WIZARD_STEPS.length - 1 && (
                <span style={{ flex: 1, height: 2, minWidth: 14, maxWidth: 56, borderRadius: 2, margin: "0 4px", background: completed.includes(s.key) ? "#5A7150" : "var(--ink-100)", transition: "background 200ms" }}/>
              )}
            </React.Fragment>
          );
        })}
      </div>
      <span className="wiz-done" style={{ fontSize: 11.5, color: "var(--fg-2)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>{doneCount} of {WIZARD_STEPS.length} done</span>
    </div>
  );
}

function NextStepButton({ route, completed, go, onAdvance }) {
  const next = NEXT_OF[route];
  if (!next) return null;
  return (
    <button onClick={() => onAdvance(route, next.to)} style={{
      position: "fixed", right: 28, bottom: 24, zIndex: 70,
      display: "inline-flex", alignItems: "center", gap: 9, padding: "12px 18px",
      borderRadius: 999, border: "none", cursor: "pointer", fontFamily: "var(--font-sans)",
      fontSize: 14, fontWeight: 600, color: "#fff", background: "#5A7150",
      boxShadow: "0 8px 24px rgba(47,69,40,0.30), 0 0 0 4px rgba(90,113,80,0.12)",
      transition: "transform 120ms cubic-bezier(0.2,0.7,0.1,1), background 120ms",
    }}
      onMouseEnter={e => { e.currentTarget.style.background = "#4E6345"; }}
      onMouseLeave={e => { e.currentTarget.style.background = "#5A7150"; }}
      onMouseDown={e => { e.currentTarget.style.transform = "translateY(0.5px)"; }}
      onMouseUp={e => { e.currentTarget.style.transform = "none"; }}>
      {next.milestone && <Icon name="sparkles" size={16}/>}
      {next.label}
      <Icon name="arrow" size={16}/>
    </button>
  );
}

Object.assign(window, { Rail, Topbar, ScreenIndex, ScreenIndexButton, WizardBar, NextStepButton, WIZARD_STEPS, WIZARD_INDEX, NEXT_OF });
