// app.jsx — AFEX PAY shell, router, navigation
const { useState: uS, useEffect: uE } = React;

const SELLER_NAV = [
  { id: "s/dashboard", label: "Dashboard", icon: "grid" },
  { id: "s/vendas", label: "Vendas", icon: "cart" },
  { id: "s/transacoes", label: "Transações", icon: "swap" },
  { id: "s/taxas", label: "Taxas", icon: "percent" },
  { id: "s/repasses", label: "Repasses", icon: "wallet" },
  { id: "s/integracoes", label: "Integrações", icon: "plug" },
  { id: "s/api", label: "APIs", icon: "code" },
  { id: "s/relatorios", label: "Relatórios", icon: "chart" },
  { id: "s/config", label: "Configurações", icon: "gear" },
  { id: "s/suporte", label: "Suporte", icon: "help" },
];
const ADMIN_NAV = [
  { id: "a/dashboard", label: "Dashboard", icon: "grid" },
  { id: "a/sellers", label: "Sellers", icon: "users" },
  { id: "a/transacoes", label: "Transações", icon: "swap" },
  { id: "a/repasses", label: "Repasses", icon: "wallet" },
  { id: "a/taxas", label: "Gestão de taxas", icon: "percent" },
  { id: "a/compliance", label: "Compliance", icon: "shield" },
  { id: "a/integracoes", label: "Integrações", icon: "plug" },
  { id: "a/relatorios", label: "Relatórios", icon: "chart" },
  { id: "a/config", label: "Configurações", icon: "gear" },
];

const ROUTES = {
  "auth/login": (p) => <AuthLogin {...p} />, "auth/signup": (p) => <AuthSignup {...p} />,
  "auth/forgot": (p) => <AuthForgot {...p} />, "auth/verify": (p) => <AuthVerify {...p} />,
  "auth/reset": (p) => <AuthReset {...p} />,
  "auth/2fa": (p) => <Auth2FA {...p} />, "onboarding": (p) => <Onboarding {...p} />,
  "s/dashboard": (p) => <SellerDashboard {...p} />, "s/vendas": () => <SellerVendas />,
  "s/transacoes": () => <SellerTransacoes />, "s/taxas": () => <SellerTaxas />,
  "s/repasses": () => <SellerRepasses />, "s/integracoes": (p) => <SellerIntegracoes {...p} />,
  "s/api": () => <SellerAPI />, "s/relatorios": () => <SellerRelatorios />,
  "s/config": () => <SellerConfig />, "s/suporte": () => <SellerSuporte />,
  "a/dashboard": (p) => <AdminDashboard {...p} />, "a/sellers": () => <AdminSellers />,
  "a/transacoes": () => <AdminTransacoes />, "a/repasses": () => <AdminRepasses />,
  "a/taxas": () => <AdminTaxas />, "a/compliance": () => <AdminCompliance />,
  "a/integracoes": () => <AdminIntegracoes />, "a/relatorios": () => <AdminRelatorios />,
  "a/config": () => <AdminConfig />,
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#FF5A00",
  "theme": "dark",
  "density": "regular"
}/*EDITMODE-END*/;

function Sidebar({ route, go, nav, ws, collapsed }) {
  return (
    <aside style={{
      width: collapsed ? 0 : "var(--sidebar-w)", minWidth: collapsed ? 0 : "var(--sidebar-w)",
      borderRight: "1px solid var(--line)", background: "var(--bg-2)", height: "100%",
      display: "flex", flexDirection: "column", overflow: "hidden", transition: "all .25s"
    }} className="sidebar">
      <div style={{ padding: "22px 18px", borderBottom: "1px solid var(--line)" }}>
        <Wordmark height={26} />
      </div>
      <nav className="col" style={{ padding: "14px 12px", gap: 2, flex: 1, overflowY: "auto" }}>
        <div className="eyebrow" style={{ padding: "8px 12px 6px" }}>{ws === "a" ? "Administração" : "Minha loja"}</div>
        {nav.map(n => {
          const C = I[n.icon]; const active = route === n.id;
          return (
            <button key={n.id} onClick={() => go(n.id)} style={{
              display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: 9,
              border: "none", background: active ? "var(--accent-wash)" : "transparent",
              color: active ? "var(--accent)" : "var(--ink-soft)", fontSize: 14.5, fontWeight: active ? 600 : 500,
              width: "100%", textAlign: "left", transition: "all .14s", position: "relative"
            }} onMouseEnter={e => { if (!active) { e.currentTarget.style.background = "var(--surface-2)"; e.currentTarget.style.color = "var(--ink)"; } }}
              onMouseLeave={e => { if (!active) { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink-soft)"; } }}>
              {active && <span style={{ position: "absolute", left: -12, top: 8, bottom: 8, width: 3, borderRadius: 3, background: "var(--accent)" }} />}
              <C size={19} /> {n.label}
            </button>
          );
        })}
      </nav>
      <div style={{ padding: 12, borderTop: "1px solid var(--line)" }}>
        <div className="card card-pad col gap-8" style={{ padding: 14, background: "linear-gradient(135deg, rgba(255,90,0,0.12), var(--surface))" }}>
          <div className="row gap-8"><I.rocket size={16} style={{ color: "var(--accent)" }} /><span style={{ fontSize: 13, fontWeight: 600 }}>Seu e‑commerce merece mais</span></div>
          <p className="faint" style={{ fontSize: 11.5, margin: 0, lineHeight: 1.4 }}>Antecipe recebíveis com 1,89% e cresça mais rápido.</p>
          <button className="btn btn-primary btn-sm" style={{ marginTop: 2 }}>Antecipar agora</button>
        </div>
      </div>
    </aside>
  );
}

function Topbar({ go, ws, setWs, onMenu, user, onLogout }) {
  const [notif, setNotif] = uS(false);
  const uName = user ? (user.name || user.email) : (ws === "a" ? "Roberto Lima" : "Marina Alves");
  const uMail = user ? user.email : (ws === "a" ? "Super admin" : "contato@luminastore.com.br");
  const [wsMenu, setWsMenu] = uS(false);
  const [userMenu, setUserMenu] = uS(false);
  uE(() => {
    const h = () => { setNotif(false); setWsMenu(false); setUserMenu(false); };
    window.addEventListener("click", h); return () => window.removeEventListener("click", h);
  }, []);
  const stop = e => e.stopPropagation();
  return (
    <header style={{ height: "var(--topbar-h)", minHeight: "var(--topbar-h)", borderBottom: "1px solid var(--line)", background: "color-mix(in srgb, var(--bg) 80%, transparent)", backdropFilter: "blur(12px)", display: "flex", alignItems: "center", padding: "0 24px", gap: 16, position: "sticky", top: 0, zIndex: 50 }}>
      <button className="iconbtn show-mobile" onClick={onMenu} style={{ display: "none" }}><I.grid size={20} /></button>
      <div className="input-affix hide-mobile" style={{ width: 340, maxWidth: "32vw" }}>
        <I.search size={17} className="affix affix-l" />
        <input className="input" placeholder={ws === "a" ? "Buscar sellers, transações…" : "Buscar vendas, pedidos…"} style={{ height: 40, background: "var(--surface)" }} />
      </div>
      <div className="grow" />

      {/* workspace switcher */}
      <div style={{ position: "relative" }} onClick={stop}>
        <button className="chip" onClick={() => { setWsMenu(!wsMenu); setNotif(false); setUserMenu(false); }} style={{ height: 40 }}>
          <span style={{ width: 7, height: 7, borderRadius: "50%", background: ws === "a" ? "var(--violet)" : "var(--accent)" }} />
          {ws === "a" ? "Painel Admin" : "Painel Seller"} <I.chevD size={15} />
        </button>
        {wsMenu && (
          <div className="card fade-in" style={{ position: "absolute", right: 0, top: 48, width: 240, padding: 6, boxShadow: "var(--shadow-lg)", zIndex: 80 }}>
            {[["s", "Painel do Seller", "Lumina Store", "var(--accent)"], ["a", "Painel Admin", "AFEX Pay · Global", "var(--violet)"]].map(([k, t, s, c]) => (
              <button key={k} onClick={() => { setWs(k); go(k === "a" ? "a/dashboard" : "s/dashboard"); setWsMenu(false); }} style={{ display: "flex", gap: 12, alignItems: "center", width: "100%", padding: 10, borderRadius: 8, border: "none", background: ws === k ? "var(--surface-2)" : "transparent", textAlign: "left" }}>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: c + "22", color: c, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{k === "a" ? <I.shield size={18} /> : <I.cart size={18} />}</div>
                <div className="col" style={{ lineHeight: 1.25 }}><span style={{ fontSize: 13.5, fontWeight: 600 }}>{t}</span><span className="faint" style={{ fontSize: 12 }}>{s}</span></div>
                {ws === k && <I.check size={16} style={{ color: "var(--accent)", marginLeft: "auto" }} />}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* notifications */}
      <div style={{ position: "relative" }} onClick={stop}>
        <button className="iconbtn" onClick={() => { setNotif(!notif); setWsMenu(false); setUserMenu(false); }} style={{ position: "relative" }}>
          <I.bell size={20} />
          <span style={{ position: "absolute", top: 7, right: 8, width: 7, height: 7, borderRadius: "50%", background: "var(--accent)", border: "2px solid var(--bg)" }} />
        </button>
        {notif && (
          <div className="card fade-in" style={{ position: "absolute", right: 0, top: 48, width: 360, boxShadow: "var(--shadow-lg)", zIndex: 80, overflow: "hidden" }}>
            <div className="row between" style={{ padding: "14px 18px", borderBottom: "1px solid var(--line)" }}><span className="section-title" style={{ fontSize: 15 }}>Notificações</span><button className="btn btn-subtle btn-sm">Marcar lidas</button></div>
            <div className="col" style={{ maxHeight: 380, overflowY: "auto" }}>
              {DATA.notifications.map((n, i) => { const C = I[n.icon]; const c = n.type === "orange" ? "accent" : n.type; return (
                <div key={i} className="row gap-12" style={{ padding: "13px 18px", borderTop: i ? "1px solid var(--line)" : "none", cursor: "pointer" }} onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                  <div style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, background: `var(--${c}-wash)`, color: `var(--${c})`, display: "flex", alignItems: "center", justifyContent: "center" }}><C size={16} /></div>
                  <div className="col grow" style={{ minWidth: 0 }}><span style={{ fontSize: 13.5, fontWeight: 600 }}>{n.title}</span><span className="faint" style={{ fontSize: 12.5 }}>{n.text}</span></div>
                  <span className="faint" style={{ fontSize: 11.5, whiteSpace: "nowrap" }}>{n.time}</span>
                </div>);})}
            </div>
          </div>
        )}
      </div>

      {/* user */}
      <div style={{ position: "relative" }} onClick={stop}>
        <button onClick={() => { setUserMenu(!userMenu); setNotif(false); setWsMenu(false); }} className="row gap-8" style={{ background: "none", border: "none", padding: 2 }}>
          <Avatar name={uName} size={36} />
          <I.chevD size={15} style={{ color: "var(--ink-faint)" }} className="hide-mobile" />
        </button>
        {userMenu && (
          <div className="card fade-in" style={{ position: "absolute", right: 0, top: 48, width: 230, padding: 6, boxShadow: "var(--shadow-lg)", zIndex: 80 }}>
            <div className="col gap-2" style={{ padding: "10px 12px" }}><span style={{ fontSize: 13.5, fontWeight: 600 }}>{uName}</span><span className="faint" style={{ fontSize: 12 }}>{uMail}</span></div>
            <div className="divider" style={{ margin: "6px 0" }} />
            {[["gear", "Configurações", () => go(ws === "a" ? "a/config" : "s/config")], ["help", "Ajuda & suporte", () => go("s/suporte")]].map(([ic, t, fn]) => { const C = I[ic]; return <button key={t} onClick={fn} className="row gap-10" style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "none", background: "transparent", fontSize: 13.5, color: "var(--ink-soft)", textAlign: "left" }} onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}><C size={17} /> {t}</button>;})}
            <div className="divider" style={{ margin: "6px 0" }} />
            <button onClick={onLogout} className="row gap-10" style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "none", background: "transparent", fontSize: 13.5, color: "var(--red)", textAlign: "left" }} onMouseEnter={e => e.currentTarget.style.background = "var(--red-wash)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}><I.logout size={17} /> Sair</button>
          </div>
        )}
      </div>
    </header>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = uS(() => localStorage.getItem("afex_route") || "auth/login");
  const [ws, setWs] = uS(() => localStorage.getItem("afex_ws") || "s");
  const [user, setUser] = uS(null);
  const [authReady, setAuthReady] = uS(false);
  const [mobileNav, setMobileNav] = uS(false);
  const main = React.useRef(null);

  const go = (r) => {
    // Role gate: keep a logged-in user inside their own workspace.
    if (user) {
      if (user.role === "seller" && r.startsWith("a/")) r = "s/dashboard";
      if (user.role === "admin" && r.startsWith("s/")) r = "a/dashboard";
    }
    setRoute(r); localStorage.setItem("afex_route", r);
    if (r.startsWith("a/")) { setWs("a"); localStorage.setItem("afex_ws", "a"); }
    else if (r.startsWith("s/")) { setWs("s"); localStorage.setItem("afex_ws", "s"); }
    setMobileNav(false);
    if (main.current) main.current.scrollTop = 0;
  };
  const switchWs = (k) => { setWs(k); localStorage.setItem("afex_ws", k); };

  const logout = async () => {
    try { await api.auth.logout(); } catch (e) { /* ignore */ }
    setUser(null);
    go("auth/login");
  };

  // Session gate — validates any stored token against /auth/me on load and
  // routes the user to their workspace (or to login).
  uE(() => {
    let cancelled = false;
    const finish = () => { if (!cancelled) setAuthReady(true); };
    const urlToken = new URLSearchParams(window.location.search).get("token");
    if (urlToken) { go("auth/reset"); finish(); return; }
    if (!api.auth.token()) {
      const r = localStorage.getItem("afex_route") || "auth/login";
      if (!r.startsWith("auth/") && r !== "onboarding") go("auth/login");
      finish(); return;
    }
    api.auth.me()
      .then((u) => {
        if (cancelled) return;
        setUser(u);
        setWs(u.role === "admin" ? "a" : "s");
        const r = localStorage.getItem("afex_route") || "";
        const wrong = r.startsWith("auth/") || r === "" ||
          (u.role === "admin" && r.startsWith("s/")) || (u.role === "seller" && r.startsWith("a/"));
        if (wrong) {
          const home = u.role === "admin" ? "a/dashboard" : "s/dashboard";
          setRoute(home); localStorage.setItem("afex_route", home);
        }
      })
      .catch(() => { if (!cancelled) { api.auth.setToken(null); go("auth/login"); } })
      .finally(finish);
    return () => { cancelled = true; };
  }, []);

  // apply tweaks
  uE(() => {
    const r = document.documentElement;
    r.style.setProperty("--accent", t.accent);
    r.setAttribute("data-theme", t.theme === "light" ? "light" : "dark");
    r.style.setProperty("--density", t.density === "compact" ? "0.82" : t.density === "comfy" ? "1.12" : "1");
  }, [t]);

  const isFull = route.startsWith("auth/") || route === "onboarding";
  const View = ROUTES[route] || ROUTES["s/dashboard"];
  const nav = ws === "a" ? ADMIN_NAV : SELLER_NAV;

  if (!authReady) {
    return <div style={{ height: "100%", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg)" }}><span className="faint">Carregando…</span></div>;
  }

  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
      {isFull ? (
        <div style={{ height: "100%", overflow: "auto" }}>{View({ go })}</div>
      ) : (
        <div style={{ height: "100%", display: "flex", overflow: "hidden" }}>
          {mobileNav && <div onClick={() => setMobileNav(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", zIndex: 99 }} className="show-mobile-fixed" />}
          <div className={mobileNav ? "mobile-nav-open" : ""} style={{ height: "100%", zIndex: 100 }}>
            <Sidebar route={route} go={go} nav={nav} ws={ws} collapsed={false} />
          </div>
          <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, height: "100%" }}>
            <Topbar go={go} ws={ws} setWs={switchWs} onMenu={() => setMobileNav(true)} user={user} onLogout={logout} />
            <main ref={main} style={{ flex: 1, overflowY: "auto", padding: "28px 32px 60px" }}>
              <div style={{ maxWidth: 1320, margin: "0 auto" }} key={route}>{View({ go })}</div>
            </main>
          </div>
        </div>
      )}

      <TweaksPanel>
        <TweakSection label="Marca" />
        <TweakColor label="Cor de acento" value={t.accent} options={["#FF5A00", "#22C55E", "#3B82F6", "#8B5CF6"]} onChange={v => setTweak("accent", v)} />
        <TweakSection label="Aparência" />
        <TweakRadio label="Tema" value={t.theme} options={["dark", "light"]} onChange={v => setTweak("theme", v)} />
        <TweakRadio label="Densidade" value={t.density} options={["compact", "regular", "comfy"]} onChange={v => setTweak("density", v)} />
      </TweaksPanel>
    </div>
  );
}

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