// app.jsx — shell: sidebar, topbar, routing, role switcher, tweaks
const { useState: useStateApp, useEffect: useEffectApp } = React;

const ACCENTS = {
  "Queen City": ["#0d9488","#0f766e","#f0fdfa","#ccfbf1","#99f6e4"],
  Blue:    ["#2563eb","#1d4ed8","#eff6ff","#dbeafe","#bfdbfe"],
  Indigo:  ["#4f46e5","#4338ca","#eef2ff","#e0e7ff","#c7d2fe"],
  Emerald: ["#059669","#047857","#ecfdf5","#d1fae5","#a7f3d0"],
  Slate:   ["#334155","#1e293b","#f1f5f9","#e2e8f0","#cbd5e1"],
  Orange:  ["#ea580c","#c2410c","#fff7ed","#ffedd5","#fed7aa"],
};
const FONTS = {
  "Inter": '"Inter", system-ui, -apple-system, sans-serif',
  "Space Grotesk": '"Space Grotesk", system-ui, sans-serif',
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "Queen City",
  "density": "comfortable",
  "font": "Inter"
}/*EDITMODE-END*/;

const NAV = [
  { group: "Workspace", items: [
    { id: "dashboard", label: "Dashboard", icon: "dashboard", roles: ["sdr","leader","admin"] },
    { id: "leads", label: "Leads", icon: "leads", roles: ["sdr","leader","admin"], badgeNew: true },
  ]},
  { group: "Agent", items: [
    { id: "agent", label: "Configuration", icon: "agent", roles: ["leader","admin"] },
    { id: "context", label: "Knowledge & context", icon: "docs", roles: ["leader","admin"] },
    { id: "integrations", label: "Integrations", icon: "plug", roles: ["admin"] },
  ]},
  { group: "Insights", items: [
    { id: "reporting", label: "Reporting", icon: "report", roles: ["leader","admin"] },
    { id: "usage", label: "Usage & cost", icon: "usage", roles: ["admin"] },
  ]},
  { group: "Admin", items: [
    { id: "settings", label: "Workspace settings", icon: "settings", roles: ["admin"] },
    { id: "onboarding", label: "Setup wizard", icon: "sparkle", roles: ["sdr","leader","admin"] },
  ]},
];

const ROLE_LABEL = { sdr: "SDR", leader: "Sales leader", admin: "Admin" };
const ROLE_USER = { sdr: { name: "Sam Okafor", init: "SO" }, leader: { name: "Dana Whitfield", init: "DW" }, admin: { name: "Alex Reyes", init: "AR" } };
const TITLES = {
  dashboard: "Dashboard", leads: "Leads", agent: "Agent configuration", context: "Knowledge & context",
  integrations: "Integrations", reporting: "Reporting", usage: "Usage & cost", settings: "Settings",
};

function App() {
  // Embed controls (used by the marketing-site showcase iframe):
  //   ?role=admin  -> start in a given role   ?route=leads -> start on a screen
  //   ?tour=1      -> auto-cycle through admin screens for a "live" showcase
  const params = new URLSearchParams(window.location.search);
  const roleParam = params.get("role");
  const initialRole = ["sdr", "leader", "admin"].includes(roleParam) ? roleParam : "sdr";
  const initialRoute = params.get("route") || "dashboard";
  const tourMode = params.get("tour") === "1";

  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useStateApp(initialRoute);
  const [role, setRole] = useStateApp(initialRole);
  const [leads, setLeads] = useStateApp(window.LEADS);
  const [openId, setOpenId] = useStateApp(null);
  const [toasts, setToasts] = useStateApp([]);

  const toast = (msg) => { const id = Math.random(); setToasts(p => [...p, { id, msg }]); };
  const dropToast = (id) => setToasts(p => p.filter(x => x.id !== id));

  const newCount = leads.filter(l => l.status === "new").length;
  const ac = ACCENTS[t.accent] || ACCENTS["Queen City"];
  const accentVars = {
    "--accent": ac[0], "--accent-600": ac[0], "--accent-700": ac[1],
    "--accent-50": ac[2], "--accent-100": ac[3], "--accent-200": ac[4],
    "--font": FONTS[t.font] || FONTS["Inter"],
  };

  // role change → if current route not allowed, go to dashboard
  useEffectApp(() => {
    const allowed = NAV.flatMap(g => g.items).find(i => i.id === route)?.roles.includes(role);
    if (!allowed && route !== "onboarding") setRoute("dashboard");
  }, [role]);

  function go(r) { setRoute(r); if (r !== "leads") setOpenId(null); }

  // Programmatic handles for export/automation (refreshed each render)
  useEffectApp(() => {
    window.lumeGo = go;
    window.lumeSetRole = setRole;
    window.lumeOpen = (id) => { setRoute("leads"); setOpenId(id); };
  });

  // Auto-tour: cycle through admin screens for the embedded marketing showcase.
  useEffectApp(() => {
    if (!tourMode) return;
    const seq = ["dashboard", "leads", "reporting", "usage", "integrations"];
    let i = 0;
    const id = setInterval(() => { i = (i + 1) % seq.length; go(seq[i]); }, 3800);
    return () => clearInterval(id);
  }, []);

  if (route === "onboarding") {
    return <div style={accentVars}><Onboarding onFinish={() => { setRoute("dashboard"); toast("Setup complete — first agent run started"); }} onExit={() => setRoute("dashboard")} /></div>;
  }

  const visibleNav = NAV.map(g => ({ ...g, items: g.items.filter(i => i.roles.includes(role)) })).filter(g => g.items.length);

  return (
    <div className="app" data-density={t.density === "compact" ? "compact" : undefined} style={accentVars}>
      {/* Sidebar */}
      <aside className="sidebar">
        <div className="brand">
          <img className="brand-logo" src="assets/qcai-logo-badge.png" alt="Queen City AI" />
          <div className="brand-product">AI Growth Engine</div>
        </div>
        <div className="ws-switch">
          <span className="ws-logo">{window.WORKSPACE.initials}</span>
          <div style={{ flex: 1, minWidth: 0 }}><div className="ws-name">{window.WORKSPACE.name}</div><div className="ws-plan">{window.WORKSPACE.plan}</div></div>
          <Icon name="chevDown" size={15} color="var(--gray-500)" />
        </div>
        <nav className="nav">
          {visibleNav.map((g, gi) => (
            <div key={gi}>
              <div className="nav-group-label">{g.group}</div>
              {g.items.map(it => (
                <button key={it.id} className={"nav-item " + (route === it.id ? "active" : "")} onClick={() => go(it.id)}>
                  <Icon name={it.icon} size={17} />
                  {it.label}
                  {it.badgeNew && newCount > 0 && <span className="nav-badge">{newCount}</span>}
                </button>
              ))}
            </div>
          ))}
        </nav>
        <div style={{ padding: 14, borderTop: "1px solid rgba(255,255,255,0.07)", fontSize: 11.5, color: "var(--gray-500)" }}>
          <div className="row gap-6"><Icon name="shield" size={13} color="var(--gray-500)" />Tenant data isolated</div>
        </div>
      </aside>

      {/* Main */}
      <div className="main">
        <header className="topbar">
          <h1>{TITLES[route] || "Queen City AI"}</h1>
          <div className="spacer" />
          <div className="search"><Icon name="search" size={15} /><input placeholder="Search leads, companies…" /></div>
          <div className="role-switch" title="Switch role to see role-appropriate navigation">
            {["sdr","leader","admin"].map(r => (
              <button key={r} className={"role-btn " + (role === r ? "active" : "")} onClick={() => setRole(r)}>{ROLE_LABEL[r]}</button>
            ))}
          </div>
          <button className="btn btn-ghost btn-sm" style={{ padding: 7 }}><Icon name="bell" size={18} color="var(--gray-500)" /></button>
          <span className="avatar" title={ROLE_USER[role].name}>{ROLE_USER[role].init}</span>
        </header>

        <div className="content">
          {route === "dashboard" && <Dashboard leads={leads} role={role} go={go} setOpenId={setOpenId} />}
          {route === "leads" && <LeadsScreen leads={leads} setLeads={setLeads} toast={toast} role={role} openId={openId} setOpenId={setOpenId} />}
          {route === "agent" && <AgentScreen toast={toast} />}
          {route === "context" && <ContextScreen toast={toast} />}
          {route === "integrations" && <IntegrationsScreen toast={toast} />}
          {route === "reporting" && <ReportingScreen />}
          {route === "usage" && <UsageScreen />}
          {route === "settings" && <SettingsScreen toast={toast} />}
        </div>
      </div>

      {/* Toasts */}
      <div className="toast-wrap">{toasts.map(tt => <Toast key={tt.id} msg={tt.msg} onDone={() => dropToast(tt.id)} />)}</div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
