// App.jsx — Main application shell
'use strict';
const { useState, useCallback } = React;

const DEFAULT_COMPANY = {
  name:    'JuFlow Digital',
  cnpj:    '12.345.678/0001-90',
  email:   'contato@juflow.com.br',
  phone:   '(11) 98765-0000',
  address: 'Rua das Inovações, 1024 — Centro, São Paulo/SP',
  website: 'www.juflow.com.br',
  terms:   'Garantia de 90 dias para serviços e 180 dias para peças. Equipamentos não retirados em 60 dias serão cobrado taxa de armazenagem.',
};

function App() {
  const { clients: initClients, workOrders: initOS, appointments: initAppts,
    services: initSvcs, transactions: initTrx, revenueChart, notifications: initNotifs } = window.MockData;

  const [isLoggedIn,   setIsLoggedIn]   = useState(false);
  const [user,         setUser]         = useState(null);
  const [page,         setPage]         = useState('dashboard');
  const [mobileOpen,   setMobileOpen]   = useState(false);
  const [toasts,       setToasts]       = useState([]);
  const [globalSearch, setGlobalSearch] = useState('');

  const [clients,      setClients]      = useState(initClients);
  const [workOrders,   setWorkOrders]   = useState(initOS);
  const [appointments, setAppointments] = useState(initAppts);
  const [services,     setServices]     = useState(initSvcs);
  const [transactions, setTransactions] = useState(initTrx);
  const [notifications,setNotifications]= useState(initNotifs);
  const [company,      setCompany]      = useState(DEFAULT_COMPANY);

  // Demo: nao persiste em localStorage. Toda vez que cliente atualiza a pagina,
  // tudo volta ao mockData.js / DEFAULT_COMPANY originais.
  const saveCompany = useCallback((data) => setCompany(data), []);

  // ── Auth ──────────────────────────────────────────────────────────────────
  const handleLogin  = u => { setUser(u); setIsLoggedIn(true); };
  const handleLogout = () => { setIsLoggedIn(false); setUser(null); setPage('dashboard'); };

  // ── Toast ─────────────────────────────────────────────────────────────────
  const addToast = useCallback(({ type='success', title, msg }) => {
    const id = Math.random().toString(36).slice(2);
    setToasts(ts => [...ts, { id, type, title, msg }]);
  }, []);
  const removeToast = useCallback(id => setToasts(ts => ts.filter(t => t.id !== id)), []);

  // ── Notifications ─────────────────────────────────────────────────────────
  const markAllRead = () => setNotifications(ns => ns.map(n => ({ ...n, read: true })));

  // ── CRUD helpers ──────────────────────────────────────────────────────────
  // Work Orders
  const addWO    = wo  => setWorkOrders(p => [wo, ...p]);
  const updateWO = (id, d) => setWorkOrders(p => p.map(x => x.id===id ? {...x,...d} : x));
  const deleteWO = id  => setWorkOrders(p => p.filter(x => x.id !== id));
  // Clients
  const addCli    = c  => setClients(p => [...p, c]);
  const updateCli = (id, d) => setClients(p => p.map(x => x.id===id ? {...x,...d} : x));
  const deleteCli = id => setClients(p => p.filter(x => x.id !== id));
  // Appointments
  const addAppt    = a  => setAppointments(p => [...p, a]);
  const updateAppt = (id, d) => setAppointments(p => p.map(x => x.id===id ? {...x,...d} : x));
  const deleteAppt = id => setAppointments(p => p.filter(x => x.id !== id));
  // Services
  const addSvc    = s  => setServices(p => [...p, s]);
  const updateSvc = (id, d) => setServices(p => p.map(x => x.id===id ? {...x,...d} : x));
  const deleteSvc = id => setServices(p => p.filter(x => x.id !== id));
  // Transactions
  const addTrx    = t  => setTransactions(p => [t, ...p]);
  const updateTrx = (id, d) => setTransactions(p => p.map(x => x.id===id ? {...x,...d} : x));
  const deleteTrx = id => setTransactions(p => p.filter(x => x.id !== id));

  // ── Render current page ───────────────────────────────────────────────────
  const renderPage = () => {
    const props = { addToast, clients, workOrders, appointments, services, transactions };
    switch (page) {
      case 'dashboard':
        return <Dashboard workOrders={workOrders} appointments={appointments} clients={clients}
          transactions={transactions} revenueChart={revenueChart} setPage={setPage}/>;
      case 'os':
        return <WorkOrders workOrders={workOrders} clients={clients} services={services} company={company}
          onAdd={addWO} onUpdate={updateWO} onDelete={deleteWO} addToast={addToast}/>;
      case 'clientes':
        return <Clients clients={clients} workOrders={workOrders}
          onAdd={addCli} onUpdate={updateCli} onDelete={deleteCli} addToast={addToast}/>;
      case 'agenda':
        return <CalendarPage appointments={appointments} clients={clients}
          onAdd={addAppt} onUpdate={updateAppt} onDelete={deleteAppt} addToast={addToast}/>;
      case 'servicos':
        return <ServicesPage services={services} workOrders={workOrders}
          onAdd={addSvc} onUpdate={updateSvc} onDelete={deleteSvc} addToast={addToast}/>;
      case 'financeiro':
        return <Financial transactions={transactions} workOrders={workOrders}
          onAdd={addTrx} onUpdate={updateTrx} onDelete={deleteTrx}
          onUpdateWO={updateWO} addToast={addToast}/>;
      case 'relatorios':
        return <Reports workOrders={workOrders} transactions={transactions} clients={clients}/>;
      case 'configuracoes':
        return <Settings company={company} onSaveCompany={saveCompany} addToast={addToast}/>;
      default:
        return <Dashboard workOrders={workOrders} appointments={appointments} clients={clients}
          transactions={transactions} revenueChart={revenueChart} setPage={setPage}/>;
    }
  };

  if (!isLoggedIn) return <Login onLogin={handleLogin}/>;

  return (
    <div className="flex h-screen overflow-hidden bg-surface no-print" style={{ fontFamily: 'Inter, system-ui, sans-serif' }}>
      <Sidebar page={page} setPage={setPage} user={user} onLogout={handleLogout}
        mobileOpen={mobileOpen} onMobileClose={() => setMobileOpen(false)}/>

      <div className="flex flex-col flex-1 overflow-hidden min-w-0">
        <Header page={page} onMenuToggle={() => setMobileOpen(v => !v)}
          notifications={notifications} onMarkRead={markAllRead}
          globalSearch={globalSearch} setGlobalSearch={setGlobalSearch}
          onSearchNav={() => {
            const q = globalSearch.toLowerCase();
            if (!q) return;
            const hasOS = workOrders.some(o => o.clientName?.toLowerCase().includes(q) || o.num?.includes(q));
            const hasCli = clients.some(c => c.name?.toLowerCase().includes(q));
            if (hasOS) setPage('os');
            else if (hasCli) setPage('clientes');
          }}/>

        <main className="flex-1 overflow-y-auto p-4 md:p-6" style={{ background: '#F5F7FA' }}>
          <div className="max-w-screen-xl mx-auto">
            {renderPage()}
          </div>
        </main>
      </div>

      <ToastContainer toasts={toasts} removeToast={removeToast}/>
    </div>
  );
}

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