// ============================================================
// Vendors.jsx
// ============================================================
// FASE 12 — riusa le card Workflow + SLA esposte da RdA.jsx (caricato prima).
const WorkflowInstancesCardCmp = window.WorkflowInstancesCard;
const SlaEventsCardCmp = window.SlaEventsCard;

function vendorStatusKind(status) {
  if (status === 'qualified') return 'ok';
  if (status === 'in_qualification') return 'info';
  if (status === 'disqualified') return 'err';
  return ''; // pending
}

// FASE A (realizzazione) — insight vendor REALE: prompt costruito dal profilo
// del fornitore selezionato, inviato a window.aiAsk → /api/ai/invoke.
const VENDOR_INSIGHT_SYSTEM = "Sei un analista vendor management di una piattaforma di governance degli investimenti industriali (CAPEX). Dato il profilo sintetico di un fornitore, fornisci una valutazione dell'affidabilità e una raccomandazione d'uso: per quali tipologie di commessa e lead time è adatto, ed eventuali cautele in base al rischio. Massimo 3 frasi, italiano professionale, nessun preambolo né titoli.";
function buildVendorInsightPrompt(v) {
  if (!v) return '';
  const riskLabel = v.risk === 'high' ? 'alto' : v.risk === 'medium' ? 'medio' : 'basso';
  return [
    `Profilo fornitore:`,
    `- Nome: ${v.name}`,
    `- Categoria merceologica: ${v.category || 'n/d'}`,
    `- Paese: ${v.country || 'n/d'}`,
    `- Rating qualifica: ${(v.rating ?? 0).toFixed(1)}/5`,
    `- Puntualità consegne (on-time): ${v.onTime ?? 0}%`,
    `- Progetti CAPEX svolti: ${v.projects ?? 0}`,
    `- Livello di rischio: ${riskLabel}`,
    v.status ? `- Stato qualifica: ${v.status}` : null,
    ``,
    `Fornisci la valutazione di affidabilità e la raccomandazione d'uso.`,
  ].filter((l) => l !== null).join('\n');
}

function Vendors() {
  const { seed, extras, user, seedCustom, routeParam } = useStore();
  // FASE 2 RBAC (sessione 102) — gating "+ Nuovo vendor".
  const canCreateVendor = window.can('vendor.create', user, seedCustom);
  const [sel, setSel] = React.useState(null);
  const [showNew, setShowNew] = React.useState(false);
  const [showOffers, setShowOffers] = React.useState(false);
  // Dedup extras + seed per evitare key duplicate (vendor in extras vince su seed).
  const allVendors = React.useMemo(() => {
    const ext = extras?.vendors || [];
    const seenIds = new Set();
    const out = [];
    for (const v of [...ext, ...seed.VENDORS]) {
      if (!v?.id || seenIds.has(v.id)) continue;
      seenIds.add(v.id);
      out.push(v);
    }
    return out;
  }, [extras, seed]);
  const pg = usePaginated(allVendors, 10);

  // Sessione 119 — routeParam auto-select: quando si naviga via
  // `navigate('vendors', <id>)` (es. da un'anomalia su un vendor nella pagina
  // Alert), apri direttamente il detail del vendor target invece della sola
  // lista. Human-on-the-loop: l'oggetto è selezionato, l'azione la sceglie
  // l'utente. Pattern coerente con RdA.jsx. Trigger solo on routeParam change.
  React.useEffect(() => {
    if (!routeParam) return;
    const target = allVendors.find((v) => v.id === routeParam);
    if (target) setSel(target);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [routeParam]);
  return (
    <div className="page fade-in">
      <div className="page-header">
        <div>
          <div className="eyebrow">Procurement</div>
          <h1 className="page-title">Vendor & fornitori</h1>
          <div className="page-sub">{seed.VENDORS.length} vendor qualificati · rating, on-time, rischio e storico progetti. L'agente aggiorna il profilo ad ogni nuova interazione documentale.</div>
        </div>
        <div className="actions"><Btn
          variant={canCreateVendor ? 'primary' : 'ghost'}
          size="sm"
          disabled={!canCreateVendor}
          onClick={() => { if (canCreateVendor) setShowNew(true); }}
          title={canCreateVendor ? undefined : window.whyDisabled('vendor.create')}
        ><Icon name="plus" size={12}/> Nuovo vendor</Btn></div>
      </div>

      <div className="grid grid-4" style={{marginBottom:14}}>
        <div className="card"><Stat label="Vendor attivi" value={seed.VENDORS.length} /></div>
        <div className="card"><Stat label="Rating medio" value={(seed.VENDORS.reduce((a,b)=>a+b.rating,0)/seed.VENDORS.length).toFixed(2)} delta="su 5" tone="up" /></div>
        <div className="card"><Stat label="On-time medio" value={Math.round(seed.VENDORS.reduce((a,b)=>a+b.onTime,0)/seed.VENDORS.length)+'%'} tone="up" /></div>
        <div className="card"><Stat label="A rischio alto" value={seed.VENDORS.filter(v=>v.risk==='high').length} tone="down" /></div>
      </div>

      <div className="grid" style={{gridTemplateColumns: sel ? '1fr 420px' : '1fr', gap: 14}}>
        <div className="card">
          <table className="tbl">
            <thead><tr><th>Vendor</th><th>Categoria</th><th>Paese</th><th className="num">Rating</th><th className="num">On-time</th><th className="num">Progetti</th><th>Rischio</th><th>Stato</th></tr></thead>
            <tbody>
              {pg.slice.map(v => (
                <tr key={v.id} className="clickable" onClick={()=>setSel(v)}>
                  <td style={{fontWeight:500}}>{v.name}</td>
                  <td style={{color:'var(--text-2)', fontSize:11.5}}>{v.category}</td>
                  <td style={{color:'var(--text-2)', fontSize:11.5}}>{v.country}</td>
                  <td className="num">{v.rating.toFixed(1)}</td>
                  <td className="num">{v.onTime}%</td>
                  <td className="num">{v.projects}</td>
                  <td><Chip kind={v.risk==='high'?'err':v.risk==='medium'?'warn':'ok'} dot>{v.risk}</Chip></td>
                  <td>{v.status ? <Chip kind={vendorStatusKind(v.status)} dot>{v.status}</Chip> : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <Pagination {...pg} />
        </div>
        {sel && (
          <div className="card">
            <div className="card-header">
              <div className="title">{sel.name}</div>
              <div className="actions"><button className="btn ghost icon" onClick={()=>setSel(null)}><Icon name="x"/></button></div>
            </div>
            <div className="card-body">
              <div className="row" style={{gap:8, alignItems:'center', marginBottom:6}}>
                <div className="mono" style={{fontSize:11, color:'var(--text-3)'}}>{sel.category} · {sel.country}</div>
                <span className="spacer"/>
                {sel.status && <Chip kind={vendorStatusKind(sel.status)} dot>{sel.status}</Chip>}
              </div>
              <div className="grid grid-2" style={{marginTop:12, gap:10}}>
                <Stat label="Rating" value={sel.rating.toFixed(1)+'/5'} />
                <Stat label="On-time" value={sel.onTime+'%'} />
                <Stat label="Progetti" value={sel.projects} />
                <Stat label="Rischio" value={sel.risk} />
              </div>

              {/* FASE 12 — Workflow qualifica vendor + Eventi SLA & Notifiche */}
              {WorkflowInstancesCardCmp && (
                <div style={{marginTop:14}}>
                  <WorkflowInstancesCardCmp entityType="vendor" entityId={sel.id}/>
                </div>
              )}
              {SlaEventsCardCmp && (
                <div style={{marginTop:12}}>
                  <SlaEventsCardCmp entityType="vendor" entityId={sel.id}/>
                </div>
              )}

              <div className="sep"/>
              <div className="eyebrow"><Icon name="sparkle" size={11}/> Insight AI</div>
              <AiInsightPanel
                system={VENDOR_INSIGHT_SYSTEM}
                prompt={buildVendorInsightPrompt(sel)}
                autoRun
                runKey={sel.id}
                compact
              />
              <div className="row" style={{gap:6, marginTop:12}}>
                <Btn variant="primary" size="sm"><Icon name="mail" size={12}/> Contatta</Btn>
                <Btn variant="ai" size="sm" onClick={()=>setShowOffers(true)}><Icon name="sparkle" size={12}/> Confronta offerte</Btn>
              </div>
            </div>
          </div>
        )}
      </div>
      <NewVendorModal open={showNew} onClose={() => setShowNew(false)} />
      {showOffers && sel && <VendorOffersModal vendor={sel} benchmarks={seed.BENCHMARKS || []} user={user} onClose={() => setShowOffers(false)} />}
    </div>
  );
}

// FASE D2 — "Confronta offerte": vista REALE delle offerte del vendor (da
// /api/vendor-offers?vendor=<name>) con delta vs mediana benchmark + insight AI
// sulla competitività (riusa AiInsightPanel).
function VendorOffersModal({ vendor, benchmarks, user, onClose }) {
  const [offers, setOffers] = React.useState(null); // null = loading
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    let alive = true;
    setOffers(null); setErr(null);
    fetch(`/api/vendor-offers?vendor=${encodeURIComponent(vendor.name)}&limit=100`, {
      headers: { 'X-Actor-Persona-Id': user?.id || '' }, cache: 'no-store',
    })
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status))))
      .then((j) => { if (alive) setOffers(j.data || []); })
      .catch((e) => { if (alive) setErr(String(e?.message || e)); });
    return () => { alive = false; };
  }, [vendor.name, user?.id]);

  const medianByCat = React.useMemo(() => {
    const m = {};
    (benchmarks || []).forEach((b) => { m[b.category] = b.historicalMedian; });
    return m;
  }, [benchmarks]);

  const withDelta = React.useMemo(() => (offers || []).map((o) => {
    const med = medianByCat[o.category];
    const delta = med ? ((o.amountEur - med) / med) * 100 : null;
    return { ...o, _median: med ?? null, _delta: delta };
  }), [offers, medianByCat]);

  const aiPrompt = React.useMemo(() => {
    if (!withDelta.length) return '';
    const rows = withDelta.map((o) =>
      `- ${o.category}: ${Math.round(o.amountEur)} € (${o.offerDate})${o._median ? `, mediana ${Math.round(o._median)} €, scarto ${o._delta.toFixed(1)}%` : ', nessuna mediana di riferimento'}`
    ).join('\n');
    return `Offerte del fornitore "${vendor.name}" (rating ${(vendor.rating ?? 0).toFixed(1)}/5, on-time ${vendor.onTime ?? 0}%):\n${rows}\n\nValuta la competitività complessiva delle offerte rispetto alla mediana di mercato e indica su quali categorie negoziare.`;
  }, [withDelta, vendor]);

  return (
    <Modal open onClose={onClose} title={`Offerte · ${vendor.name}`} size="lg" footer={<Btn variant="ghost" size="sm" onClick={onClose}>Chiudi</Btn>}>
      {!offers && !err && <div style={{ padding: 14, textAlign: 'center', color: 'var(--text-3)', fontSize: 12 }}>Caricamento offerte…</div>}
      {err && <div style={{ padding: 14, color: 'var(--err)', fontSize: 12 }}>Errore: {err}</div>}
      {offers && offers.length === 0 && (
        <div style={{ padding: 14, color: 'var(--text-3)', fontSize: 12 }}>
          Nessuna offerta registrata in DB per <strong>{vendor.name}</strong>. Le offerte si aggiungono dalla pagina Benchmark ("Aggiungi offerta").
        </div>
      )}
      {offers && offers.length > 0 && (
        <div className="col" style={{ gap: 14 }}>
          <table className="tbl">
            <thead><tr><th>Categoria</th><th>Data</th><th className="num">Importo</th><th className="num">Mediana mercato</th><th>Scostamento</th></tr></thead>
            <tbody>
              {withDelta.map((o) => {
                const high = o._delta != null && o._delta > 5;
                const low = o._delta != null && o._delta < -5;
                return (
                  <tr key={o.id}>
                    <td style={{ fontWeight: 500 }}>{o.category}</td>
                    <td className="mono" style={{ fontSize: 11 }}>{o.offerDate}</td>
                    <td className="num">{fmtEUR(o.amountEur, true)}</td>
                    <td className="num" style={{ color: 'var(--text-2)' }}>{o._median ? fmtEUR(Math.round(o._median), true) : '—'}</td>
                    <td>{o._delta == null ? '—' : <Chip kind={high ? 'err' : low ? 'ok' : 'warn'} dot>{fmtPct(o._delta, 1)}</Chip>}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div>
            <div className="eyebrow" style={{ marginBottom: 6 }}><Icon name="sparkle" size={11} /> Valutazione competitività</div>
            <AiInsightPanel
              system="Sei un analista procurement CAPEX. Dato l'elenco delle offerte di un fornitore con lo scostamento rispetto alla mediana di mercato, valuta la competitività. Se ci sono almeno 2 categorie inizia con una tabella markdown compatta (Categoria | Offerta | Mediana | Scarto%, colonne numeriche allineate a destra con ---:). Poi massimo 3 frasi: competitività complessiva e su quali categorie conviene negoziare. Italiano professionale, nessun preambolo, solo dati forniti."
              prompt={aiPrompt}
              idleLabel="Valuta con AI"
              compact
            />
          </div>
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { Vendors });
