// ── SimulatorView (Tool11 — paper-trading settimanale) ───────────────────────
// Denaro FITTIZIO. Ogni lunedì riparte: €500/ticker, trading attivo Lun→Ven seguendo
// Tool4 (primario). Forward-test, NON consulenza. Confronto vs buy-and-hold e SPY.

function SimNavChart({ nav }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current || !window.LightweightCharts || !nav || nav.length < 1) return;
    const el = ref.current;
    let chart;
    try {
      chart = LightweightCharts.createChart(el, {
        width: Math.max(100, el.clientWidth), height: Math.max(100, el.clientHeight),
        layout: { background: { color: "transparent" }, textColor: "#8892a4", fontFamily: "JetBrains Mono, monospace", fontSize: 11 },
        grid: { vertLines: { color: "rgba(255,255,255,0.035)" }, horzLines: { color: "rgba(255,255,255,0.05)" } },
        rightPriceScale: { borderVisible: false, scaleMargins: { top: 0.2, bottom: 0.12 } },
        timeScale: { borderVisible: false, timeVisible: true, secondsVisible: false },
        crosshair: {
          mode: LightweightCharts.CrosshairMode.Magnet,
          vertLine: { color: "#3a4252", width: 1, labelBackgroundColor: "#1c2230" },
          horzLine: { color: "#3a4252", width: 1, labelBackgroundColor: "#1c2230" },
        },
        localization: { priceFormatter: (p) => "€" + Math.round(p) },
      });
    } catch (e) { console.warn("sim chart init", e); return; }

    const toPts = (key) => {
      const seen = new Set();
      const out = [];
      for (const p of nav) {
        if (!p.timestamp || p[key] == null) continue;
        // Il backend invia GIÀ l'ora italiana (Europe/Rome). La tratto come fissa:
        // append "Z" → l'epoch è quel wall-clock interpretato come UTC, e
        // LightweightCharts (che rende in UTC) mostra esattamente l'ora di Roma.
        // Indipendente dal fuso del browser. Vedi CONVENZIONE FUSO ORARIO in CLAUDE.md.
        const t = Math.floor(new Date(p.timestamp + "Z").getTime() / 1000);
        if (!t || isNaN(t) || seen.has(t)) continue;
        seen.add(t); out.push({ time: t, value: p[key] });
      }
      return out;
    };
    // Strategia come AREA con riempimento sfumato → molto più leggibile di una linea sottile.
    const sBh = chart.addLineSeries({ color: "#8892a4", lineWidth: 1, lineStyle: LightweightCharts.LineStyle.Dashed, priceLineVisible: false, lastValueVisible: true, title: "Buy&Hold" });
    const sSpy = chart.addLineSeries({ color: "#6ea8fe", lineWidth: 1, lineStyle: LightweightCharts.LineStyle.Dotted, priceLineVisible: false, lastValueVisible: true, title: "SPY" });
    const sStrat = chart.addAreaSeries({
      lineColor: "#22c55e", lineWidth: 2,
      topColor: "rgba(34,197,94,0.30)", bottomColor: "rgba(34,197,94,0.01)",
      priceLineVisible: false, lastValueVisible: true, title: "Strategia",
      crosshairMarkerRadius: 3,
    });
    sBh.setData(toPts("bh_nav")); sSpy.setData(toPts("spy_nav")); sStrat.setData(toPts("nav"));
    chart.timeScale().fitContent();

    const ro = new ResizeObserver(() => chart.applyOptions({ width: el.clientWidth, height: el.clientHeight }));
    ro.observe(el);
    return () => { ro.disconnect(); chart.remove(); };
  }, [nav]);
  return <div ref={ref} style={{ position: "absolute", inset: 0 }} />;
}

// Donut SVG (no librerie). slices: [{label, value>=0, color, display}].
function SimDonut({ slices, size = 158, thickness = 30, center, centerSub, centerColor }) {
  const pos = (slices || []).filter(s => s.value > 0);
  const total = pos.reduce((a, s) => a + s.value, 0);
  const r = size / 2, ir = r - thickness;
  const cx = (txt, color, dy, fs, fw) => txt ? (
    <text x={r} y={r + dy} textAnchor="middle" fill={color}
          style={{ fontSize: fs, fontWeight: fw, fontFamily: "JetBrains Mono, monospace" }}>{txt}</text>
  ) : null;
  if (total <= 0) {
    // Nessuna fetta (tutto a 0): mostra comunque un anello grigio col valore al
    // centro — coerente con l'altra torta, invece del solo trattino.
    return (
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: "block", flexShrink: 0 }}>
        <circle cx={r} cy={r} r={(r + ir) / 2} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth={thickness} />
        {cx(center, "var(--text-muted)", -1, 15, 700)}
        {cx(centerSub, "var(--text-faint)", 15, 10, 400)}
      </svg>
    );
  }
  let body;
  if (pos.length === 1) {
    body = <circle cx={r} cy={r} r={(r + ir) / 2} fill="none" stroke={pos[0].color} strokeWidth={thickness} />;
  } else {
    let acc = 0;
    body = pos.map((s, i) => {
      const f = s.value / total;
      const a0 = acc * 2 * Math.PI - Math.PI / 2; acc += f;
      const a1 = acc * 2 * Math.PI - Math.PI / 2;
      const large = f > 0.5 ? 1 : 0;
      const x0 = r + r * Math.cos(a0), y0 = r + r * Math.sin(a0);
      const x1 = r + r * Math.cos(a1), y1 = r + r * Math.sin(a1);
      const xi1 = r + ir * Math.cos(a1), yi1 = r + ir * Math.sin(a1);
      const xi0 = r + ir * Math.cos(a0), yi0 = r + ir * Math.sin(a0);
      const d = `M ${x0} ${y0} A ${r} ${r} 0 ${large} 1 ${x1} ${y1} L ${xi1} ${yi1} A ${ir} ${ir} 0 ${large} 0 ${xi0} ${yi0} Z`;
      return <path key={i} d={d} fill={s.color} stroke="#0d1117" strokeWidth="2.5"><title>{s.label}: {s.display}</title></path>;
    });
  }
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: "block", flexShrink: 0 }}>
      {body}
      {cx(center, centerColor || "var(--text)", -1, 15, 700)}
      {cx(centerSub, "var(--text-muted)", 15, 10, 400)}
    </svg>
  );
}

function SimLegend({ items }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4, fontSize: 12, flex: 1, minWidth: 0 }}>
      {(items || []).filter(x => x.value > 0).map((x, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 9, height: 9, borderRadius: 2, background: x.color, flexShrink: 0 }}></span>
          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{x.label}</span>
          <span className="mono" style={{ marginLeft: "auto", color: "var(--text-muted)" }}>{x.display}</span>
        </div>
      ))}
    </div>
  );
}

// Grafico a barre: per ogni ticker investito (blu) e guadagno (verde su, rosso giù).
// STESSA scala per entrambi (magnitudini corrette): l'investito è grande, il guadagno
// Due barre per ticker su SCALE DIVERSE (investito su €budget, guadagno su max|guadagno|)
// così il guadagno — piccolo in assoluto — resta visibile. Entrambe vanno verso l'ALTO;
// il guadagno è verde, la perdita rossa (il segno è dato dal colore e dall'etichetta).
// Larghezza piena: misura il contenitore e distribuisce le colonne su tutta la larghezza.
function SimBars({ positions, budget }) {
  const ref = useRef(null);
  const [w, setW] = useState(700);
  useEffect(() => {
    if (!ref.current) return;
    const upd = () => { if (ref.current) setW(ref.current.clientWidth || 700); };
    upd();
    const ro = new ResizeObserver(upd);
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);
  if (!positions || !positions.length) return <div ref={ref} />;
  const data = positions.map(p => ({ sym: p.symbol, inv: Math.max(0, p.invested || 0),
    gain: (p.value || 0) - (p.cost_basis != null ? p.cost_basis : budget) }));
  const maxInv = Math.max(1, budget, ...data.map(d => d.inv));
  const maxGain = Math.max(0.01, ...data.map(d => Math.abs(d.gain)));
  const H = 160, top = 18, base = top + H, n = data.length;
  const colW = w / n;                         // colonne distribuite su TUTTA la larghezza
  const barW = Math.max(8, Math.min(22, colW * 0.26)), gap = Math.max(4, colW * 0.06);
  return (
    <div ref={ref} style={{ width: "100%" }}>
      <svg width={w} height={base + 40} style={{ display: "block" }}>
        <line x1="0" y1={base} x2={w} y2={base} stroke="rgba(255,255,255,0.12)" strokeWidth="1" />
        {data.map((d, i) => {
          const cx = i * colW + colW / 2;
          const x1 = cx - barW - gap / 2, x2 = cx + gap / 2;
          const invH = (d.inv / maxInv) * H;
          const gH = (Math.abs(d.gain) / maxGain) * H;
          const up = d.gain >= 0;
          const gc = up ? "#3fb950" : "#f0556b";
          return (
            <g key={i}>
              <rect x={x1} y={base - invH} width={barW} height={Math.max(1, invH)} rx={2} fill="#5b8def">
                <title>{d.sym} · investito €{d.inv.toFixed(0)}</title>
              </rect>
              <rect x={x2} y={base - gH} width={barW} height={Math.max(1, gH)} rx={2} fill={gc}>
                <title>{d.sym} · {up ? "+" : ""}€{d.gain.toFixed(1)}</title>
              </rect>
              <text x={x1 + barW / 2} y={base - invH - 4} textAnchor="middle" fontSize="10" fill="#8892a4">{d.inv.toFixed(0)}</text>
              <text x={x2 + barW / 2} y={base - gH - 4} textAnchor="middle" fontSize="10" fill={gc}>{up ? "+" : ""}{d.gain.toFixed(1)}</text>
              <text x={cx} y={base + 20} textAnchor="middle" fontSize="11" fill="#c9d1d9" fontWeight="600">{d.sym}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

// Formatta il timestamp dell'ultima valutazione. `iso` è GIÀ ora italiana (Europe/Rome,
// convertita dal backend) → uso i componenti senza riconversione del fuso del browser.
function _simFmtEval(iso) {
  if (!iso) return "—";
  const m = String(iso).match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);
  if (!m) return String(iso);
  const [, y, mo, d, hh, mm] = m;
  const now = new Date();
  const today = now.getFullYear() === +y && (now.getMonth() + 1) === +mo && now.getDate() === +d;
  return today ? `oggi alle ${hh}:${mm}` : `${d}/${mo} alle ${hh}:${mm}`;
}

// Scheda Portfolio Manager LLM (sleeve separata) — stesso stile ricco del simulatore
function PMPanel({ onBack }) {
  const [d, setD] = useState(null);
  const [err, setErr] = useState(null);
  const [isMobile, setIsMobile] = useState(typeof window !== "undefined" && window.innerWidth < 760);
  useEffect(() => {
    const onR = () => setIsMobile(window.innerWidth < 760);
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
  }, []);
  const load = () => fetch("/api/pm").then(r => r.json()).then(j => { setD(j); setErr(j?.error || null); }).catch(e => setErr(String(e)));
  useEffect(() => { load(); const t = setInterval(load, 60 * 1000); return () => clearInterval(t); }, []);
  const pct = (v) => v == null ? "—" : `${v >= 0 ? "+" : ""}${v.toFixed(2)}%`;
  const pc = (v) => v == null ? "var(--text-muted)" : v >= 0 ? "var(--green)" : "var(--red)";
  const PALETTE = ["#6ea8fe", "#56cfe1", "#9d8df1", "#5fd0ac", "#7aa2f7", "#c08cf0", "#74c0fc", "#80b8a0", "#a3b1cf", "#88d3c0"];

  const s = d?.summary || {};
  const cash = d?.cash || 0;
  const dec = d?.decisions || [];
  const wl = d?.watchlist || [];
  const rawPos = d?.positions || [];
  // Universo = watchlist seguita (così torte/barre mostrano ANCHE le aziende a zero);
  // fallback alle sole posizioni se la watchlist non è disponibile.
  const universe = wl.length ? wl.map(w => w.symbol) : rawPos.map(p => p.symbol);
  const colorOf = {}; universe.forEach((sym, i) => { colorOf[sym] = PALETTE[i % PALETTE.length]; });
  const posBySym = {}; rawPos.forEach(p => { posBySym[p.symbol] = { ...p, _cost: (p.shares || 0) * (p.avg_cost || 0) }; });
  const positions = universe.map(sym => posBySym[sym]).filter(Boolean);   // solo quelle in posizione (tabella)
  const heldSet = new Set(rawPos.map(p => p.symbol));

  const allocSlices = universe.map(sym => {
    const v = posBySym[sym] ? (posBySym[sym].value || 0) : 0;
    return { label: sym, value: Math.max(0, v), color: colorOf[sym], display: "$" + v.toFixed(0) };
  });
  if (cash > 0) allocSlices.push({ label: "Cash", value: cash, color: "#2d3340", display: "$" + cash.toFixed(0) });
  const gainSlices = universe.map(sym => {
    const p = posBySym[sym];
    const g = p ? ((p.value || 0) - p._cost) : 0;
    return { label: sym, value: Math.abs(g), color: colorOf[sym], display: (g >= 0 ? "+" : "-") + "$" + Math.abs(g).toFixed(1), _g: g };
  });
  const netGain = rawPos.reduce((a, p) => a + ((p.value || 0) - (p.shares || 0) * (p.avg_cost || 0)), 0);
  const barPos = universe.map(sym => {
    const p = posBySym[sym];
    return { symbol: sym, invested: p ? p._cost : 0, value: p ? (p.value || 0) : 0, cost_basis: p ? p._cost : 0 };
  });
  // Legenda che mostra ANCHE le voci a zero (dimmate); per i guadagni colora per segno.
  const fullLegend = (items, signed) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 4, fontSize: 12, flex: 1, minWidth: 0 }}>
      {items.map((x, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 6, opacity: x.value > 0 ? 1 : 0.42 }}>
          <span style={{ width: 9, height: 9, borderRadius: 2, background: x.color, flexShrink: 0 }}></span>
          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{x.label}</span>
          <span className="mono" style={{ marginLeft: "auto", color: signed && x._g != null ? (x._g >= 0 ? "var(--green)" : "var(--red)") : "var(--text-muted)" }}>{x.display}</span>
        </div>
      ))}
    </div>
  );

  return (
    <div style={{ padding: 16, overflowY: "auto", height: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6, flexWrap: "wrap" }}>
        <button className="btn btn-sm" onClick={onBack}><Icon name="rewind" size={13} /> Strategia</button>
        <h3 style={{ margin: 0, fontSize: 15 }}>Portfolio Manager <span style={{ color: "var(--violet)" }}>AI</span></h3>
        <span style={{ fontSize: 11, color: "var(--amber)", border: "1px solid var(--amber)", borderRadius: 5, padding: "1px 7px" }}>denaro fittizio · paper</span>
        <button className="btn btn-sm" style={{ marginLeft: "auto" }} onClick={() => load()}><Icon name="refresh" size={13} /> Aggiorna</button>
      </div>
      <div style={{ color: "var(--text-muted)", fontSize: 12.5, marginBottom: 14 }}>
        Trader AI a <b>cassa unica $10k</b>: decide come una persona usando tutti i tool, sizing per rischio (1%/trade),
        stop/target. Si attiva solo sugli eventi. Confronto vs comprare-e-tenere e SPY.
      </div>
      {d?.active && d?.last_run && (
        <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 14, display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}
             title="Timestamp dell'ultimo ciclo del PM (scrive un punto NAV ad ogni esecuzione durante il mercato).">
          <Icon name="clock" size={13} />
          Ultima esecuzione: <b style={{ color: "var(--text)" }}>{_simFmtEval(d.last_run)}</b>
          <span style={{ color: "var(--text-faint)" }}>· gira ad ogni ciclo a mercato aperto</span>
        </div>
      )}
      {err && <div style={{ color: "var(--red)", marginBottom: 12 }}>Errore: {err}</div>}
      {d && !d.active && (
        <div className="card" style={{ color: "var(--text-muted)" }}>
          Il Portfolio Manager non ha ancora una settimana attiva — parte al <b>reset di lunedì</b> e inizia a tradare con dati reali.
        </div>
      )}
      {d?.active && <>
        {/* Summary */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 14 }}>
          <div className="card" style={{ flex: "1 1 210px", minWidth: 180 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 4 }}>NAV · settimana</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: pc(s.return_pct) }}>{pct(s.return_pct)}</div>
            <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>${(s.nav || 0).toFixed(0)} su ${(d.capital || 0).toFixed(0)} · {s.n_pos || 0} pos · {s.n_trades || 0} trade</div>
          </div>
          <div className="card" style={{ flex: "1 1 160px", minWidth: 140 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 4 }}>vs Buy&amp;Hold</div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 600, color: pc(s.bh_return_pct) }}>{pct(s.bh_return_pct)}</div>
            <div style={{ fontSize: 11.5, color: pc((s.return_pct || 0) - (s.bh_return_pct || 0)) }}>Δ {pct((s.return_pct || 0) - (s.bh_return_pct || 0))}</div>
          </div>
          <div className="card" style={{ flex: "1 1 160px", minWidth: 140 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 4 }}>vs SPY</div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 600, color: pc(s.spy_return_pct) }}>{pct(s.spy_return_pct)}</div>
            <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>cash ${(cash).toFixed(0)}</div>
          </div>
        </div>

        {/* Torte */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 14 }}>
          <div className="card" style={{ flex: "1 1 300px", minWidth: 250 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--text-muted)", marginBottom: 8 }}>Capitale per posizione</div>
            <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
              <SimDonut slices={allocSlices} size={isMobile ? 150 : 200} center={"$" + (s.nav || 0).toFixed(0)} centerSub="NAV" />
              {fullLegend(allocSlices)}
            </div>
          </div>
          <div className="card" style={{ flex: "1 1 300px", minWidth: 250 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--text-muted)", marginBottom: 8 }}>Guadagni per posizione</div>
            <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
              <SimDonut slices={gainSlices} size={isMobile ? 150 : 200}
                        center={(netGain >= 0 ? "+" : "-") + "$" + Math.abs(netGain).toFixed(0)}
                        centerSub="netto" centerColor={netGain >= 0 ? "#3fb950" : "#f0556b"} />
              {fullLegend(gainSlices, true)}
            </div>
          </div>
        </div>

        {/* Curva NAV */}
        <div style={{ display: "flex", alignItems: "baseline", gap: 12, margin: "0 0 6px", flexWrap: "wrap" }}>
          <h3 style={{ margin: 0, fontSize: 14 }}>Andamento del valore</h3>
          <span style={{ fontSize: 11.5 }}>
            <b style={{ color: "#22c55e" }}>— PM</b> · <b style={{ color: "#8892a4" }}>— compra-e-tieni</b> · <b style={{ color: "#6ea8fe" }}>— SPY</b>
          </span>
        </div>
        <div className="card" style={{ position: "relative", height: 240, marginBottom: 16, padding: 0 }}>
          {(d.nav && d.nav.length > 1)
            ? <SimNavChart nav={d.nav} />
            : <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", color: "var(--text-faint)", fontSize: 12.5 }}>Curva in costruzione (servono più punti durante la settimana).</div>}
        </div>

        {/* Barre */}
        {positions.length > 0 && (
          <div className="card" style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--text-muted)", marginBottom: 3 }}>Investito e guadagno per posizione</div>
            <div style={{ fontSize: 11, color: "var(--text-faint)", marginBottom: 8 }}>
              <b style={{ color: "#5b8def" }}>▮ investito</b> · <b style={{ color: "#3fb950" }}>▮ guadagno</b> / <b style={{ color: "#f0556b" }}>perdita</b> · valore sopra ogni barra
            </div>
            <SimBars positions={barPos} budget={0} />
          </div>
        )}

        {/* Posizioni */}
        <h3 style={{ margin: "0 0 8px", fontSize: 14 }}>Posizioni aperte</h3>
        {positions.length === 0 ? (
          <div className="card" style={{ color: "var(--text-muted)", fontSize: 12.5, marginBottom: 16 }}>Nessuna posizione aperta.</div>
        ) : isMobile ? (
          <div className="card" style={{ padding: 0, marginBottom: 16 }}>
            {positions.map(p => (
              <div key={p.symbol} style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", borderTop: "1px solid var(--border-soft)" }}>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <strong>{p.symbol}</strong>
                  <div className="mono" style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 3 }}>
                    {p.shares} az @ ${p.avg_cost} · stop {p.stop} · tgt {p.target}
                  </div>
                </div>
                <div style={{ textAlign: "right", flexShrink: 0 }}>
                  <div className="mono" style={{ fontWeight: 700, fontSize: 13.5 }}>${(p.value || 0).toFixed(0)}</div>
                  <div className="mono" style={{ fontSize: 12, color: pc(p.pnl_pct), fontWeight: 600 }}>{pct(p.pnl_pct)}</div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="card" style={{ padding: 0, marginBottom: 16 }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
              <thead><tr style={{ color: "var(--text-muted)", textAlign: "right" }}>
                <th style={{ textAlign: "left", padding: "9px 14px", fontWeight: 600 }}>Ticker</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Azioni</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Costo</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Prezzo</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Valore</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>P&amp;L</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Stop</th>
                <th style={{ padding: "9px 14px", fontWeight: 600 }}>Target</th>
              </tr></thead>
              <tbody>
                {positions.map(p => (
                  <tr key={p.symbol} style={{ borderTop: "1px solid var(--border-soft)", textAlign: "right" }}>
                    <td style={{ textAlign: "left", padding: "9px 14px", fontWeight: 600 }}>{p.symbol}</td>
                    <td className="mono" style={{ padding: "9px 8px", color: "var(--text-muted)" }}>{p.shares}</td>
                    <td className="mono" style={{ padding: "9px 8px" }}>${p.avg_cost}</td>
                    <td className="mono" style={{ padding: "9px 8px" }}>${p.last_price}</td>
                    <td className="mono" style={{ padding: "9px 8px", fontWeight: 600 }}>${(p.value || 0).toFixed(0)}</td>
                    <td className="mono" style={{ padding: "9px 8px", color: pc(p.pnl_pct), fontWeight: 700 }}>{pct(p.pnl_pct)}</td>
                    <td className="mono" style={{ padding: "9px 8px", color: "var(--red)" }}>{p.stop}</td>
                    <td className="mono" style={{ padding: "9px 14px", color: "var(--green)" }}>{p.target}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Watchlist dinamica — aziende analizzate */}
        <h3 style={{ margin: "0 0 6px", fontSize: 14 }}>
          Aziende seguite dal PM <span style={{ color: "var(--text-muted)", fontWeight: 400, fontSize: 12 }}>({wl.length})</span>
        </h3>
        <div style={{ fontSize: 11.5, color: "var(--text-faint)", marginBottom: 8 }}>
          Universo analizzato questa settimana. <b style={{ color: "var(--green)" }}>● in posizione</b> ·{" "}
          <span style={{ color: "var(--violet)" }}>🃏 Top Pick</span> = subentrata da Tool9 in settimana.
        </div>
        <div className="card" style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 16 }}>
          {wl.length === 0
            ? <span style={{ color: "var(--text-muted)", fontSize: 12 }}>—</span>
            : wl.map(w => {
              const held = heldSet.has(w.symbol);
              const pick = w.source === "tool9";
              return (
                <span key={w.symbol} title={pick ? "Subentrata dai Top Picks (Tool9)" : (held ? "In posizione" : "In watchlist")}
                      style={{
                        display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px", borderRadius: 20,
                        fontSize: 12, fontFamily: "JetBrains Mono, monospace",
                        border: `1px solid ${pick ? "var(--violet)" : held ? "var(--green)" : "var(--border-soft)"}`,
                        background: pick ? "rgba(157,141,241,0.12)" : held ? "rgba(34,197,94,0.08)" : "transparent",
                      }}>
                  {held && <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--green)", flexShrink: 0 }} />}
                  <b>{w.symbol}</b>
                  {pick && <span style={{ color: "var(--violet)", fontSize: 10.5 }}>🃏 Top Pick</span>}
                </span>
              );
            })}
        </div>

        {/* Settimane passate (chiuse) — storico pm_weeks */}
        <h3 style={{ margin: "18px 0 8px", fontSize: 14 }}>Settimane passate</h3>
        {(!d?.weeks || d.weeks.length === 0)
          ? <div className="card" style={{ color: "var(--text-muted)", fontSize: 12.5 }}>Nessuna settimana finalizzata ancora.</div>
          : <div className="card" 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: "4px 8px" }}>Settimana</th>
                  <th style={{ padding: "4px 8px" }}>Valore</th>
                  <th style={{ padding: "4px 8px" }}>Rendimento</th>
                  <th style={{ padding: "4px 8px" }}>vs B&amp;H</th>
                  <th style={{ padding: "4px 8px" }}>vs SPY</th>
                  <th style={{ padding: "4px 8px" }}>Trade</th>
                </tr></thead>
                <tbody>
                  {d.weeks.map((w, i) => (
                    <tr key={i} style={{ borderTop: "1px solid var(--border)", textAlign: "right" }}>
                      <td style={{ textAlign: "left", padding: "4px 8px" }}>{w.week_start}</td>
                      <td style={{ padding: "4px 8px" }}>{w.end_value != null ? "$" + w.end_value.toFixed(0) : "—"}</td>
                      <td style={{ padding: "4px 8px", color: pc(w.return_pct), fontWeight: 600 }}>{pct(w.return_pct)}</td>
                      <td style={{ padding: "4px 8px", color: pc(w.bh_return_pct) }}>{pct(w.bh_return_pct)}</td>
                      <td style={{ padding: "4px 8px", color: pc(w.spy_return_pct) }}>{pct(w.spy_return_pct)}</td>
                      <td style={{ padding: "4px 8px" }}>{w.n_trades != null ? w.n_trades : "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>}

        {/* Decisioni / reasoning */}
        <h3 style={{ margin: "18px 0 8px", fontSize: 14 }}>Decisioni del PM (reasoning)</h3>
        {dec.length === 0
          ? <div className="card" style={{ color: "var(--text-muted)", fontSize: 12.5 }}>Nessuna decisione registrata.</div>
          : dec.map((x, i) => (
            <div key={i} style={{ borderLeft: `3px solid ${x.action === "ENTER" ? "var(--green)" : "var(--text-faint)"}`, padding: "7px 11px", marginBottom: 6, background: "var(--surface)", borderRadius: 6 }}>
              <div style={{ fontSize: 11, color: "var(--text-muted)" }}>
                <b>{x.symbol}</b> · <span style={{ color: x.action === "ENTER" ? "var(--green)" : "var(--text-muted)", fontWeight: 600 }}>{x.action}</span> · {x.event} · {(x.timestamp || "").slice(5, 16).replace("T", " ")}
              </div>
              <div style={{ fontSize: 12, marginTop: 2 }}>{x.reasoning}</div>
            </div>
          ))}
      </>}
    </div>
  );
}

function SimulatorView() {
  const [mode, setMode] = useState("strategy");
  const [data, setData] = useState(null);
  const [hist, setHist] = useState({ weeks: [] });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [status, setStatus] = useState(null);     // null | running | ok | err
  const [openWeek, setOpenWeek] = useState(null);
  const [detail, setDetail] = useState([]);
  const [updatedAt, setUpdatedAt] = useState(null);
  const [help, setHelp] = useState(false);
  const [isMobile, setIsMobile] = useState(typeof window !== "undefined" && window.innerWidth < 760);
  useEffect(() => {
    const onR = () => setIsMobile(window.innerWidth < 760);
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
  }, []);

  const load = async (spin) => {
    if (spin) setLoading(true);
    try {
      const [d, h] = await Promise.all([
        fetch("/api/simulator").then(r => r.json()),
        fetch("/api/simulator/history").then(r => r.json()),
      ]);
      setData(d); setHist(h || { weeks: [] }); setError(d?.error || null);
      setUpdatedAt(new Date());
    } catch (e) { setError(String(e)); }
    finally { if (spin) setLoading(false); }
  };
  useEffect(() => {
    load(true);
    const t = setInterval(() => load(false), 60 * 1000);   // auto-refresh ogni 60s
    return () => clearInterval(t);
  }, []);

  const act = async (path) => {
    setStatus("running");
    try {
      await fetch(path, { method: "POST" });
      // Il trade/reset gira in background sul server: ricarico a 2s e di nuovo a 6s
      // (così vedi l'esito senza F5, anche se il ciclo è un po' lento).
      setTimeout(() => load(false), 2000);
      setTimeout(() => { load(false); setStatus("ok"); setTimeout(() => setStatus(null), 3500); }, 6000);
    } catch { setStatus("err"); setTimeout(() => setStatus(null), 3000); }
  };

  const openDetail = async (wk) => {
    if (openWeek === wk) { setOpenWeek(null); return; }
    setOpenWeek(wk);
    try {
      const h = await fetch("/api/simulator/history?week=" + encodeURIComponent(wk)).then(r => r.json());
      setDetail(h.detail || []);
    } catch { setDetail([]); }
  };

  const pctC = (v) => v == null ? "var(--text-muted)" : v >= 0 ? "var(--green)" : "var(--red)";
  const pct = (v) => v == null ? "—" : `${v >= 0 ? "+" : ""}${v.toFixed(2)}%`;
  const sigColor = (s) => {
    if (!s) return "var(--text-muted)";
    if (s.includes("BUY")) return "var(--green)";
    if (s.includes("SELL")) return "var(--red)";
    return "var(--amber)";
  };

  const s = data?.summary || {};
  const positions = data?.positions || [];
  const trades = data?.trades || [];

  // Torte: (1) capitale per azione + cash da investire, (2) guadagni per azione
  const budget = data?.budget || 500;
  // Palette armoniosa (toni blu/teal/viola in linea con l'app), non arcobaleno.
  const PALETTE = ["#6ea8fe", "#56cfe1", "#9d8df1", "#5fd0ac", "#7aa2f7",
                   "#c08cf0", "#74c0fc", "#80b8a0", "#a3b1cf", "#88d3c0"];
  const allocSlices = positions.map((p, i) => ({
    label: p.symbol, value: Math.max(0, p.invested || 0),
    color: PALETTE[i % PALETTE.length], display: "€" + (p.invested || 0).toFixed(0),
  }));
  const totalCash = positions.reduce((a, p) => a + (p.cash || 0), 0);
  if (totalCash > 0) allocSlices.push({ label: "Da investire", value: totalCash, color: "#2d3340", display: "€" + totalCash.toFixed(0) });
  // Stessi colori per-ticker della torta "capitale" (così DELL e MU si distinguono);
  // il segno guadagno/perdita è dato dal +/- nelle etichette e dal valore netto al centro.
  const gainSlices = positions.map((p, i) => {
    const g = (p.value || 0) - budget;
    return { label: p.symbol, value: Math.abs(g), color: PALETTE[i % PALETTE.length],
             display: (g >= 0 ? "+" : "-") + "€" + Math.abs(g).toFixed(1) };
  });
  const netGain = positions.reduce((a, p) => a + ((p.value || 0) - budget), 0);

  if (mode === "pm") return <PMPanel onBack={() => setMode("strategy")} />;

  return (
    <div style={{ padding: 16, overflowY: "auto", height: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4, flexWrap: "wrap" }}>
        <h3 style={{ margin: 0, fontSize: 15 }}>Simulatore</h3>
        <span style={{ fontSize: 11, color: "var(--amber)", border: "1px solid var(--amber)", borderRadius: 5, padding: "1px 7px" }}>
          denaro fittizio · non è consulenza
        </span>
        <button className="icon-btn" onClick={() => setHelp(h => !h)} title="Cos'è questa pagina? (guida)"
                style={help ? { color: "var(--accent)" } : {}}>
          <Icon name="info" size={16} />
        </button>
        <button className="btn btn-sm" onClick={() => setMode("pm")} title="Sleeve Portfolio Manager LLM"
                style={{ borderColor: "var(--violet)", color: "var(--violet)" }}>
          🤖 Portfolio Manager AI
        </button>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" }}>
          {status === "running" && <span style={{ fontSize: 11, color: "var(--amber)" }}>eseguo…</span>}
          {status === "ok" && <span style={{ fontSize: 11, color: "var(--green)" }}>✓ aggiornato</span>}
          {updatedAt && status !== "running" && status !== "ok" && (
            <span style={{ fontSize: 11, color: "var(--text-muted)" }} title="Ultimo aggiornamento dati (auto ogni 60s)">
              agg. {updatedAt.toLocaleTimeString("it-IT")}
            </span>
          )}
          <button className="btn btn-sm" disabled={loading || status === "running"} onClick={() => load(true)}
                  title="Ricarica dati e grafico al prezzo corrente (nessun trade)">
            <Icon name="refresh" size={13} style={loading ? { animation: "spin 1s linear infinite" } : {}} /> Aggiorna
          </button>
          <button className="btn btn-sm" disabled={status === "running"} onClick={() => act("/api/simulator/run-now")}
                  title="Forza subito una rivalutazione: opera solo se il segnale Tool4 è cambiato (altrimenti niente)">
            <Icon name="play" size={13} /> {status === "running" ? "…" : "Trada ora"}
          </button>
          <button className="btn btn-sm" disabled={status === "running"} onClick={() => act("/api/simulator/reset")}
                  title="Riavvia la settimana corrente (reset sleeve + allocazione)">
            <Icon name="rewind" size={13} /> Reset settimana
          </button>
        </div>
      </div>
      <div style={{ color: "var(--text-muted)", fontSize: 12.5, marginBottom: data?.active && data?.last_eval ? 6 : 14 }}>
        Ogni lunedì riparte: €{data?.budget || 500}/ticker, trading attivo Lun→Ven seguendo Tool4. Confronto vs comprare-e-tenere e SPY.
      </div>
      {data?.active && data?.last_eval && (
        <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 14, display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}
             title="Ultimo ciclo del simulatore: rivaluta tutti i ticker. Se i segnali sono HOLD non fa trade, ma la valutazione è avvenuta.">
          <Icon name="clock" size={13} />
          Ultima valutazione: <b style={{ color: "var(--text)" }}>{_simFmtEval(data.last_eval)}</b>
          <span style={{ color: "var(--text-faint)" }}>· nessun trade se i segnali sono HOLD</span>
        </div>
      )}

      {help && (
        <div className="card" style={{ marginBottom: 16, fontSize: 12.5, lineHeight: 1.6 }}>
          <div style={{ display: "flex", alignItems: "center", marginBottom: 8 }}>
            <strong style={{ fontSize: 14 }}>Guida: cosa stai guardando</strong>
            <button className="btn btn-sm" style={{ marginLeft: "auto" }} onClick={() => setHelp(false)}>Chiudi</button>
          </div>
          <p style={{ margin: "0 0 10px" }}>
            <b>Cos'è.</b> Un gioco a <b>soldi finti</b>: ogni lunedì parti con €{data?.budget || 500} per ciascuna
            azione della tua watchlist, e durante la settimana il sistema compra/vende seguendo i segnali di Tool4.
            Serve a vedere se "dare retta" ai segnali avrebbe fatto guadagnare — senza rischiare soldi veri.
          </p>
          <p style={{ margin: "0 0 6px" }}><b>Le 3 card in alto</b></p>
          <ul style={{ margin: "0 0 10px", paddingLeft: 18 }}>
            <li><b>Settimana</b>: guadagno/perdita totale di questa settimana.</li>
            <li><b>vs Buy&amp;Hold</b>: confronto col "compra e tieni" (se lunedì avessi comprato e non toccato più niente). Δ <span style={{ color: "var(--green)" }}>verde</span> = la strategia sta facendo meglio.</li>
            <li><b>vs SPY</b>: confronto con l'indice S&amp;P 500 (il mercato USA nel suo insieme).</li>
          </ul>
          <p style={{ margin: "0 0 6px" }}><b>Le 2 torte</b></p>
          <ul style={{ margin: "0 0 10px", paddingLeft: 18 }}>
            <li><b>Capitale per azione</b>: come sono divisi i tuoi soldi <i>adesso</i> — quanto in ogni azione + quanto ancora in contanti ("Da investire").</li>
            <li><b>Guadagni per azione</b>: quanto pesa il guadagno/perdita di ciascuna azione (stessi colori dell'altra torta). Il <b>+</b> o <b>−</b> e il valore al centro dicono se sei in positivo o negativo.</li>
          </ul>
          <p style={{ margin: "0 0 6px" }}><b>Il grafico a linee (curva)</b></p>
          <p style={{ margin: "0 0 10px" }}>
            È il <b>valore del tuo portafoglio nel tempo</b>, durante la settimana, con 3 linee a confronto:
            <span style={{ color: "#22c55e" }}> ▬ verde = la tua strategia</span>,
            <span style={{ color: "#8892a4" }}> ▬ grigio = compra-e-tieni</span>,
            <span style={{ color: "#6ea8fe" }}> ▬ blu = indice SPY</span>.
            <b> Se il verde sta sopra le altre, il trading sta convenendo</b>; se sta sotto, faresti meglio a non fare nulla.
            (I numeri sull'asse sono euro totali del portafoglio.)
          </p>
          <p style={{ margin: "0 0 6px" }}><b>Posizioni</b>: per ogni azione il segnale attuale, quante ne hai, quanto vale ora e il guadagno/perdita.</p>
          <p style={{ margin: 0 }}><b>Trade recenti</b>: le operazioni (compra/vendi) fatte questa settimana. Tutto è denaro fittizio.</p>
        </div>
      )}

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

      {data && !data.active && (
        <div className="card" style={{ color: "var(--text-muted)" }}>
          Simulatore non ancora avviato. Si attiva dal toggle in <b>Configurazione</b> e parte il lunedì,
          oppure premi <b>Reset settimana</b> per avviarlo subito.
        </div>
      )}

      {data && data.active && <>
        {/* Summary settimana corrente */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 14 }}>
          <div className="card" style={{ flex: "1 1 200px", minWidth: 170 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 4 }}>Settimana {s.week_start}</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: pctC(s.return_pct) }}>{pct(s.return_pct)}</div>
            <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>€{(s.nav || 0).toFixed(0)} su €{(s.total_start || 0).toFixed(0)} · {s.n_trades || 0} trade</div>
          </div>
          <div className="card" style={{ flex: "1 1 160px", minWidth: 140 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 4 }}>vs Buy&amp;Hold</div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 600, color: pctC(s.bh_return_pct) }}>{pct(s.bh_return_pct)}</div>
            <div style={{ fontSize: 11.5, color: pctC((s.return_pct || 0) - (s.bh_return_pct || 0)) }}>
              {(s.return_pct != null && s.bh_return_pct != null) ? `Δ ${pct((s.return_pct || 0) - (s.bh_return_pct || 0))}` : ""}
            </div>
          </div>
          <div className="card" style={{ flex: "1 1 160px", minWidth: 140 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--text-muted)", marginBottom: 4 }}>vs SPY</div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 600, color: pctC(s.spy_return_pct) }}>{pct(s.spy_return_pct)}</div>
          </div>
        </div>

        {/* Torte: capitale per azione + guadagni per azione */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 14 }}>
          <div className="card" style={{ flex: "1 1 300px", minWidth: 250 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--text-muted)", marginBottom: 8 }}>Capitale per azione</div>
            <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
              <SimDonut slices={allocSlices} size={isMobile ? 150 : 200} center={"€" + (s.nav || 0).toFixed(0)} centerSub="NAV" />
              <SimLegend items={allocSlices} />
            </div>
          </div>
          <div className="card" style={{ flex: "1 1 300px", minWidth: 250 }}>
            <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--text-muted)", marginBottom: 8 }}>Guadagni per azione</div>
            <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
              <SimDonut slices={gainSlices} size={isMobile ? 150 : 200}
                        center={(netGain >= 0 ? "+" : "-") + "€" + Math.abs(netGain).toFixed(0)}
                        centerSub="netto" centerColor={netGain >= 0 ? "#3fb950" : "#f0556b"} />
              <SimLegend items={gainSlices} />
            </div>
          </div>
        </div>

        {/* Curva NAV */}
        <div style={{ display: "flex", alignItems: "baseline", gap: 12, margin: "0 0 6px", flexWrap: "wrap" }}>
          <h3 style={{ margin: 0, fontSize: 14 }}>Andamento del valore</h3>
          <span style={{ fontSize: 11.5 }}>
            <b style={{ color: "#22c55e" }}>— strategia</b> ·{" "}
            <b style={{ color: "#8892a4" }}>— compra-e-tieni</b> ·{" "}
            <b style={{ color: "#6ea8fe" }}>— SPY</b>
          </span>
        </div>
        <div className="card" style={{ position: "relative", height: 240, marginBottom: 4, padding: 0 }}>
          {(data.nav && data.nav.length > 1)
            ? <SimNavChart nav={data.nav} />
            : <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", color: "var(--text-faint)", fontSize: 12.5 }}>
                Curva in costruzione (servono più punti durante la settimana).
              </div>}
        </div>
        <div style={{ fontSize: 11.5, color: "var(--text-muted)", marginBottom: 16 }}>
          Valore del tuo portafoglio (in €) nel tempo. Se la linea <b style={{ color: "#22c55e" }}>verde</b> sta
          sopra le altre, seguire i segnali sta convenendo rispetto a tenere fermo o all'indice.
        </div>

        {/* Barre: investito + guadagno per azione */}
        <div className="card" style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--text-muted)", marginBottom: 3 }}>Investito e guadagno per azione</div>
          <div style={{ fontSize: 11, color: "var(--text-faint)", marginBottom: 8 }}>
            <b style={{ color: "#5b8def" }}>▮ investito</b> · <b style={{ color: "#3fb950" }}>▮ guadagno</b> / <b style={{ color: "#f0556b" }}>perdita</b> · scale diverse (la perdita va comunque in alto, in rosso) · valore sopra ogni barra
          </div>
          <SimBars positions={positions} budget={budget} />
        </div>

        {/* Posizioni — tabella chiara su desktop, card su mobile */}
        <h3 style={{ margin: "0 0 8px", fontSize: 14 }}>Posizioni</h3>
        {isMobile ? (
          <div className="card" style={{ padding: 0, marginBottom: 16 }}>
            {positions.map(p => (
              <div key={p.symbol} style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", borderTop: "1px solid var(--border-soft)" }}>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                    <strong title={p.name}>{p.symbol}</strong>
                    <span style={{ color: sigColor(p.t4_signal), fontWeight: 600, fontSize: 11.5 }}>{p.t4_signal || "—"}</span>
                  </div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 3 }}>
                    investito €{p.invested} · cash €{p.cash} · {p.shares} az{p.n_trades ? ` · ${p.n_trades} trade` : ""}
                  </div>
                </div>
                <div style={{ textAlign: "right", flexShrink: 0 }}>
                  <div className="mono" style={{ fontWeight: 700, fontSize: 13.5 }}>€{p.value}</div>
                  <div className="mono" style={{ fontSize: 12, color: pctC(p.pnl_pct), fontWeight: 600 }}>{pct(p.pnl_pct)}</div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="card" style={{ padding: 0, marginBottom: 16 }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
              <thead><tr style={{ color: "var(--text-muted)", textAlign: "right" }}>
                <th style={{ textAlign: "left", padding: "9px 14px", fontWeight: 600 }}>Ticker</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Segnale</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Azioni</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Investito</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Cash</th>
                <th style={{ padding: "9px 8px", fontWeight: 600 }}>Valore</th>
                <th style={{ padding: "9px 14px", fontWeight: 600 }}>P&amp;L</th>
              </tr></thead>
              <tbody>
                {positions.map(p => (
                  <tr key={p.symbol} style={{ borderTop: "1px solid var(--border-soft)", textAlign: "right" }}>
                    <td style={{ textAlign: "left", padding: "9px 14px", fontWeight: 600 }} title={p.name}>{p.symbol}</td>
                    <td className="mono" style={{ padding: "9px 8px", color: sigColor(p.t4_signal), fontWeight: 600 }}>{p.t4_signal || "—"}</td>
                    <td className="mono" style={{ padding: "9px 8px", color: "var(--text-muted)" }}>{p.shares}</td>
                    <td className="mono" style={{ padding: "9px 8px" }}>€{p.invested}</td>
                    <td className="mono" style={{ padding: "9px 8px", color: "var(--text-muted)" }}>€{p.cash}</td>
                    <td className="mono" style={{ padding: "9px 8px", fontWeight: 600 }}>€{p.value}</td>
                    <td className="mono" style={{ padding: "9px 14px", color: pctC(p.pnl_pct), fontWeight: 700 }}>{pct(p.pnl_pct)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Trade recenti — righe responsive */}
        {trades.length > 0 && <>
          <h3 style={{ margin: "0 0 8px", fontSize: 14 }}>Trade recenti</h3>
          <div className="card" style={{ padding: 0, marginBottom: 16, maxHeight: 260, overflowY: "auto" }}>
            {trades.map((t, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 14px", borderTop: "1px solid var(--border-soft)" }}>
                <span style={{ color: t.side === "BUY" ? "var(--green)" : "var(--red)", fontWeight: 700, fontSize: 11.5, minWidth: 32, flexShrink: 0 }}>{t.side}</span>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div><strong>{t.symbol}</strong> <span className="mono" style={{ color: "var(--text-muted)", fontSize: 12 }}>@{(t.price || 0).toFixed(2)}</span></div>
                  <div style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 2 }}>{(t.timestamp || "").slice(5, 16).replace("T", " ")} · {t.reason}</div>
                </div>
                <span className="mono" style={{ fontWeight: 600, flexShrink: 0 }}>€{(t.value || 0).toFixed(0)}</span>
              </div>
            ))}
          </div>
        </>}
      </>}

      {/* Settimane passate */}
      <h3 style={{ margin: "0 0 8px", fontSize: 14 }}>Settimane passate</h3>
      {(!hist.weeks || hist.weeks.length === 0)
        ? <div style={{ color: "var(--text-muted)", fontSize: 12.5 }}>Nessuna settimana finalizzata ancora.</div>
        : <div className="card" style={{ padding: 0, 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: "7px 12px" }}>Settimana</th>
                <th>Rendimento</th><th>Buy&amp;Hold</th><th>SPY</th><th>Trade</th><th></th>
              </tr></thead>
              <tbody>
                {hist.weeks.map(w => (
                  <React.Fragment key={w.week_start}>
                    <tr style={{ borderTop: "1px solid var(--border-soft)", textAlign: "right", cursor: "pointer" }} onClick={() => openDetail(w.week_start)}>
                      <td style={{ textAlign: "left", padding: "6px 12px", fontWeight: 600 }}>{w.week_start}</td>
                      <td className="mono" style={{ color: pctC(w.return_pct), fontWeight: 700 }}>{pct(w.return_pct)}</td>
                      <td className="mono" style={{ color: pctC(w.bh_return_pct) }}>{pct(w.bh_return_pct)}</td>
                      <td className="mono" style={{ color: pctC(w.spy_return_pct) }}>{pct(w.spy_return_pct)}</td>
                      <td className="mono" style={{ color: "var(--text-muted)" }}>{w.n_trades}</td>
                      <td style={{ color: "var(--text-muted)" }}><Icon name="chevDown" size={13} /></td>
                    </tr>
                    {openWeek === w.week_start && (
                      <tr><td colSpan={6} style={{ padding: 0, background: "var(--bg-soft, rgba(255,255,255,0.02))" }}>
                        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                          <tbody>
                            {detail.map(d => (
                              <tr key={d.symbol} style={{ borderTop: "1px solid var(--border-soft)", textAlign: "right" }}>
                                <td style={{ textAlign: "left", padding: "4px 22px", fontWeight: 600 }}>{d.symbol}</td>
                                <td className="mono" style={{ color: pctC(d.return_pct) }}>{pct(d.return_pct)}</td>
                                <td className="mono" style={{ color: "var(--text-muted)" }}>buy-hold {pct(d.bh_return_pct)}</td>
                                <td className="mono" style={{ color: "var(--text-muted)", padding: "4px 22px" }}>{d.n_trades} trade</td>
                              </tr>
                            ))}
                            {detail.length === 0 && <tr><td style={{ padding: "6px 22px", color: "var(--text-muted)" }}>—</td></tr>}
                          </tbody>
                        </table>
                      </td></tr>
                    )}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
          </div>}
    </div>
  );
}

window.SimulatorView = SimulatorView;
