// App principal — Metal Padrão Sistema de Vendas

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "sidebarMode": "expanded",
  "listView": "table",
  "density": "regular",
  "accent": "#ffc431"
}/*EDITMODE-END*/;

function App() {
  const [user, setUser] = React.useState(null);
  const [route, setRoute] = React.useState("vendas");
  const [vendas, setVendas] = React.useState(() => window.MP_DATA.vendas);
  const [openVenda, setOpenVenda] = React.useState(null);
  const [newOpen, setNewOpen] = React.useState(false);
  const [mobileNav, setMobileNav] = React.useState(false);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Sync tweaks to DOM
  React.useEffect(() => {
    document.documentElement.dataset.density = t.density;
    document.documentElement.style.setProperty("--mp-yellow", t.accent);
  }, [t.density, t.accent]);

  const handleAddEntrada = (op, payload) => {
    setVendas(vs => vs.map(v => v.op === op
      ? { ...v, entradas: [...v.entradas, { id: Date.now(), ...payload }] }
      : v));
    setOpenVenda(curr => {
      if (!curr || curr.op !== op) return curr;
      return { ...curr, entradas: [...curr.entradas, { id: Date.now(), ...payload }] };
    });
  };
  const handleAddFat = (op, payload) => {
    setVendas(vs => vs.map(v => v.op === op
      ? { ...v, faturamentos: [...v.faturamentos, payload] }
      : v));
    setOpenVenda(curr => {
      if (!curr || curr.op !== op) return curr;
      return { ...curr, faturamentos: [...curr.faturamentos, payload] };
    });
  };
  const handleNova = (payload) => {
    const op = payload.op;
    const venda = { ...payload, faturamentos: [], entradas: [] };
    setVendas(vs => [venda, ...vs]);
    setNewOpen(false);
    setOpenVenda(venda);
  };

  if (!user) return <LoginScreen onLogin={setUser} />;

  // Next OP (sequencial)
  const maxOp = Math.max(0, ...vendas.map(v => parseInt(v.op, 10)));
  const proxOp = String(maxOp + 1).padStart(3, "0");

  const routes = {
    vendas: {
      title: "Vendas",
      crumb: "Módulo · vendas",
      content: <VendasList vendas={vendas} onOpen={setOpenVenda} onNew={() => setNewOpen(true)} view={t.listView} />
    },
    clientes:   { title: "Clientes",   crumb: "Cadastros",  content: <ClientesPage vendas={vendas} /> },
    vendedores: { title: "Vendedores", crumb: "Cadastros",  content: <VendedoresPage vendas={vendas} /> },
    producao:   { title: "Produção",   crumb: "Em breve",   content: <SoonPage title="Produção" hint="Acompanhamento da fila de produção, alocação por OP e prazo de entrega." /> },
    relatorios: { title: "Relatórios", crumb: "Em breve",   content: <SoonPage title="Relatórios" hint="Faturamento mensal, ranking de vendedores, comparativo previsto × realizado." /> },
  };

  const current = routes[route];

  return (
    <div className="shell" data-sidebar={t.sidebarMode} data-mobile-nav={mobileNav ? "open" : "closed"}>
      <Sidebar route={route} setRoute={(r) => { setRoute(r); setMobileNav(false); }} user={user} onLogout={() => setUser(null)} />

      <div className="main">
        <Topbar title={current.title} crumb={current.crumb} onToggleMobile={() => setMobileNav(v => !v)} />
        <div className="page">{current.content}</div>
      </div>

      <VendaDetail
        venda={openVenda}
        onClose={() => setOpenVenda(null)}
        onAddEntrada={handleAddEntrada}
        onAddFaturamento={handleAddFat}
      />
      <NovaVendaModal
        open={newOpen}
        onClose={() => setNewOpen(false)}
        onSave={handleNova}
        proxOp={proxOp}
      />

      <TweaksPanel>
        <TweakSection label="Layout" />
        <TweakRadio
          label="Sidebar"
          value={t.sidebarMode}
          options={["expanded", "collapsed"]}
          onChange={(v) => setTweak("sidebarMode", v)}
        />
        <TweakRadio
          label="Lista de vendas"
          value={t.listView}
          options={["table", "cards"]}
          onChange={(v) => setTweak("listView", v)}
        />
        <TweakRadio
          label="Densidade"
          value={t.density}
          options={["regular", "compact"]}
          onChange={(v) => setTweak("density", v)}
        />
        <TweakSection label="Marca" />
        <TweakColor
          label="Amarelo"
          value={t.accent}
          options={["#ffc431", "#ffd556", "#e8a800", "#0d0d0d"]}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakSection label="Demonstração" />
        <TweakButton onClick={() => setUser(null)}>Sair (voltar ao login)</TweakButton>
      </TweaksPanel>
    </div>
  );
}

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