// ──────────────────────────── Dashboard ────────────────────────────

// Grafico "Vendite per ora": colonne pulite (incasso di ogni ora), colonna del
// picco evidenziata. Niente linea/puntini: massima leggibilità.
const HourlyBars = ({ data }) => {
  const PLOT = 184; // altezza area grafico in px (niente % → niente barre collassate)
  const max = Math.max(...data.map(d => d.v)) || 1;
  const peakIdx = data.reduce((bi, d, i, a) => (d.v > a[bi].v ? i : bi), 0);
  return (
    <div className="pt-2">
      <div className="flex items-end gap-2" style={{ height: `${PLOT}px` }}>
        {data.map((d, i) => {
          const empty = d.v === 0;
          const hpx = empty ? 0 : Math.max(8, (d.v / max) * PLOT);
          const isPeak = i === peakIdx && !empty;
          return (
            <div key={i} className="group flex-1 h-full flex items-end justify-center">
              {empty ? (
                <div className="w-full h-[6px] rounded-sm bg-line2"></div>
              ) : (
                <div className="w-full rounded-t-lg relative transition-all duration-fast ease-standard hover:brightness-105"
                  style={{
                    height: `${hpx}px`,
                    background: isPeak
                      ? 'linear-gradient(180deg, var(--accent-indigo), var(--accent-blue))'
                      : 'linear-gradient(180deg, var(--accent-blue), color-mix(in srgb, var(--accent-blue) 55%, transparent))',
                    boxShadow: isPeak ? '0 4px 12px -3px color-mix(in srgb, var(--accent-blue) 45%, transparent)' : 'none',
                  }}>
                  {/* etichetta valore al passaggio del mouse */}
                  <div className="absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-0.5 rounded-md bg-[var(--bg-selected)] text-[var(--accent-blue)] text-[10.5px] num font-medium opacity-0 group-hover:opacity-100 transition-all duration-fast ease-standard whitespace-nowrap z-10">
                    {fmtEur(d.v)}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
      {/* Etichette ore (allineate alle colonne) */}
      <div className="flex gap-2 mt-2">
        {data.map((d, i) => (
          <div key={i} className={`flex-1 num text-[11px] text-center ${i === peakIdx && d.v > 0 ? 'text-[var(--accent-blue)] font-semibold' : 'text-muted'}`}>{d.h}</div>
        ))}
      </div>
    </div>
  );
};

const Dashboard = ({ onShortcut, session, activeStoreId = STORE.id }) => {
  const isAll = activeStoreId === 'all';
  const activeStore = isAll
    ? { name: 'Tutti i negozi', id: 'all', address: '4 punti vendita · vista aggregata' }
    : STORES.find(s => s.id === activeStoreId) || STORE;
  const cassaAperta = session?.fondo != null;

  // Statistiche vendite per venditore (storico completo, dal backend)
  const [sellerStats, setSellerStats] = React.useState(null);
  React.useEffect(() => {
    let alive = true;
    if (window.__API__ && window.__API__.get) {
      window.__API__.get('/api/stats/sellers?storeId=' + encodeURIComponent(activeStoreId))
        .then(r => { if (alive && r && r.ok) setSellerStats(r.sellers); });
    }
    return () => { alive = false; };
  }, [activeStoreId]);

  // Notifiche reali (stesso endpoint della campanella) per la card "Notifiche & promemoria"
  const [notifiche, setNotifiche] = React.useState(null);
  React.useEffect(() => {
    let alive = true;
    if (window.__API__ && window.__API__.get) {
      window.__API__.get('/api/notifiche').then(r => { if (alive && r && r.ok) setNotifiche(r.items || []); });
    }
    return () => { alive = false; };
  }, [activeStoreId]);
  // palette per tipo (coerente con la campanella in shell.jsx)
  const NOTIF_BG = { scorta:'var(--warning-50)', scadenza:'var(--danger-50)', richiesta:'rgba(0,122,255,0.12)', trasferimento:'rgba(0,122,255,0.12)', cassa:'rgba(0,122,255,0.12)', turno:'var(--warning-50)' };
  const NOTIF_FG = { scorta:'var(--warning-700)', scadenza:'var(--danger-700)', richiesta:'var(--accent-blue)', trasferimento:'var(--accent-blue)', cassa:'var(--accent-blue)', turno:'var(--warning-700)' };
  const NOTIF_ICON = { scorta:'Box', scadenza:'Clock', richiesta:'Box', trasferimento:'Truck', cassa:'Wallet', turno:'Clock' };

  // Calcola KPI in base al negozio selezionato (singolo o aggregato)
  // "Tutti" = solo i negozi nello scope del principal (Admin/Manager: tutti; Area Manager: la sua area)
  const _scope = window.__SESSION__?.op?.scopeStores;
  const scopedStores = (!_scope || _scope === 'all') ? STORES : STORES.filter(s => _scope.includes(s.id));

  let t, hourlyData, topCatData, recentReceipts;
  if (isAll) {
    const allData = scopedStores.map(s => TODAY_STORES[s.id]).filter(Boolean);
    const totalRevenue     = allData.reduce((s, d) => s + d.revenue, 0);
    const totalRevenuePrev = allData.reduce((s, d) => s + d.revenuePrev, 0);
    const totalReceipts    = allData.reduce((s, d) => s + d.receipts, 0);
    const totalReceiptsPrev= allData.reduce((s, d) => s + d.receiptsPrev, 0);
    const totalItems       = allData.reduce((s, d) => s + d.items, 0);
    const totalItemsPrev   = allData.reduce((s, d) => s + d.itemsPrev, 0);
    t = {
      revenue:     totalRevenue,    revenuePrev:     totalRevenuePrev,
      receipts:    totalReceipts,   receiptsPrev:    totalReceiptsPrev,
      avgTicket:   totalReceipts > 0 ? totalRevenue / totalReceipts : 0,
      avgTicketPrev: totalReceiptsPrev > 0 ? totalRevenuePrev / totalReceiptsPrev : 0,
      items:       totalItems,      itemsPrev:       totalItemsPrev,
      returns:     allData.reduce((s, d) => s + (d.returns || 0), 0),
      cashBreakdown: {
        contanti: allData.reduce((s, d) => s + d.cashBreakdown.contanti, 0),
        carta:    allData.reduce((s, d) => s + d.cashBreakdown.carta, 0),
        bonifico: allData.reduce((s, d) => s + d.cashBreakdown.bonifico, 0),
        buoni:    allData.reduce((s, d) => s + (d.cashBreakdown.buoni || 0), 0),
      },
    };
    // Somma oraria per i negozi nello scope
    hourlyData = HOURLY.map((h, i) => ({
      h: h.h,
      v: scopedStores.reduce((s, st) => s + ((HOURLY_STORES[st.id] || [])[i]?.v || 0), 0),
    }));
    // Aggrega categorie (solo negozi nello scope)
    const catMap = {};
    scopedStores.forEach(st => {
      (TOP_CATEGORIES_STORES[st.id] || []).forEach(c => { catMap[c.name] = (catMap[c.name] || 0) + c.value; });
    });
    const totalCatVal = Object.values(catMap).reduce((s, v) => s + v, 0) || 1;
    topCatData = Object.entries(catMap).sort((a, b) => b[1] - a[1]).slice(0, 6)
      .map(([name, value]) => ({ name, value, share: Math.round(value / totalCatVal * 100) }));
    recentReceipts = RECENT_RECEIPTS;
  } else {
    t             = TODAY_STORES[activeStoreId] || TODAY;
    hourlyData    = HOURLY_STORES[activeStoreId] || HOURLY;
    topCatData    = TOP_CATEGORIES_STORES[activeStoreId] || TOP_CATEGORIES;
    recentReceipts = RECENT_RECEIPTS.filter(r => !r.store || r.store === activeStoreId);
  }

  const peakHour  = hourlyData.reduce((best, d) => d.v > best.v ? d : best, { h: '—', v: 0 });

  return (
    <>
      <Topbar
        eyebrow={activeStore.name + (activeStore.address ? ' · ' + activeStore.address : '')}
        title="Andamento di oggi"
        right={<>
          <Btn variant="outline" size="md" leading={<I.Refresh size={16}/>} onClick={async () => { if (window.__BI_REFRESH__) await window.__BI_REFRESH__(); if (window.__toast) window.__toast('Dati aggiornati', 'success'); }}>Aggiorna</Btn>
          <Btn variant="ink" size="md" leading={<I.Cash size={16}/>} onClick={() => onShortcut('pos')}>Apri Cassa</Btn>
        </>}
      />

      <div className="px-7 py-6 space-y-6 max-w-[1400px]">
        {/* KPI strip */}
        <Card padded={false}>
          <div className="flex divide-x divide-line">
            <Stat label="Incasso oggi"    value={fmtEur(t.revenue)}    delta={+((t.revenue/t.revenuePrev - 1) * 100)} subtle="vs ieri" />
            <Stat label="Scontrini"       value={t.receipts}            delta={+((t.receipts/t.receiptsPrev - 1) * 100)} subtle="vs ieri" />
            <Stat label="Scontrino medio" value={fmtEur(t.avgTicket)}   delta={+((t.avgTicket/t.avgTicketPrev - 1) * 100)} subtle="vs ieri" />
            <Stat label="Pezzi venduti"   value={t.items}               delta={+((t.items/t.itemsPrev - 1) * 100)} subtle="vs ieri" />
          </div>
        </Card>

        {/* Row: hourly chart + shortcuts */}
        <div className="grid grid-cols-3 gap-6">
          <Card
            className="col-span-2"
            title="Vendite per ora"
            action={
              <div className="flex items-center gap-2">
                <Pill tone="neutral">Oggi</Pill>
                <span className="text-[12px] text-muted">apertura 10:00 – 20:00</span>
              </div>
            }
          >
            <HourlyBars data={hourlyData} />
            <div className="mt-4 flex items-center gap-6 text-[12px] text-muted">
              <span className="flex items-center gap-2"><span className="w-2.5 h-2.5 rounded-sm bg-[var(--accent-blue)]"></span>Incasso orario</span>
              <span>Ora di punta · <span className="text-ink font-medium">{peakHour.h}:00</span></span>
              <span>Picco · <span className="num text-ink font-medium">{fmtEur(peakHour.v)}</span></span>
            </div>
          </Card>

          <Card title="Scorciatoie rapide">
            <div className="grid grid-cols-2 gap-2.5">
              {[
                { id: 'pos',    icon: 'Cash',    label: 'Nuova vendita', sub: 'F2',  chip: 'chip-blue' },
                { id: 'pos',    icon: 'Return',  label: 'Reso',          sub: '⌥R', chip: 'chip-orange' },
                { id: 'catalogo', icon: 'Search', label: 'Cerca articolo', sub: '⌘K', chip: 'chip-cyan' },
                { id: 'anagrafiche', icon: 'User', label: 'Nuovo cliente', sub: '⌥C', chip: 'chip-purple' },
                { id: 'magazzino', icon: 'Box', label: 'Inventario', sub: '', chip: 'chip-green' },
                { id: 'documenti', icon: 'Receipt', label: 'Scontrini', sub: '', chip: 'chip-indigo' },
              ].map((s, i) => {
                const Ico = I[s.icon];
                return (
                  <button
                    key={i}
                    onClick={() => onShortcut(s.id)}
                    className="focus-ring text-left p-3.5 rounded-xl bg-surface shadow-sm transition-all duration-fast ease-standard hover:shadow-md hover:-translate-y-0.5 active:translate-y-0"
                  >
                    <div className="flex items-start justify-between">
                      <span className={`icon-chip ${s.chip}`}><Ico size={20} /></span>
                      {s.sub && <span className="num text-[10.5px] text-muted">{s.sub}</span>}
                    </div>
                    <div className="mt-3 text-[13.5px] font-medium text-ink">{s.label}</div>
                  </button>
                );
              })}
            </div>
          </Card>
        </div>

        {/* Row: vendite per venditore */}
        <Card title="Vendite per venditore" action={<Pill tone="neutral">Storico</Pill>}>
          {sellerStats == null ? (
            <div className="py-6 text-center text-muted text-[13.5px]">Caricamento…</div>
          ) : sellerStats.length === 0 ? (
            <div className="py-6 text-center text-muted text-[13.5px]">Nessuna vendita registrata.</div>
          ) : (() => {
            const max = Math.max(...sellerStats.map(s => s.total)) || 1;
            // Badge posizione: oro/argento/bronzo per i primi 3, neutro per gli altri
            const rankStyle = [
              { background: 'linear-gradient(140deg,#f6c844,#e0a512)', color: '#5a4300' },
              { background: 'linear-gradient(140deg,#d6dae0,#aab2bd)', color: '#3a3f47' },
              { background: 'linear-gradient(140deg,#e6a667,#c47f3e)', color: '#4a2c0e' },
            ];
            return (
              <div className="space-y-3">
                {sellerStats.map((s, i) => (
                  <div key={s.name}>
                    <div className="flex items-baseline justify-between mb-1.5">
                      <span className="text-[13.5px] text-ink flex items-center gap-2">
                        <span className="num text-[11px] font-semibold w-5 h-5 rounded-full flex items-center justify-center shrink-0"
                          style={rankStyle[i] || { background: 'var(--bg-selected)', color: 'var(--accent-blue)' }}>{i + 1}</span>
                        {s.name}
                      </span>
                      <span className="text-[12.5px] text-muted">
                        <span className="num text-ink font-medium">{fmtEur(s.total)}</span> · {s.count} vendite · media {fmtEur(s.avg)}
                      </span>
                    </div>
                    <div className="h-2 bg-line2 rounded-full overflow-hidden ml-7">
                      <div className="h-full rounded-full" style={{ width: `${Math.max(3, (s.total / max) * 100)}%`, background: i === 0 ? 'linear-gradient(90deg,var(--accent-indigo),var(--accent-blue))' : 'var(--accent-blue)' }}/>
                    </div>
                  </div>
                ))}
              </div>
            );
          })()}
        </Card>

        {/* Row: top categories + alerts */}
        <div className="grid grid-cols-3 gap-6">
          <Card title="Vendite per categoria" action={<Pill tone="neutral">Oggi</Pill>}>
            <div className="space-y-3.5">
              {topCatData.map((c, i) => (
                <div key={i}>
                  <div className="flex items-baseline justify-between mb-1.5">
                    <span className="text-[13.5px] text-ink">{c.name}</span>
                    <span className="num text-[13px] text-ink">{fmtEur(c.value)} <span className="text-muted">· {c.share}%</span></span>
                  </div>
                  <div className="h-1.5 bg-line2 rounded-full overflow-hidden">
                    <div className="h-full bg-[var(--accent-blue)] rounded-full" style={{ width: `${c.share * 3}%` }}></div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          <Card title="Notifiche & promemoria" action={notifiche && notifiche.length > 0 ? <Pill tone="neutral">{notifiche.length}</Pill> : null}>
            {notifiche == null ? (
              <div className="py-8 text-center text-muted text-[13px]">Caricamento…</div>
            ) : notifiche.length === 0 ? (
              <div className="py-10 flex flex-col items-center text-center gap-2 text-muted">
                <span className="w-12 h-12 rounded-2xl bg-paper flex items-center justify-center"><I.Bell size={22}/></span>
                <span className="text-[13px]">Tutto in ordine · nessun avviso</span>
              </div>
            ) : (
              <ul className="space-y-1.5">
                {notifiche.slice(0, 6).map((a) => {
                  const Ico = I[NOTIF_ICON[a.type] || 'Bell'] || I.Bell;
                  return (
                    <li key={a.id}>
                      <button onClick={() => a.section && onShortcut(a.section)}
                        className="w-full flex gap-3 items-start text-left px-2 py-2 rounded-lg hover:bg-[var(--bg-hover)] transition-colors">
                        <span className="w-9 h-9 shrink-0 rounded-md flex items-center justify-center" style={{ background: NOTIF_BG[a.type] || 'var(--bg-hover)', color: NOTIF_FG[a.type] || 'var(--text-secondary)' }}>
                          <Ico size={18} />
                        </span>
                        <div className="min-w-0">
                          <div className="text-[13.5px] text-ink leading-snug truncate">{a.title}</div>
                          <div className="text-[12px] text-muted mt-0.5 truncate">{a.detail}</div>
                        </div>
                      </button>
                    </li>
                  );
                })}
              </ul>
            )}
          </Card>

          <Card title="Cassa" action={
            cassaAperta
              ? <Pill tone="pos">Aperta · fondo {fmtEur(session.fondo)}</Pill>
              : <Pill tone="warn">Cassa chiusa</Pill>
          }>
            <dl className="space-y-3 text-[13.5px]">
              <div className="flex justify-between"><dt className="text-muted">Fondo cassa</dt><dd className="num text-ink">{cassaAperta ? fmtEur(session.fondo) : '—'}</dd></div>
              <div className="flex justify-between"><dt className="text-muted">Contanti incassati</dt><dd className="num text-ink">{fmtEur(TODAY.cashBreakdown.contanti)}</dd></div>
              <div className="flex justify-between"><dt className="text-muted">Carta</dt><dd className="num text-ink">{fmtEur(TODAY.cashBreakdown.carta)}</dd></div>
              <div className="flex justify-between"><dt className="text-muted">Bonifico</dt><dd className="num text-ink">{fmtEur(TODAY.cashBreakdown.bonifico)}</dd></div>
              <div className="border-t border-line my-2"></div>
              <div className="flex justify-between text-[15px]">
                <dt className="font-medium text-ink">Totale in cassa</dt>
                <dd className="num font-semibold text-ink">
                  {cassaAperta
                    ? fmtEur(session.fondo + TODAY.cashBreakdown.contanti + TODAY.cashBreakdown.carta + TODAY.cashBreakdown.bonifico + (TODAY.cashBreakdown.buoni || 0))
                    : '—'}
                </dd>
              </div>
            </dl>
            <div className="mt-4 grid grid-cols-2 gap-2">
              <Btn variant="outline" size="md" onClick={() => onShortcut('apertura')} leading={<I.Cash size={16}/>}>Apertura</Btn>
              <Btn variant="outline" size="md" onClick={() => onShortcut('eod')} leading={<I.EOD size={16}/>}>Chiusura</Btn>
            </div>
          </Card>
        </div>

        {/* Recent receipts */}
        <Card title="Ultimi scontrini" padded={false}
          action={<Btn variant="ghost" size="sm" trailing={<I.ArrowR size={14}/>} onClick={() => onShortcut('documenti')}>Tutti i documenti</Btn>}>
          <table className="w-full text-[13.5px]">
            <thead>
              <tr className="text-left text-muted uppercase text-[11px] tracking-[0.08em] hairline">
                <th className="px-5 py-3 font-medium">N°</th>
                <th className="px-5 py-3 font-medium">Ora</th>
                <th className="px-5 py-3 font-medium">Cliente</th>
                <th className="px-5 py-3 font-medium">Pezzi</th>
                <th className="px-5 py-3 font-medium">Pagamento</th>
                <th className="px-5 py-3 font-medium">Cassiere</th>
                <th className="px-5 py-3 font-medium text-right">Totale</th>
                <th className="px-2"></th>
              </tr>
            </thead>
            <tbody>
              {recentReceipts.map((r, i) => (
                <tr key={r.id} onClick={() => onShortcut('documenti')} className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                  <td className="px-5 py-3.5 num text-ink font-medium">{r.id}</td>
                  <td className="px-5 py-3.5 num text-ink">{r.time}</td>
                  <td className="px-5 py-3.5 text-ink">
                    {r.customer}
                    {r.taxfree && <Pill tone="info" className="ml-2"><I.Globe size={11}/> Tax-free</Pill>}
                  </td>
                  <td className="px-5 py-3.5 num text-ink">{r.items}</td>
                  <td className="px-5 py-3.5 text-ink">
                    <span className="inline-flex items-center gap-1.5">
                      {r.payment === 'Carta'   && <I.Card size={14} className="text-muted"/>}
                      {r.payment === 'Contanti' && <I.Wallet size={14} className="text-muted"/>}
                      {r.payment === 'Bonifico' && <I.Doc size={14} className="text-muted"/>}
                      {r.payment}
                    </span>
                  </td>
                  <td className="px-5 py-3.5">
                    <span className="inline-flex items-center gap-2">
                      <span className="w-6 h-6 rounded-full bg-line2 text-ink text-[10px] font-semibold flex items-center justify-center">{r.operator}</span>
                    </span>
                  </td>
                  <td className="px-5 py-3.5 num text-ink text-right font-medium">{fmtEur(r.total)}</td>
                  <td className="px-2 py-3.5 text-muted">
                    <button onClick={(e) => { e.stopPropagation(); if (window.__toast) window.__toast('Apertura stampa scontrino…', 'info'); if (window.__print) window.__print(); }} className="w-8 h-8 rounded hover:bg-[var(--bg-hover)] flex items-center justify-center"><I.Dots size={16}/></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    </>
  );
};

Object.assign(window, { Dashboard });
