/* ===== Pago na Hora — App root ===== */

function App() {
  const initial = (location.hash || '').replace('#', '');
  const [view, setView] = useState(initial === 'onboarding' ? 'onboarding' : 'app');
  const [role, setRole] = useState('pj');
  const [pjEntity, setPjEntity] = useState({ name: 'Estúdio Norte', initials: 'EN' });
  const [section, setSection] = useState('overview');
  const [drawer, setDrawer] = useState(null);
  const [payOpen, setPayOpen] = useState(initial === 'new');
  const [payPreset, setPayPreset] = useState(null);
  const [success, setSuccess] = useState(null);
  const [toast, setToast] = useState(null);

  useEffect(() => {
    const onHash = () => {
      const h = (location.hash || '').replace('#', '');
      if (h === 'onboarding') setView('onboarding');
      else if (h === 'new') { setView('app'); setPayOpen(true); }
      else setView('app');
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  useEffect(() => {
    if (toast) { const t = setTimeout(() => setToast(null), 3200); return () => clearTimeout(t); }
  }, [toast]);

  const openNew = (preset) => { setPayPreset(preset || null); setPayOpen(true); };
  const closeDrawer = () => setDrawer(null);

  const finishPay = (result) => {
    setPayOpen(false);
    setPayPreset(null);
    if (location.hash === '#new') history.replaceState(null, '', location.pathname);
    setSuccess(result);
  };

  // ---------- ONBOARDING ----------
  if (view === 'onboarding') {
    return (
      <Onboarding
        goLanding={() => { location.href = 'https://pagonahora.com/'; }}
        onDone={(r) => { setRole(r); setSection('overview'); setView('app'); history.replaceState(null, '', location.pathname + '#dashboard'); setToast('Conta criada! Bem-vindo à Pago na Hora.'); }}
      />
    );
  }

  // ---------- APP ----------
  const titles = {
    pj: {
      overview: { t: 'Visão geral', s: pjEntity.name + ' · PJ · Junho 2026', search: 'Buscar entidade, contrato ou pagamento…' },
      assistant: { t: 'Assistente', s: 'Sua IA da Pago na Hora', noSearch: true },
      payments: { t: 'Pagar', s: 'Pagamentos enviados, agendados e pendentes', search: 'Buscar pagamento…' },
      receivables: { t: 'Receber', s: 'Entradas previstas, aprovadas e recebidas', search: 'Buscar entrada…' },
      providers: { t: 'Entidades', s: '37 entidades conectadas', search: 'Buscar entidade…' },
      contracts: { t: 'Contratos', s: 'Modelos e assinaturas', search: 'Buscar contrato…' },
      documents: { t: 'Documentos', s: 'Contratos, notas e comprovantes', search: 'Buscar documento…' },
    },
    pf: {
      overview: { t: 'Visão geral', s: 'Marina Alves · PF · Junho 2026', search: 'Buscar entidade…' },
      assistant: { t: 'Assistente', s: 'Sua IA da Pago na Hora', noSearch: true },
      payments: { t: 'Pagar', s: 'Pagamentos enviados, agendados e pendentes', search: 'Buscar pagamento…' },
      receivables: { t: 'Receber', s: 'Entradas previstas, aprovadas e recebidas', search: 'Buscar entrada…' },
      contracts: { t: 'Contratos', s: 'Seus contratos e assinaturas', search: 'Buscar contrato…' },
      documents: { t: 'Documentos', s: 'Contratos, notas e comprovantes', search: 'Buscar documento…' },
    },
  };
  const meta = titles[role][section] || titles[role].overview;

  let body;
  if (section === 'assistant') body = <Assistant key={role} role={role} />;
  else if (role === 'pj') {
    if (section === 'overview') body = <OverviewPJ onNew={() => openNew()} openProvider={setDrawer} />;
    else if (section === 'payments') body = <PaymentsPJ onNew={() => openNew()} openProvider={setDrawer} />;
    else if (section === 'receivables') body = <ReceivablesPF />;
    else if (section === 'providers') body = <ProvidersPJ openProvider={setDrawer} />;
    else if (section === 'contracts') body = <ContractsView role="pj" onNew={() => openNew()} />;
    else body = <DocumentsView role="pj" />;
  } else {
    if (section === 'overview') body = <OverviewPF />;
    else if (section === 'payments') body = <PaymentsPJ onNew={() => openNew()} openProvider={setDrawer} />;
    else if (section === 'receivables') body = <ReceivablesPF />;
    else if (section === 'contracts') body = <ContractsView role="pf" />;
    else body = <DocumentsView role="pf" />;
  }

  return (
    <div className="app">
      <Sidebar role={role} setRole={setRole} section={section} setSection={setSection} onNew={() => openNew()} pjEntity={pjEntity} setPjEntity={setPjEntity} />
      <div className="main">
        <Topbar title={meta.t} sub={meta.s} search={meta.search} noSearch={meta.noSearch} />
        {body}
      </div>

      {drawer && <ProviderDrawer provider={drawer} onClose={closeDrawer} onPay={(pv) => { closeDrawer(); openNew(pv); }} />}
      {payOpen && <NewPayment preset={payPreset} onClose={() => { setPayOpen(false); if (location.hash === '#new') history.replaceState(null, '', location.pathname); }} onDone={finishPay} />}
      {success && <PaySuccess result={success} onClose={() => { setSuccess(null); setSection('payments'); }} />}

      {toast && (
        <div className="toast">
          <span className="ic"><Icon name="check" size={16} color="var(--green)" sw={3} /></span>
          {toast}
        </div>
      )}
    </div>
  );
}

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