// Portal shell — sidebar nav + topbar + content area
const PortalShell = ({ user, route, setRoute, onLogout, children }) => {
  const isMobile = useIsMobile();
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const go = (id) => { setRoute(id); setDrawerOpen(false); };
  const navItems = [
    { id: "dashboard", label: "Dashboard", icon: "home" },
    { id: "library",   label: "Asset Library", icon: "library" },
    { id: "audit",     label: "Audit", icon: "audit", badge: "3" },
    { id: "api",       label: "API", icon: "api" },
  ];
  return (
    <div style={{ minHeight: "100vh", display: "grid", gridTemplateColumns: isMobile ? "1fr" : "260px 1fr", background: "var(--bone)" }}>
      {isMobile && drawerOpen && <div className="drawer-overlay" onClick={()=>setDrawerOpen(false)} />}
      {/* SIDEBAR */}
      <aside style={{
        background: "var(--ink)", color: "var(--bone)", display: "flex", flexDirection: "column", padding: "24px 18px",
        position: isMobile ? "fixed" : "sticky", top: 0, height: "100vh",
        width: isMobile ? 280 : "auto", zIndex: 100,
        transform: isMobile && !drawerOpen ? "translateX(-100%)" : "translateX(0)",
        transition: "transform 0.25s ease",
      }}>
        <div style={{ padding: "0 6px 24px", borderBottom: "1px solid var(--line-dark)" }}>
          <Logo light size={17} />
          <div style={{ marginTop: 14, padding: "10px 12px", border: "1px solid var(--line-dark)", borderRadius: 10, display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 28, height: 28, borderRadius: 6, background: "var(--accent)", display: "grid", placeItems: "center", color: "var(--ink)", fontWeight: 600, fontSize: 12 }}>AP</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{user.tenant}</div>
              <div style={{ fontSize: 11, color: "var(--muted-2)" }}>Workspace · EU-West</div>
            </div>
            <Icon name="chevron-down" size={14} style={{ color: "var(--muted-2)" }}/>
          </div>
        </div>

        <nav style={{ display: "flex", flexDirection: "column", gap: 2, padding: "16px 0" }}>
          <div className="eyebrow" style={{ padding: "0 14px 8px", color: "var(--muted-2)" }}>Workspace</div>
          {navItems.map(n => (
            <div key={n.id} className={`nav-item ${route === n.id ? "active" : ""}`} onClick={()=>go(n.id)}>
              <Icon name={n.icon} className="icon" />
              <span style={{ flex: 1 }}>{n.label}</span>
              {n.badge && (
                <span style={{ fontSize: 10, background: "var(--accent)", color: "var(--ink)", padding: "1px 7px", borderRadius: 99, fontFamily: "var(--font-mono)", fontWeight: 500 }}>{n.badge}</span>
              )}
            </div>
          ))}
        </nav>

        <div style={{ marginTop: 8, padding: "12px 0", borderTop: "1px solid var(--line-dark)" }}>
          <div className="eyebrow" style={{ padding: "0 14px 8px", color: "var(--muted-2)" }}>Account</div>
          <div className="nav-item" onClick={()=>go("settings")}><Icon name="settings" className="icon"/> Settings</div>
          <div className="nav-item"><Icon name="external" className="icon"/> Documentation</div>
        </div>

        <div style={{ marginTop: "auto", borderTop: "1px solid var(--line-dark)", paddingTop: 16, display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 34, height: 34, borderRadius: 99, background: "var(--ink-3)", display: "grid", placeItems: "center", fontSize: 12, fontWeight: 500 }}>AC</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{user.name}</div>
            <div style={{ fontSize: 11, color: "var(--muted-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.role}</div>
          </div>
          <button onClick={onLogout} style={{ background: "transparent", border: "none", color: "var(--muted-2)", padding: 6, cursor: "pointer" }} title="Sign out">
            <Icon name="logout" size={16}/>
          </button>
        </div>
      </aside>

      {/* MAIN */}
      <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
        <header style={{
          height: 64, padding: isMobile ? "0 16px" : "0 36px", borderBottom: "1px solid var(--line)",
          display: "flex", alignItems: "center", gap: isMobile ? 10 : 16, background: "var(--bone)", position: "sticky", top: 0, zIndex: 50
        }}>
          {isMobile && (
            <button className="drawer-toggle" onClick={()=>setDrawerOpen(true)} aria-label="Open menu">
              <Icon name="menu" size={18}/>
            </button>
          )}
          {isMobile ? <Logo size={15}/> : (
            <div style={{ position: "relative", flex: 1, maxWidth: 480 }}>
              <Icon name="search" size={15} style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--muted)" }} />
              <input placeholder="Search assets, audits, endpoints…" style={{
                width: "100%", padding: "9px 14px 9px 38px", border: "1px solid var(--line)", borderRadius: 8,
                background: "var(--paper)", fontSize: 13, outline: "none"
              }}/>
              <span className="kbd kbd-hide-mobile" style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)" }}>⌘K</span>
            </div>
          )}
          <div style={{ flex: 1 }}/>
          {!isMobile && (
            <button className="btn btn-quiet" style={{ padding: "8px 14px" }}>
              <Icon name="sparkles" size={14} style={{ color: "var(--accent)" }}/> Ask Graphite AI
            </button>
          )}
          <button aria-label="Search" style={{ display: isMobile ? "grid" : "none", background: "transparent", border: "1px solid var(--line)", borderRadius: 99, width: 36, height: 36, placeItems: "center", cursor: "pointer" }}>
            <Icon name="search" size={15}/>
          </button>
          <button style={{ background: "transparent", border: "1px solid var(--line)", borderRadius: 99, width: 36, height: 36, display: "grid", placeItems: "center", position: "relative", cursor: "pointer", flexShrink: 0 }}>
            <Icon name="bell" size={15}/>
            <span style={{ position: "absolute", top: 7, right: 8, width: 7, height: 7, borderRadius: 99, background: "var(--accent)" }} />
          </button>
        </header>
        <main style={{ flex: 1, overflow: "auto" }}>{children}</main>
      </div>
    </div>
  );
};

// DASHBOARD
const Dashboard = ({ user, setRoute }) => {
  const isMobile = useIsMobile();
  const sparkData = [12, 14, 13, 18, 17, 22, 28, 24, 31, 35, 38, 42];
  return (
    <div style={{ padding: isMobile ? "20px 16px 60px" : "36px 36px 80px", maxWidth: 1500 }}>
      {/* Hero */}
      <div className="chamfer" style={{ background: "var(--ink)", color: "var(--bone)", padding: isMobile ? "32px 24px" : "48px 52px", marginBottom: isMobile ? 20 : 32, "--chamfer": isMobile ? "16px" : "24px", position: "relative", overflow: "hidden" }}>
        <div className="login-bg" style={{ opacity: 0.6 }}/>
        <div style={{ position: "relative", zIndex: 1, display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.4fr 1fr", gap: isMobile ? 32 : 48, alignItems: "end" }}>
          <div>
            <div className="eyebrow eyebrow-coral" style={{ marginBottom: 18 }}>● Tuesday · April 28, 2026</div>
            <h1 className="h-display" style={{ color: "var(--bone)" }}>
              Good afternoon, Amelia.<br/>
              <span className="accent">3 audits</span> need your eyes.
            </h1>
            <p style={{ color: "var(--muted-2)", fontSize: 16, marginTop: 18, maxWidth: 560 }}>
              Two pieces flagged for ISI placement on the Veltrox HCP campaign, and a brand-consistency review on Acme.com is ready for sign-off.
            </p>
            <div style={{ display: "flex", gap: 12, marginTop: 28 }}>
              <button className="btn btn-primary" onClick={()=>setRoute("audit")}>
                Open audit queue <Icon name="arrow-right" size={13}/>
              </button>
              <button className="btn btn-ghost-light" onClick={()=>setRoute("library")}>
                Browse library
              </button>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: isMobile ? 14 : 20 }}>
            {[
              { k: "94", lbl: "Avg. governance score", trend: "+6" },
              { k: "12 min", lbl: "Median audit turnaround", trend: "-3 min" },
              { k: "847", lbl: "Assets in your library", trend: "+12" },
              { k: "3.2M", lbl: "API calls this month", trend: "+18%" },
            ].map((s, i) => (
              <div key={i} style={{ borderTop: "1px solid var(--line-dark)", paddingTop: 14 }}>
                <div style={{ fontSize: isMobile ? 22 : 28, fontFamily: "var(--font-serif)", fontStyle: "italic", color: "var(--bone)", letterSpacing: "-0.01em" }}>{s.k}</div>
                <div style={{ fontSize: 12, color: "var(--muted-2)", marginTop: 4 }}>{s.lbl}</div>
                <div style={{ fontSize: 11, color: "var(--accent)", marginTop: 4, fontFamily: "var(--font-mono)" }}>↑ {s.trend}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Quick actions row */}
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)", gap: isMobile ? 14 : 20, marginBottom: isMobile ? 24 : 32 }}>
        {[
          { id: "library", icon: "library", title: "Asset Library", desc: "Design system, Figma files, design.md for AI agents.", meta: "847 assets · synced 12m ago" },
          { id: "audit",   icon: "audit",   title: "Run an Audit",  desc: "Upload designs for regulatory + brand governance review.", meta: "Avg. 12 min · ISI / WCAG / brand", primary: true },
          { id: "api",     icon: "api",     title: "API Access",    desc: "Integrate Graphite into your DAM, CMS, or review tools.", meta: "v2.4 · 4 active keys" },
        ].map(c => (
          <div key={c.id} className="card chamfer-tr" onClick={()=>setRoute(c.id)} style={{
            padding: 28, cursor: "pointer", display: "flex", flexDirection: "column", gap: 14,
            background: c.primary ? "var(--ink)" : "var(--paper)",
            color: c.primary ? "var(--bone)" : "var(--ink)",
            borderColor: c.primary ? "var(--ink)" : "var(--line)",
            transition: "transform 0.15s, border-color 0.15s",
          }}
          onMouseEnter={e => e.currentTarget.style.transform = "translateY(-2px)"}
          onMouseLeave={e => e.currentTarget.style.transform = "translateY(0)"}
          >
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: c.primary ? "var(--accent)" : "var(--bone)", display: "grid", placeItems: "center", color: c.primary ? "var(--ink)" : "var(--ink)" }}>
                <Icon name={c.icon} size={18}/>
              </div>
              <Icon name="arrow-up-right" size={16} style={{ color: c.primary ? "var(--muted-2)" : "var(--muted)" }}/>
            </div>
            <div>
              <div style={{ fontSize: 20, fontWeight: 500, letterSpacing: "-0.01em" }}>{c.title}</div>
              <p style={{ fontSize: 14, color: c.primary ? "var(--muted-2)" : "var(--muted)", margin: "6px 0 0", lineHeight: 1.5 }}>{c.desc}</p>
            </div>
            <div className="eyebrow" style={{ marginTop: "auto", color: c.primary ? "var(--muted-2)" : "var(--muted)" }}>{c.meta}</div>
          </div>
        ))}
      </div>

      {/* Two-col: recent audits + activity */}
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.5fr 1fr", gap: isMobile ? 16 : 20 }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "20px 24px", display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--line)" }}>
            <div>
              <div className="eyebrow">Recent audits</div>
              <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4 }}>Awaiting your review</div>
            </div>
            <button className="btn btn-quiet" onClick={()=>setRoute("audit")} style={{ padding: "7px 14px", fontSize: 12 }}>View all</button>
          </div>
          <div className="tbl-scroll">
          <table className="tbl">
            <thead><tr><th>Asset</th><th>Type</th><th>Score</th><th>Issues</th><th>Status</th></tr></thead>
            <tbody>
              {[
                { n: "Veltrox HCP — Email v3", t: "Email", s: 78, i: "2 critical · 4 minor", st: "warn", stl: "Needs review" },
                { n: "Veltrox patient leaflet", t: "Print", s: 91, i: "1 minor", st: "ok", stl: "Approved" },
                { n: "Acme.com / Therapeutic areas", t: "Web", s: 64, i: "3 critical · 6 minor", st: "crit", stl: "Action required" },
                { n: "Cardiometabolic banner set", t: "Display", s: 88, i: "2 minor", st: "ok", stl: "Approved" },
                { n: "Investor day deck (Q2)", t: "Deck", s: 82, i: "5 minor", st: "warn", stl: "In review" },
              ].map((r, i) => (
                <tr key={i} style={{ cursor: "pointer" }} onClick={()=>setRoute("audit")}>
                  <td style={{ fontWeight: 500 }}>{r.n}</td>
                  <td style={{ color: "var(--muted)" }}>{r.t}</td>
                  <td><strong style={{ color: r.s >= 85 ? "var(--ok)" : r.s >= 65 ? "var(--warn)" : "var(--crit)" }}>{r.s}</strong></td>
                  <td style={{ color: "var(--muted)", fontSize: 13 }}>{r.i}</td>
                  <td><span className={`pill pill-${r.st}`}><span className="pill-dot"/>{r.stl}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        </div>

        <div className="card" style={{ padding: 24 }}>
          <div className="eyebrow">API usage</div>
          <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4, marginBottom: 12 }}>Last 12 weeks</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 8 }}>
            <span style={{ fontSize: 36, fontWeight: 500, letterSpacing: "-0.02em" }}>3.2M</span>
            <span style={{ fontSize: 13, color: "var(--ok)", fontFamily: "var(--font-mono)" }}>+18.4%</span>
          </div>
          <Sparkline data={sparkData}/>
          <hr className="hr" style={{ margin: "18px 0" }}/>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Activity</div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 14 }}>
            {[
              { who: "Dr. Cole", what: "approved", obj: "Cardiometabolic banner set", when: "12m ago" },
              { who: "Reg. team", what: "flagged", obj: "Veltrox HCP — Email v3", when: "1h ago" },
              { who: "Graphite AI", what: "completed audit on", obj: "Acme.com home", when: "3h ago" },
              { who: "You", what: "uploaded", obj: "Spring campaign — v2", when: "yesterday" },
            ].map((a, i) => (
              <li key={i} style={{ fontSize: 13, color: "var(--ink)", display: "flex", gap: 10 }}>
                <div style={{ width: 6, height: 6, borderRadius: 99, background: "var(--accent)", marginTop: 7, flexShrink: 0 }}/>
                <div style={{ flex: 1 }}>
                  <strong>{a.who}</strong> <span style={{ color: "var(--muted)" }}>{a.what}</span> <em style={{ fontStyle: "normal", borderBottom: "1px dotted var(--muted)" }}>{a.obj}</em>
                  <div style={{ fontSize: 11, color: "var(--muted)", fontFamily: "var(--font-mono)", marginTop: 2 }}>{a.when}</div>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PortalShell, Dashboard });
