// ─────────────────────────────────────────────────────────────────────────────
// boot-entry.jsx — punto di render dell'app + sistema di notifiche (toast).
//
// Renderizza <Root/>, che avvolge il componente di design <App/> e monta anche
// un <ToastHost/> per le notifiche interne (niente alert del browser).
//
//   • window.__BI_RERENDER__ → forza un re-render (dopo window.__BI_REFRESH__),
//     così l'app rilegge i dati freschi SENZA remount (sessione/stato intatti).
//   • window.__BI_ON_401__   → sessione scaduta: torna al login.
//   • window.__toast(msg,type)→ mostra una notifica interna (success|error|info),
//     in basso a destra, nello stile del design.
//
// Caricato per ULTIMO (vedi shared/jsx-order.json).
// ─────────────────────────────────────────────────────────────────────────────

(function () {
  const { useState: useStateBoot, useEffect: useEffectBoot } = React;

  // Icone inline (self-contained, nessuna dipendenza dall'ordine di caricamento)
  const IconCheck = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
  );
  const IconX = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
  );

  let _toastSeq = 0;

  function ToastHost() {
    const [toasts, setToasts] = useStateBoot([]);
    useEffectBoot(() => {
      window.__toast = (message, type = 'success') => {
        const id = ++_toastSeq;
        setToasts((list) => [...list, { id, message, type }]);
        setTimeout(() => setToasts((list) => list.filter((t) => t.id !== id)), 3500);
      };
      return () => { window.__toast = null; };
    }, []);

    if (!toasts.length) return null;
    return (
      <div className="fixed bottom-6 right-6 z-toast flex flex-col items-end gap-2" role="status" aria-live="polite">
        {toasts.map((t) => {
          const bg = t.type === 'error' ? 'var(--danger-500)'
            : t.type === 'info' ? 'var(--info-700)'
            : 'var(--success-500)';
          return (
            <div key={t.id}
              className="px-5 py-3 rounded-md shadow-popover flex items-center gap-2.5"
              style={{ background: bg, color: 'var(--text-inverse)' }}>
              {t.type === 'error' ? <IconX /> : <IconCheck />}
              <span className="text-[14px] font-medium">{t.message}</span>
            </div>
          );
        })}
      </div>
    );
  }

  function Root() {
    const [v, setV] = useStateBoot(0);
    useEffectBoot(() => {
      window.__BI_RERENDER__ = () => setV((x) => x + 1);
      window.__BI_ON_401__ = () => window.location.reload();
      // Helper export: scarica un CSV (header = array di stringhe, rows = array di array)
      window.__csv = (filename, header, rows) => {
        try {
          const esc = (c) => '"' + String(c == null ? '' : c).replace(/"/g, '""') + '"';
          const body = [header, ...rows].map((r) => r.map(esc).join(';')).join('\n');
          const blob = new Blob(['﻿' + body], { type: 'text/csv;charset=utf-8;' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url; a.download = filename || 'export.csv';
          document.body.appendChild(a); a.click(); a.remove();
          setTimeout(() => URL.revokeObjectURL(url), 1000);
          if (window.__toast) window.__toast('Esportazione completata', 'success');
        } catch (e) { if (window.__toast) window.__toast('Esportazione non riuscita', 'error'); }
      };
      // Helper stampa: apre la finestra di stampa del browser (salva come PDF)
      window.__print = () => { try { window.print(); } catch (e) {} };
      // Helper export PDF mirato: apre una finestra con SOLO il documento formattato e stampa.
      window.__printDoc = (title, innerHtml) => {
        try {
          const w = window.open('', '_blank', 'width=860,height=920');
          if (!w) { if (window.__toast) window.__toast('Abilita i popup per esportare il PDF', 'error'); return; }
          w.document.write(
            '<!doctype html><html><head><meta charset="utf-8"><title>' + title + '</title><style>' +
            '*{box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Inter,sans-serif;color:#1d1d1f;margin:0;padding:44px;font-size:13px}' +
            'h1{font-size:22px;margin:0;letter-spacing:-.01em}.brand{font-size:12px;color:#007aff;font-weight:700;letter-spacing:.06em}.muted{color:#6e6e73}' +
            '.row{display:flex;justify-content:space-between;align-items:flex-start}' +
            '.meta{display:grid;grid-template-columns:1fr 1fr;gap:10px 28px;margin:22px 0;padding:16px 18px;border:1px solid #e6e6ea;border-radius:10px}' +
            '.meta .l{font-size:10px;text-transform:uppercase;letter-spacing:.06em;color:#6e6e73;display:block;margin-bottom:2px}' +
            'table{width:100%;border-collapse:collapse;margin-top:6px}th,td{text-align:left;padding:9px 6px;border-bottom:1px solid #eee}' +
            'th{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:#6e6e73}td.n,th.n{text-align:right}' +
            '.tot{display:flex;justify-content:flex-end;gap:28px;margin-top:18px;font-size:17px;font-weight:600}' +
            '@media print{body{padding:0}}</style></head><body>' + innerHtml +
            '<script>window.onload=function(){setTimeout(function(){window.print();},120);}<\/script></body></html>'
          );
          w.document.close();
        } catch (e) { if (window.__toast) window.__toast('Esportazione non riuscita', 'error'); }
      };
      return () => { window.__BI_RERENDER__ = null; window.__csv = null; window.__print = null; window.__printDoc = null; };
    }, []);
    const App = window.App;
    // __v cambia ad ogni refresh → App si ri-renderizza e rilegge i dati globali.
    return (
      <React.Fragment>
        <App __v={v} />
        <ToastHost />
      </React.Fragment>
    );
  }

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