
// ============================================================
// JuFlow — Main App (state + routing)
// ============================================================
const { useState: useStApp, useReducer, useCallback: useCbApp } = React;
const UAPP = window.JFUtils;

const App = () => {
  // ── Auth ──────────────────────────────────────────────
  const [loggedIn, setLoggedIn] = useStApp(false);

  // ── Navigation ────────────────────────────────────────
  const [page, setPage] = useStApp('dashboard');
  const [sidebarCollapsed, setSidebarCollapsed] = useStApp(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useStApp(false);
  const isMobile = useIsMobile(900);

  // ── Data (mutable state) ──────────────────────────────
  const [appointments, setAppointments] = useStApp(window.JF.APPOINTMENTS);
  const [clients, setClients] = useStApp(window.JF.CLIENTS);

  // ── Agenda state ──────────────────────────────────────
  const [agendaDate, setAgendaDate] = useStApp(new Date(window.JF.TODAY));
  const [agendaView, setAgendaView] = useStApp('daily');

  // ── Modals ────────────────────────────────────────────
  const [apptModal, setApptModal] = useStApp(null);       // { type:'new'|'detail', data:{} }
  const [clientDetail, setClientDetail] = useStApp(null); // client object

  // ── Toasts ────────────────────────────────────────────
  const [toasts, setToasts] = useStApp([]);

  const addToast = useCbApp((message, type = 'success') => {
    const id = Date.now() + Math.random();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3500);
  }, []);

  // ── Appointment actions ───────────────────────────────
  const handleSaveAppt = (newAppt) => {
    setAppointments(prev => {
      const exists = prev.find(a => a.id === newAppt.id);
      if (exists) return prev.map(a => a.id === newAppt.id ? newAppt : a);
      return [...prev, newAppt];
    });
  };

  const handleCancelAppt = (apptId) => {
    setAppointments(prev => prev.map(a => a.id === apptId ? { ...a, status:'cancelled' } : a));
  };

  // ── Client actions ────────────────────────────────────
  const handleSaveClient = (newClient) => {
    setClients(prev => {
      const exists = prev.find(c => c.id === newClient.id);
      if (exists) return prev.map(c => c.id === newClient.id ? newClient : c);
      return [...prev, newClient];
    });
  };

  // ── Navigation helpers ────────────────────────────────
  const openNewAppt  = (initial = {}) => setApptModal({ type:'new', data:initial });
  const openApptDetail = (appt) => setApptModal({ type:'detail', data:appt });
  const closeApptModal = () => setApptModal(null);

  const navigateTo = (p) => {
    setPage(p);
    setClientDetail(null);
    setApptModal(null);
    setMobileMenuOpen(false);
  };

  // ── Login screen ──────────────────────────────────────
  if (!loggedIn) {
    return (
      <>
        <LoginScreen onLogin={() => setLoggedIn(true)} />
        <Toast toasts={toasts} />
      </>
    );
  }

  // ── Main layout ───────────────────────────────────────
  const renderPage = () => {
    switch (page) {
      case 'dashboard':
        return <Dashboard appointments={appointments} onNavigate={navigateTo} addToast={addToast} onNewAppointment={() => openNewAppt()} />;

      case 'agenda':
        return (
          <Agenda
            appointments={appointments}
            date={agendaDate}
            onDateChange={setAgendaDate}
            view={agendaView}
            onViewChange={setAgendaView}
            onOpenNew={openNewAppt}
            onOpenAppt={openApptDetail}
          />
        );

      case 'clientes':
        return (
          <Clientes
            appointments={appointments}
            onViewClient={setClientDetail}
            onNewAppt={openNewAppt}
          />
        );

      case 'atendimentos':
        return (
          <Atendimentos
            appointments={appointments}
            onViewAppt={openApptDetail}
            onNewAppt={openNewAppt}
          />
        );

      case 'servicos':
        return <Servicos addToast={addToast} />;

      case 'profissionais':
        return <Profissionais appointments={appointments} addToast={addToast} />;

      case 'financeiro':
        return <Financeiro appointments={appointments} addToast={addToast} />;

      case 'marketing':
        return <Marketing appointments={appointments} addToast={addToast} />;

      case 'relatorios':
        return <Relatorios appointments={appointments} />;

      case 'configuracoes':
        return <Configuracoes addToast={addToast} />;

      default:
        return <Dashboard appointments={appointments} onNavigate={navigateTo} addToast={addToast} onNewAppointment={() => openNewAppt()} />;
    }
  };

  return (
    <div style={{ display:'flex', height:'100dvh', overflow:'hidden', background:'#F5F7FA', fontFamily:"'Inter', system-ui, sans-serif" }}>
      {/* Sidebar */}
      <Sidebar
        page={page}
        onNavigate={navigateTo}
        collapsed={sidebarCollapsed}
        onToggle={() => setSidebarCollapsed(c => !c)}
        isMobile={isMobile}
        mobileOpen={mobileMenuOpen}
        onMobileClose={() => setMobileMenuOpen(false)}
      />

      {/* Main content */}
      <div style={{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden', minWidth:0 }}>
        {/* Header */}
        <Header
          page={page}
          appointments={appointments}
          onNavigate={navigateTo}
          onLogout={() => setLoggedIn(false)}
          onMenuOpen={() => setMobileMenuOpen(true)}
          isMobile={isMobile}
        />

        {/* Page content */}
        <main style={{
          flex:1, overflow:'auto',
          paddingBottom: 'var(--safe-bottom)',
        }}>
          {renderPage()}
        </main>
      </div>

      {/* Client detail overlay */}
      {clientDetail && (
        <ClientDetail
          client={clientDetail}
          appointments={appointments}
          onClose={() => setClientDetail(null)}
          onNewAppt={openNewAppt}
          addToast={addToast}
        />
      )}

      {/* Appointment modals */}
      {apptModal?.type === 'detail' && (
        <ApptDetailModal
          appt={apptModal.data}
          onClose={closeApptModal}
          onEdit={(appt) => setApptModal({ type:'new', data:appt })}
          onCancel={handleCancelAppt}
          addToast={addToast}
        />
      )}

      {apptModal?.type === 'new' && (
        <NewApptModal
          open={true}
          onClose={closeApptModal}
          initial={apptModal.data}
          appointments={appointments}
          onSave={handleSaveAppt}
          addToast={addToast}
        />
      )}

      {/* Toasts */}
      <Toast toasts={toasts} />
    </div>
  );
};

// ── Mount ────────────────────────────────────────────────
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
