// App.jsx — main router

const { useState: useStateApp, useEffect: useEffectApp } = React;

const PAGES = {
  "dashboard": () => <DashboardPage/>,
  "live-planejamento": () => <LivePlanejamentoPage/>,
  "live-apresentar": () => <ApresentarPage/>,
  "live-pedidos": () => <LivePedidosPage/>,
  "live-bag": () => <LiveBagPage/>,
  "live-sortear": () => <LiveSortearPage/>,
  "loja-pdv": () => <PdvPage/>,
  "loja-crediario": () => <CrediarioPage/>,
  "loja-financeiro": () => <FinanceiroPage/>,
  "site-pedidos": () => <SitePedidosPage/>,
  "site-carrinhos": () => <SiteCarrinhosPage/>,
  "produtos": () => <ProdutosPage/>,
  "clientes": () => <ClientesPage/>,
  "disparo": () => <DisparoPage/>,
  "marketing": () => <MarketingPage/>,
  "relatorios": () => <RelatoriosPage/>,
  "config": () => <ConfigPage/>,
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "compact"
}/*EDITMODE-END*/;

const App = () => {
  const [route, setRoute] = useStateApp(() => {
    const h = window.location.hash.replace("#", "");
    return PAGES[h] ? h : "dashboard";
  });
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [dataVersion, setDataVersion] = useStateApp(0);

  // Carrega dados reais do banco (API PHP). Em falha, mantém os dados locais.
  useEffectApp(() => {
    if (window.API && window.API.bootstrap) {
      window.API.bootstrap()
        .then(() => setDataVersion((v) => v + 1))
        .catch((e) => console.warn("API indisponível — usando dados locais.", e));
    }
  }, []);

  useEffectApp(() => {
    window.location.hash = "#" + route;
    document.documentElement.setAttribute("data-density", tweaks.density);
    // Scroll content area to top on route change
    const sc = document.querySelector(".content-scroll");
    if (sc) sc.scrollTop = 0;
  }, [route, tweaks.density]);

  useEffectApp(() => {
    const onHash = () => {
      const h = window.location.hash.replace("#", "");
      if (PAGES[h] && h !== route) setRoute(h);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, [route]);

  const Page = PAGES[route] || PAGES["dashboard"];

  return (
    <div className="app-root">
      <Sidebar route={route} setRoute={setRoute}/>
      <div className="main-area">
        <Topbar route={route}/>
        <div className="content-scroll">
          <Page/>
        </div>
      </div>

      <TweaksPanel title="Tweaks · Venda na Live">
        <TweakSection label="Densidade">
          <TweakRadio
            label="Layout"
            value={tweaks.density}
            options={[
              { value: "compact", label: "Compacta" },
              { value: "comfortable", label: "Confortável" },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
        </TweakSection>

        <TweakSection label="Navegação rápida">
          <div className="t-3" style={{fontSize:11, marginBottom:8}}>Atalhos para ver os módulos:</div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:6}}>
            {Object.entries({
              "dashboard": "Dashboard",
              "live-planejamento": "Live · Planejamento",
              "live-apresentar": "Live · Apresentar",
              "live-pedidos": "Live · Pedidos",
              "loja-pdv": "PDV",
              "loja-crediario": "Crediário",
              "loja-financeiro": "DRE",
              "site-pedidos": "E-com",
              "site-carrinhos": "Carrinhos",
              "produtos": "Produtos",
              "clientes": "CRM",
              "disparo": "Disparo em massa",
              "marketing": "Marketing",
              "relatorios": "Relatórios",
              "config": "Config",
            }).map(([k, label]) => (
              <button key={k} className={"btn sm " + (route === k ? "accent" : "ghost")} onClick={() => setRoute(k)}>{label}</button>
            ))}
          </div>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
};

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