function App() {
  const { state, dispatch, notify } = useStore();
  usePersistStore();

  React.useEffect(() => { if (window.SupaBase) loadFromSupabase(dispatch); }, []);

  const { view, cart, notif, shop, currency, printer, cashier, payMode, cashGiven, ticketNum, logoUrl } = state;
  const totalQty = cartQty(cart);

  async function handlePrint() {
    if (!cart.length) return;
    const now = new Date();

    // Lire le total avec réduction depuis localStorage
    const freshReduit = parseFloat(localStorage.getItem('pos_total_reduit') || '0');
    const totalBrut   = cartTotal(cart);
    const totalFinal  = (freshReduit > 0 && freshReduit < totalBrut) ? freshReduit : totalBrut;

    const html = buildTicketHTML({ shop, cart, currency, printer, cashier, payMode, cashGiven, ticketNum, now, logoUrl, totalOverride: totalFinal });

    // Sauvegarde vente
    const vente = {
      id:         ticketNum,
      timestamp:  now.toISOString(),
      date:       now.toLocaleDateString('fr-FR'),
      heure:      now.toLocaleTimeString('fr-FR', {hour:'2-digit', minute:'2-digit'}),
      caissier:   cashier ? cashier.name : '',
      caissierId: cashier ? cashier.id : '',
      articles:   cart.length,
      cart:       JSON.parse(JSON.stringify(cart)),
      total:      totalFinal,
      totalBrut:  totalBrut,
      devise:     currency.symbol,
      payMode:    payMode,
      cashGiven:  cashGiven,
    };

    try {
      const historique = JSON.parse(localStorage.getItem('pos_historique') || '[]');
      historique.unshift(vente);
      localStorage.setItem('pos_historique', JSON.stringify(historique.slice(0, 500)));
      const boutiqueId = localStorage.getItem('pos_boutique_id');
      if (boutiqueId) window.SupaBase.saveVente(boutiqueId, vente);
    } catch(e) {}

    // Impression thermique locale
    const clientData = JSON.parse(localStorage.getItem('pos_client_actif') || 'null');
    const ticketText = buildTicketLines({ shop, cart, currency, printer, cashier, payMode, cashGiven, ticketNum: state.ticketNum, now, totalOverride: totalFinal, client: clientData });
    let printed = false;
    try {
      const res = await fetch('http://localhost:8765', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ lines: ticketText, barcode: state.ticketNum ? String(state.ticketNum) : null, logo: logoUrl || '' }),
      });
      if (res.ok) printed = true;
    } catch(e) {}

    // Impression navigateur si pas d'imprimante
    if (!printed) {
      const w = window.open('', '_blank', 'width=400,height=600');
      if (w) { w.document.write(html); w.document.close(); setTimeout(() => { w.print(); w.close(); }, 500); }
    }

    // Reset
    localStorage.removeItem('pos_total_reduit');
    dispatch({ type: 'CLEAR_CART' });
    dispatch({ type: 'SET_CASH_GIVEN', payload: 0 });
    dispatch({ type: 'INCREMENT_TICKET' });
    notify('✅ Vente enregistrée - Caisse prête !');
  }

  return (
    <div className="app-shell">
      {notif && <div className={`toast toast-${notif.type}`}>{notif.msg}</div>}
      <Topbar onPrint={handlePrint} cartCount={totalQty} />
      {view === 'caisse'     && <CaisseScreen onPrint={handlePrint} />}
      {view === 'catalogue'  && <CatalogueScreen />}
      {view === 'parametres' && <ParametresScreen />}
      {view === 'dashboard'  && <DashboardScreen />}
      {view === 'clients'    && <ClientsScreen />}
      {view === 'stock'      && <StockScreen />}
      {view === 'historique' && <HistoriqueScreen />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  React.createElement(StoreProvider, null, React.createElement(App))
);
