// Reports · a printable summary view + JSON export/import + AI plan narrator.

function Reports() {
  const { state, prices } = useStore();
  const cur = state.settings.currency;
  const portfolio = React.useMemo(() => computePortfolio(state, prices), [state, prices]);
  const peak = React.useMemo(() => peakValuation(state), [state]);
  const risk = React.useMemo(() => roundTripRisk(state, prices), [state, prices]);

  const [narration, setNarration] = React.useState(null);
  const [loadingNarr, setLoadingNarr] = React.useState(false);

  async function generateNarration() {
    if (!aiAvailable(state)) return;
    setLoadingNarr(true);
    try {
      const summary = {
        currency: cur,
        total: portfolio.total,
        cost: portfolio.totalCost,
        pnlPct: portfolio.pnlPct,
        riskLabel: risk.label,
        riskScore: risk.score,
        peakIfHit: peak,
        holdings: portfolio.rows.map(r => ({
          symbol: r.meta.symbol, value: Math.round(r.value), pnlPct: Math.round(r.pnlPct),
          alloc: Math.round(r.alloc), hasLadder: !!state.ladders[r.coinId],
        })),
      };
      const prompt = `You are a calm, direct exit-strategy coach. Given this crypto portfolio summary as JSON, write 2 short paragraphs (max ~120 words) summarizing the user's position, the round-trip risk, and one concrete action. Be specific, never preachy. Avoid emojis. Avoid all-caps. No financial advice disclaimers · they exist elsewhere. Do not use em dashes (—). Use periods and commas.\n\n${JSON.stringify(summary)}`;
      const { text } = await aiComplete(prompt, state);
      setNarration(text);
    } catch (e) {
      setNarration(e?.message || "AI narration unavailable right now. Use Settings → AI Coach to retry.");
    } finally {
      setLoadingNarr(false);
    }
  }

  function exportJSON() {
    const data = JSON.stringify(state, null, 2);
    const blob = new Blob([data], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `exitos-backup-${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
  }

  function exportCSV() {
    const headers = ["Coin", "Symbol", "Amount", "Avg Buy", "Current Price", "Value", "Cost", "PnL", "PnL%"];
    const rows = portfolio.rows.map(r => [
      r.meta.name, r.meta.symbol, r.amount, r.avgBuyPrice, r.price, r.value, r.cost, r.pnl, r.pnlPct.toFixed(2)
    ]);
    const csv = [headers, ...rows].map(r => r.join(",")).join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `exitos-portfolio-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  function printReport() {
    window.print();
  }

  return (
    <div className="exos-page">
      <div className="exos-page-head no-print">
        <div>
          <div className="exos-kicker mono">REPORTS</div>
          <h1 className="exos-h1">Your exit plan, on paper.</h1>
          <div className="exos-page-head-sub">A clean summary you can save, print, or share. All your data, in your hands.</div>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Button icon={<Icons.Download size={14} />} onClick={exportCSV}>CSV</Button>
          <Button icon={<Icons.Download size={14} />} onClick={exportJSON}>JSON backup</Button>
          <Button variant="primary" icon={<Icons.Reports size={14} />} onClick={printReport}>Save as PDF</Button>
        </div>
      </div>

      {aiAvailable(state) && (
        <Card className="exos-ai-card no-print" style={{ marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
            <span style={{ display: "inline-flex", padding: 8, background: "var(--accent-soft)", borderRadius: 8, color: "var(--accent)" }}>
              <Icons.Sparkle size={18} />
            </span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 500 }}>AI Plan Narrator</div>
              <div style={{ fontSize: 13, color: "var(--text-mute)" }}>Get a plain-English summary of your position and one concrete action.</div>
              {narration && (
                <div className="exos-ai-narration">
                  {narration.split(/\n\n+/).map((p, i) => <p key={i}>{p}</p>)}
                </div>
              )}
            </div>
            <Button size="sm" variant="primary" onClick={generateNarration} disabled={loadingNarr}>
              {loadingNarr ? "Writing…" : narration ? "Rewrite" : "Generate"}
            </Button>
          </div>
        </Card>
      )}

      {/* The actual report */}
      <div className="exos-report" id="exos-report-body">
        <div className="exos-report-header">
          <div>
            <div className="exos-kicker mono" style={{ color: "var(--accent)" }}>EXITOS · AI-ASSISTED EXIT PLAN</div>
            <h1 style={{ margin: "6px 0 4px", fontSize: 26, fontWeight: 500 }}>Bull-market decision system</h1>
            <div style={{ color: "var(--text-mute)", fontSize: 13 }}>Generated {new Date().toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" })} · Currency: {cur}</div>
          </div>
          <div className="exos-report-stamp mono">
            <div>{risk.label.toUpperCase()} RISK</div>
            <div style={{ fontSize: 11, color: "var(--text-mute)" }}>{risk.score}/100</div>
          </div>
        </div>

        <div className="exos-report-grid">
          <ReportStat label="Total value" value={fmtCurrency(portfolio.total, cur, { compact: true })} />
          <ReportStat label="Cost basis" value={fmtCurrency(portfolio.totalCost, cur, { compact: true })} />
          <ReportStat label="Unrealized P/L" value={fmtPct(portfolio.pnlPct)} tone={portfolio.pnl >= 0 ? "gain" : "loss"} />
          <ReportStat label="Peak target" value={fmtCurrency(peak, cur, { compact: true })} />
        </div>

        <h3 className="exos-report-h">Holdings</h3>
        <table className="exos-report-table">
          <thead>
            <tr>
              <th>Coin</th><th className="right">Amount</th><th className="right">Avg Buy</th>
              <th className="right">Price</th><th className="right">Value</th>
              <th className="right">P/L</th><th className="right">Alloc</th>
            </tr>
          </thead>
          <tbody>
            {portfolio.rows.map(r => (
              <tr key={r.id}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: r.meta.color }} />
                    <span>{r.meta.symbol}</span>
                    <span style={{ color: "var(--text-mute)" }}>· {r.meta.name}</span>
                  </div>
                </td>
                <td className="right mono">{fmtNum(r.amount, 4)}</td>
                <td className="right mono">{fmtCurrency(r.avgBuyPrice, cur, { precise: r.avgBuyPrice < 10 })}</td>
                <td className="right mono">{fmtCurrency(r.price, cur, { precise: r.price < 10 })}</td>
                <td className="right mono">{fmtCurrency(r.value, cur, { compact: true })}</td>
                <td className="right mono" style={{ color: r.pnl >= 0 ? "var(--gain)" : "var(--loss)" }}>{fmtPct(r.pnlPct)}</td>
                <td className="right mono">{r.alloc.toFixed(1)}%</td>
              </tr>
            ))}
          </tbody>
        </table>

        <h3 className="exos-report-h">Exit ladders</h3>
        {portfolio.rows.map(r => {
          const ladder = state.ladders[r.coinId];
          if (!ladder || !ladder.targets?.length) return null;
          const c = computeLadder(r, ladder, r.price, state.settings.taxRate);
          return (
            <div key={r.id} className="exos-report-ladder">
              <div className="exos-report-ladder-head">
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 3, background: r.meta.color }} />
                  <span style={{ fontWeight: 500 }}>{r.meta.symbol}</span>
                  <span style={{ color: "var(--text-mute)" }}>· {fmtNum(r.amount, 4)} held @ {fmtCurrency(r.avgBuyPrice, cur, { precise: r.avgBuyPrice < 10 })}</span>
                </div>
                <div className="mono" style={{ fontSize: 12, color: "var(--text-mute)" }}>
                  Plans to sell {c.sumPct}% · keep {c.remainingPct}% moon bag
                </div>
              </div>
              <table className="exos-report-table">
                <thead>
                  <tr>
                    <th>Target</th><th className="right">Price</th><th className="right">Multiple</th>
                    <th className="right">Sell %</th><th className="right">Coins</th>
                    <th className="right">Proceeds</th><th className="right">Net (after tax)</th>
                  </tr>
                </thead>
                <tbody>
                  {c.targets.map((t, i) => (
                    <tr key={t.id}>
                      <td>#{i+1}</td>
                      <td className="right mono">{fmtCurrency(t.price, cur, { precise: t.price < 10 })}</td>
                      <td className="right mono">{(t.price / r.avgBuyPrice).toFixed(2)}×</td>
                      <td className="right mono">{t.sellPercent}%</td>
                      <td className="right mono">{fmtNum(t.coinsSold, 4)}</td>
                      <td className="right mono">{fmtCurrency(t.proceeds, cur, { compact: true })}</td>
                      <td className="right mono">{fmtCurrency(t.net, cur, { compact: true })}</td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr>
                    <td colSpan={5} style={{ textAlign: "right", color: "var(--text-mute)" }}>Plan total</td>
                    <td className="right mono" style={{ fontWeight: 500 }}>{fmtCurrency(c.totalProceeds, cur, { compact: true })}</td>
                    <td className="right mono" style={{ fontWeight: 500, color: "var(--gain)" }}>{fmtCurrency(c.totalNet, cur, { compact: true })}</td>
                  </tr>
                </tfoot>
              </table>
            </div>
          );
        })}

        <div className="exos-report-disclaimer">
          <strong>Not financial advice.</strong> ExitOS is a planning tool. Prices shown are simulated for demonstration.
          Tax estimates use a flat {Math.round(state.settings.taxRate * 100)}% reserve and may not match your jurisdiction's rules.
          Your data is stored locally in your browser and is not uploaded to ExitOS servers.
        </div>
      </div>
    </div>
  );
}

function ReportStat({ label, value, tone }) {
  const colors = { gain: "var(--gain)", loss: "var(--loss)" };
  return (
    <div className="exos-report-stat">
      <div className="exos-label">{label}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 500, color: colors[tone] }}>{value}</div>
    </div>
  );
}

const REPORTS_STYLES = `
.exos-ai-card { background: linear-gradient(90deg, var(--accent-soft) 0%, transparent 60%); }
.exos-ai-narration { margin-top: 10px; font-size: 13px; line-height: 1.55; color: var(--text); }
.exos-ai-narration p { margin: 0 0 8px; }

.exos-report { background: var(--bg-elev); border: 1px solid var(--line); border-radius: var(--radius-lg); padding: 32px; }
.exos-report-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 18px; padding-bottom: 24px; border-bottom: 1px solid var(--line); }
.exos-report-stamp {
  padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px;
  text-align: center; font-size: 11px; font-weight: 500; letter-spacing: 0.1em;
}
.exos-report-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0; margin: 22px 0; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
.exos-report-stat { padding: 14px 16px; border-right: 1px solid var(--line); }
.exos-report-stat:last-child { border-right: 0; }
.exos-report-h { font-size: 14px; font-weight: 500; letter-spacing: -0.005em; margin: 26px 0 10px; padding-bottom: 8px; border-bottom: 1px solid var(--line); }
.exos-report-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.exos-report-table th, .exos-report-table td { padding: 8px 10px; text-align: left; }
.exos-report-table th { color: var(--text-mute); font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid var(--line); }
.exos-report-table tbody tr { border-bottom: 1px solid var(--line); }
.exos-report-table .right { text-align: right; }
.exos-report-table tfoot td { border-top: 1px solid var(--line); padding-top: 10px; }
.exos-report-ladder { margin-bottom: 18px; padding: 14px; background: var(--bg-elev-2); border-radius: 10px; border: 1px solid var(--line); }
.exos-report-ladder-head { display: flex; justify-content: space-between; align-items: center; padding-bottom: 10px; margin-bottom: 6px; border-bottom: 1px solid var(--line); }
.exos-report-disclaimer { margin-top: 28px; padding: 14px 16px; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; font-size: 11px; color: var(--text-mute); line-height: 1.55; }
.exos-report-disclaimer strong { color: var(--text); }

@media print {
  @page { margin: 12mm 14mm; size: A4; }
  body, html { background: white !important; }
  .exos-sidebar, .exos-topbar, .no-print, #exos-tweaks-host, #boot { display: none !important; }
  .app { grid-template-columns: 1fr !important; }
  .exos-page { padding: 0 !important; max-width: 100% !important; }
  .exos-page-head { display: none !important; }
  .exos-report { border: 0 !important; padding: 0 !important; background: white !important; color: black !important; box-shadow: none !important; }
  .exos-report * { color: black !important; border-color: #ccc !important; }
  .exos-report .mono { color: black !important; }
  .exos-report .exos-kicker { color: #555 !important; letter-spacing: 0.14em !important; }
  .exos-report .exos-label { color: #666 !important; }
  .exos-report-stamp { background: white !important; }
  .exos-report-ladder { background: #fafafa !important; page-break-inside: avoid; }
  .exos-report-table { page-break-inside: avoid; }
  .exos-report-h { page-break-after: avoid; }
  .exos-report-disclaimer { background: #fafafa !important; page-break-inside: avoid; }
  a { text-decoration: none !important; }
}
`;
(function(){ if(document.getElementById("exos-reports-styles")) return; const t=document.createElement("style"); t.id="exos-reports-styles"; t.textContent=REPORTS_STYLES; document.head.appendChild(t); })();

window.Reports = Reports;
