// ── AccuracyView ─────────────────────────────────────────────────────────────
// Accuratezza delle previsioni (misurata su outcome già verificati vs prezzo
// reale) + pannello salute dati. Cuore della validazione: niente è "affidabile"
// finché non è misurato.

// Legenda numero tool → nome (Tool2 rimosso: i suoi output li produce Tool3).
const TOOL_LEGEND = [
  { n: "Tool0",  name: "Rischio",     desc: "regime di rischio di mercato (allerta crolli)" },
  { n: "Tool1",  name: "Collector",   desc: "scarica i prezzi (OHLCV)" },
  { n: "Tool3",  name: "Tecnico",     desc: "analisi tecnica → segnale, forecast, target/stop" },
  { n: "Tool4",  name: "News",        desc: "news + sentiment → segnale combinato" },
  { n: "Tool5",  name: "Calendario",  desc: "eventi finanziari / earnings" },
  { n: "Tool6",  name: "Telegram",    desc: "notifiche" },
  { n: "Tool7",  name: "Settori",     desc: "rotazione settoriale (11 settori SPDR)" },
  { n: "Tool8",  name: "Pre-market",  desc: "gap / momentum pre-apertura" },
  { n: "Tool9",  name: "Top Picks",   desc: "scoperta titoli promettenti" },
  { n: "Tool10", name: "Chain",       desc: "catene lead-lag (A sale → B segue)" },
  { n: "Tool11", name: "Simulatore",  desc: "paper-trading + Portfolio Manager AI" },
];

function AccuracyView() {
  const [acc, setAcc]       = useState(null);
  const [health, setHealth] = useState(null);
  const [sim, setSim]       = useState(null);
  const [pm, setPm]         = useState(null);
  const [sc, setSc]         = useState(null);   // pagella (admin-only; 401 → null)
  const [loading, setLoading] = useState(true);
  const [error, setError]   = useState(null);
  const [help, setHelp]     = useState(false);
  const [win, setWin]       = useState(30);   // finestra previsioni in giorni (0 = tutto)

  const load = async (spin) => {
    if (spin) setLoading(true);
    try {
      const [a, h, s, p, scd] = await Promise.all([
        fetch("/api/accuracy?days=" + (win || 0)).then(r => r.json()),
        fetch("/api/health").then(r => r.json()),
        fetch("/api/simulator").then(r => r.json()).catch(() => null),
        fetch("/api/pm").then(r => r.json()).catch(() => null),
        fetch("/api/scorecard?days=" + (win || 0)).then(r => r.json()).catch(() => null),
      ]);
      setAcc(a || {}); setHealth(h.health || []); setSim(s); setPm(p);
      setSc(scd && scd.tools ? scd : null);
      setError(a?.error || h?.error || null);
    } catch (e) { setError(String(e)); }
    finally { if (spin) setLoading(false); }
  };

  useEffect(() => {
    load(true);
    const t = setInterval(() => load(false), 5 * 60 * 1000);
    return () => clearInterval(t);
  }, [win]);

  const HORIZONS = ["1h", "3h", "6h", "24h"];
  const num = (v, d = 2) => (v == null ? "—" : (v >= 0 && d ? "" : "") + v.toFixed(d));
  const dirColor = (v) => v == null ? "var(--text-muted)" : v >= 55 ? "var(--green)" : v >= 50 ? "var(--amber)" : "var(--red)";
  const biasColor = (v) => v == null ? "var(--text-muted)" : Math.abs(v) <= 0.3 ? "var(--green)" : Math.abs(v) <= 0.8 ? "var(--amber)" : "var(--red)";

  const totalN = (stats) => HORIZONS.reduce((s, h) => s + ((stats?.[h]?.n) || 0), 0);

  const ForecastCard = ({ title, color, stats }) => {
    const n = totalN(stats);
    return (
      <div className="card" style={{ flex: "1 1 340px", minWidth: 300 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <span style={{ width: 10, height: 10, borderRadius: 3, background: color }}/>
          <strong style={{ fontSize: 14 }}>{title}</strong>
          <span className="mono" style={{ marginLeft: "auto", color: "var(--text-muted)", fontSize: 12 }}>
            {n} outcome
          </span>
        </div>
        {n === 0 ? (
          <div style={{ color: "var(--text-muted)", fontSize: 12.5, padding: "8px 0" }}>
            Nessun outcome ancora. Maturano ~25h dopo ogni previsione (poi compaiono qui).
          </div>
        ) : (
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
            <thead>
              <tr style={{ color: "var(--text-muted)", textAlign: "right" }}>
                <th style={{ textAlign: "left", fontWeight: 600, padding: "3px 0" }}>Oriz.</th>
                <th style={{ fontWeight: 600 }}>n</th>
                <th style={{ fontWeight: 600 }} title="% di volte che la direzione (su/giù) è corretta">Dir.Acc</th>
                <th style={{ fontWeight: 600 }} title="Mean Bias Error: previsto − reale (segno = bias sistematico)">MBE</th>
                <th style={{ fontWeight: 600 }} title="Mean Absolute Error">MAE</th>
                <th style={{ fontWeight: 600 }} title="Root Mean Squared Error">RMSE</th>
              </tr>
            </thead>
            <tbody>
              {HORIZONS.map(h => {
                const s = stats?.[h] || {};
                return (
                  <tr key={h} style={{ borderTop: "1px solid var(--border-soft, #2222)", textAlign: "right" }}>
                    <td style={{ textAlign: "left", padding: "4px 0", fontWeight: 600 }}>{h}</td>
                    <td className="mono" style={{ color: "var(--text-muted)" }}>{s.n || 0}</td>
                    <td className="mono" style={{ color: dirColor(s.dir_acc), fontWeight: 700 }}>{s.dir_acc == null ? "—" : s.dir_acc + "%"}</td>
                    <td className="mono" style={{ color: biasColor(s.mbe) }}>{s.mbe == null ? "—" : (s.mbe >= 0 ? "+" : "") + s.mbe}</td>
                    <td className="mono" style={{ color: "var(--text-muted)" }}>{num(s.mae)}</td>
                    <td className="mono" style={{ color: "var(--text-muted)" }}>{num(s.rmse)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    );
  };

  const MiniStat = ({ title, children, hint }) => (
    <div className="card" style={{ flex: "1 1 200px", minWidth: 180 }}>
      <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--text-muted)", marginBottom: 6 }} title={hint}>{title}</div>
      {children}
    </div>
  );

  const t9 = acc?.tool9 || {};
  const t8 = acc?.tool8 || {};
  const t10 = acc?.tool10 || {};
  const signed = (v, suf = "%") => v == null ? "—" : `${v >= 0 ? "+" : ""}${v}${suf}`;
  const greenRed = (v) => v == null ? "var(--text-muted)" : v >= 0 ? "var(--green)" : "var(--red)";

  return (
    <div style={{ padding: 16, overflowY: "auto", height: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
        <h3 style={{ margin: 0, fontSize: 15 }}>Accuratezza previsioni</h3>
        <button className="icon-btn" onClick={() => setHelp(h => !h)} title="Legenda: numero tool → nome"
                style={help ? { color: "var(--accent)" } : {}}>
          <Icon name="info" size={16} />
        </button>
        <button className="btn btn-sm" style={{ marginLeft: "auto" }} onClick={() => load(true)} title="Ricarica">
          <Icon name="refresh" size={13}/> Aggiorna
        </button>
      </div>
      <div style={{ color: "var(--text-muted)", fontSize: 12.5, marginBottom: 10 }}>
        Misurata su previsioni <b>già verificate</b> vs prezzo reale. Direction-accuracy &gt; 55% = segnale; MBE ≈ bias sistematico.
      </div>

      {/* Finestra temporale: di default RECENTE (non a vita) così riflette lo stato
          attuale dei modelli dopo i miglioramenti settimanali. */}
      <div style={{ display: "flex", gap: 6, alignItems: "center", marginBottom: 14, flexWrap: "wrap" }}>
        <span style={{ fontSize: 11.5, color: "var(--text-muted)" }}>Finestra previsioni (Tool3/4):</span>
        {[{ v: 7, l: "7 giorni" }, { v: 30, l: "30 giorni" }, { v: 0, l: "Tutto" }].map(o => (
          <button key={o.v} className="btn btn-sm" onClick={() => setWin(o.v)}
                  style={win === o.v ? { borderColor: "var(--accent)", color: "var(--accent)" } : {}}>{o.l}</button>
        ))}
        <span style={{ fontSize: 11, color: "var(--text-faint)" }}>
          {win ? `· solo le previsioni degli ultimi ${win} giorni` : "· media di sempre (diluisce i miglioramenti)"}
        </span>
      </div>

      {help && (
        <div className="card" style={{ marginBottom: 14, fontSize: 12.5 }}>
          <div style={{ display: "flex", alignItems: "center", marginBottom: 8 }}>
            <strong style={{ fontSize: 13.5 }}>Legenda tool — numero → nome</strong>
            <button className="btn btn-sm" style={{ marginLeft: "auto" }} onClick={() => setHelp(false)}>Chiudi</button>
          </div>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <tbody>
              {TOOL_LEGEND.map(t => (
                <tr key={t.n} style={{ borderTop: "1px solid var(--border-soft, #2222)" }}>
                  <td className="mono" style={{ padding: "5px 12px 5px 0", fontWeight: 700, whiteSpace: "nowrap", color: "var(--accent)" }}>{t.n}</td>
                  <td style={{ padding: "5px 14px 5px 0", fontWeight: 600, whiteSpace: "nowrap" }}>{t.name}</td>
                  <td style={{ padding: "5px 0", color: "var(--text-muted)" }}>{t.desc}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 8 }}>
            Tool2 è stato rimosso: i suoi output (target/stop/probabilità) ora li produce il <b>Tool3</b>.
          </div>
        </div>
      )}

      {loading && !acc && <div style={{ color: "var(--text-muted)" }}>Caricamento…</div>}
      {error && <div style={{ color: "var(--red)", marginBottom: 12 }}>Errore: {error}</div>}

      {acc && <>
        {/* Pagella tool — costo vs valore vs soldi (admin-only) */}
        {sc && sc.tools && sc.tools.length > 0 && (() => {
          const VLABEL = {
            earns_its_keep:   { t: "Si ripaga",            c: "var(--green)" },
            costs_no_value:   { t: "Costa, 0 valore",      c: "var(--red)" },
            unproven:         { t: "Da dimostrare",        c: "var(--amber)" },
            free_informative: { t: "Gratis · utile",       c: "#6ea8fe" },
            free_low_value:   { t: "Gratis · poco valore", c: "var(--text-muted)" },
          };
          return (
            <div className="card" style={{ marginBottom: 14 }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 4 }}>
                <strong style={{ fontSize: 14 }}>Pagella tool — costo vs valore vs soldi</strong>
                <span style={{ fontSize: 11, color: "var(--text-faint)" }}>“mi fa guadagnare?”</span>
              </div>
              <div style={{ fontSize: 11, color: "var(--text-faint)", marginBottom: 10 }}>
                Money = <b>proxy di triage</b> (long-only, una posizione per volta, niente concorrenza/slippage) → <b>sovrastima</b>: serve solo a capire quali tool meritano un backtest serio. Costo per trade ~{sc.assumptions?.cost_per_trade_pp}pp.
              </div>
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
                  <thead>
                    <tr style={{ color: "var(--text-muted)", textAlign: "right" }}>
                      <th style={{ textAlign: "left", padding: "3px 8px 3px 0" }}>Tool</th>
                      <th style={{ padding: "3px 8px" }}>€/mese</th>
                      <th style={{ padding: "3px 8px" }} title="Dir-acc 24h (Tool3/4/8/10) o alpha vs SPY (Tool9)">Valore</th>
                      <th style={{ padding: "3px 8px" }} title="Rendimento medio NETTO dei segnali long (proxy) e n. segnali">Money net% (n)</th>
                      <th style={{ textAlign: "right", padding: "3px 0 3px 8px" }}>Verdetto</th>
                    </tr>
                  </thead>
                  <tbody>
                    {sc.tools.map(t => {
                      const v = t.value || {}, m = t.money || {};
                      const val = v.dir_acc != null ? v.dir_acc + "%" : (v.alpha != null ? signed(v.alpha) : "—");
                      const valCol = v.dir_acc != null ? dirColor(v.dir_acc) : greenRed(v.alpha);
                      const vlab = VLABEL[t.verdict] || { t: t.verdict, c: "var(--text-muted)" };
                      return (
                        <tr key={t.tool} style={{ borderTop: "1px solid var(--border-soft, #2222)", textAlign: "right" }}>
                          <td style={{ textAlign: "left", padding: "5px 8px 5px 0", fontWeight: 600 }}>{t.label}</td>
                          <td className="mono" style={{ padding: "5px 8px", color: t.cost_month_eur > 0 ? "var(--text)" : "var(--text-faint)" }}>
                            {t.cost_month_eur > 0 ? "€" + t.cost_month_eur.toFixed(2) : "—"}
                          </td>
                          <td className="mono" style={{ padding: "5px 8px", color: valCol }}>{val}</td>
                          <td className="mono" style={{ padding: "5px 8px", color: greenRed(m.net_ret_pct) }}>
                            {m.net_ret_pct == null ? "—" : signed(m.net_ret_pct) + (m.n_signals ? ` (${m.n_signals})` : "")}
                          </td>
                          <td style={{ textAlign: "right", padding: "5px 0 5px 8px" }}>
                            <span style={{ fontSize: 11, fontWeight: 600, color: vlab.c, background: "var(--surface2)", padding: "2px 8px", borderRadius: 6, whiteSpace: "nowrap" }}>{vlab.t}</span>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          );
        })()}

        {/* Forecast Tool3 / Tool4 */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 14 }}>
          <ForecastCard title="Tool3 · Tecnico" color="#f59e0b" stats={acc.forecast?.tool3} />
          <ForecastCard title="Tool4 · News"    color="#a78bfa" stats={acc.forecast?.tool4} />
        </div>

        {/* Discovery / pre-market / chain */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 22 }}>
          <MiniStat title="Tool9 · Alpha vs SPY (~30gg)" hint="Extra-rendimento medio dei pick vs SPY">
            {t9.n_validated ? (
              <div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: greenRed(t9.avg_alpha) }}>{signed(t9.avg_alpha)}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{t9.n_validated} pick · hit {t9.hit_rate ?? "—"}%</div>
              </div>
            ) : <div style={{ color: "var(--text-muted)", fontSize: 12 }}>In maturazione (30gg)</div>}
          </MiniStat>
          <MiniStat title="Tool8 · Hit-rate gap" hint="% verdetti pre-market corretti">
            {t8.n ? (
              <div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: dirColor(t8.hit_rate) }}>{t8.hit_rate}%</div>
                <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{t8.n} verdetti</div>
              </div>
            ) : <div style={{ color: "var(--text-muted)", fontSize: 12 }}>Nessun dato</div>}
          </MiniStat>
          <MiniStat title="Tool10 · Edge stabili" hint="% relazioni lead-lag stabili nelle due metà storiche">
            {t10.n ? (
              <div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: dirColor(t10.pct_stable) }}>{t10.pct_stable}%</div>
                <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{t10.n} edge · score medio {t10.avg_edge ?? "—"}</div>
              </div>
            ) : <div style={{ color: "var(--text-muted)", fontSize: 12 }}>Nessun dato</div>}
          </MiniStat>
        </div>

        {/* Paper-trading — il "bottom line": quanto rendono davvero le decisioni */}
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, margin: "0 0 10px" }}>
          <h3 style={{ margin: 0, fontSize: 15 }}>Paper-trading (settimana)</h3>
          <span style={{ fontSize: 11, color: "var(--amber)" }}>denaro fittizio</span>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 22 }}>
          <MiniStat title="Tool11 · Strategia (Tool4)" hint="Rendimento settimana della strategia paper (segue i segnali Tool4) vs comprare-e-tenere">
            {sim?.active && sim?.summary ? (
              <div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: greenRed(sim.summary.return_pct) }}>{signed(sim.summary.return_pct)}</div>
                <div style={{ fontSize: 11.5, color: greenRed((sim.summary.return_pct || 0) - (sim.summary.bh_return_pct || 0)) }}>
                  Δ buy&amp;hold {signed((sim.summary.return_pct || 0) - (sim.summary.bh_return_pct || 0))}
                </div>
              </div>
            ) : <div style={{ color: "var(--text-muted)", fontSize: 12 }}>Non attivo</div>}
          </MiniStat>
          <MiniStat title="Tool11 · Portfolio Manager AI" hint="Rendimento settimana del trader AI (cassa unica $10k) vs comprare-e-tenere">
            {pm?.active && pm?.summary ? (
              <div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: greenRed(pm.summary.return_pct) }}>{signed(pm.summary.return_pct)}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>
                  Δ b&amp;h <span style={{ color: greenRed((pm.summary.return_pct || 0) - (pm.summary.bh_return_pct || 0)) }}>{signed((pm.summary.return_pct || 0) - (pm.summary.bh_return_pct || 0))}</span> · {pm.summary.n_pos || 0} pos
                </div>
              </div>
            ) : <div style={{ color: "var(--text-muted)", fontSize: 12 }}>Parte lunedì</div>}
          </MiniStat>
          <MiniStat title="PM AI · vs SPY" hint="Extra-rendimento del Portfolio Manager rispetto all'indice S&P 500">
            {pm?.active && pm?.summary ? (
              <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: greenRed((pm.summary.return_pct || 0) - (pm.summary.spy_return_pct || 0)) }}>
                {signed((pm.summary.return_pct || 0) - (pm.summary.spy_return_pct || 0))}
              </div>
            ) : <div style={{ color: "var(--text-muted)", fontSize: 12 }}>—</div>}
          </MiniStat>
        </div>

        {/* Salute dati */}
        <h3 style={{ margin: "0 0 10px", fontSize: 15 }}>Salute dati</h3>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          {(health || []).map(h => (
            <div key={h.key} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 14px", borderTop: "1px solid var(--border-soft, #2222)" }}>
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: h.ok ? "var(--green)" : (h.fresh ? "var(--amber)" : "var(--red)"), flexShrink: 0 }}/>
              <strong style={{ fontSize: 13, minWidth: 150 }}>{h.label}</strong>
              <span className="mono" style={{ fontSize: 12, color: "var(--text-muted)", minWidth: 110 }}>
                {h.age_min == null ? "nessun dato" : h.age_min < 90 ? `${h.age_min} min fa` : `${(h.age_min / 60).toFixed(1)}h fa`}
              </span>
              <span className="mono" style={{ fontSize: 12, color: "var(--text-muted)" }}>
                {h.rows_today == null ? "" : `${h.rows_today} righe oggi`}
              </span>
              <span style={{ marginLeft: "auto", display: "flex", gap: 6, flexWrap: "wrap", justifyContent: "flex-end" }}>
                {(h.anomalies || []).map((a, i) => (
                  <span key={i} style={{ fontSize: 11, color: "var(--red)", background: "var(--red-soft, rgba(248,81,73,0.12))", padding: "2px 7px", borderRadius: 6 }}>{a}</span>
                ))}
                {h.ok && <span style={{ fontSize: 11, color: "var(--green)" }}>ok</span>}
              </span>
            </div>
          ))}
        </div>
      </>}
    </div>
  );
}

window.AccuracyView = AccuracyView;
