/* Forecast — cash flow projection + tax reserve */

const Forecast = ({ goTo, txState, profile }) => {
  const [horizon, setHorizon] = React.useState(6); // months
  const [taxRate, setTaxRate] = React.useState(0.27);

  const baseCur = profile?.baseCurrency || window.CB_DATA?.profile?.baseCurrency || "USD";
  const fmtFC = (n, opts) => CB.fmtCur(CB.convert(n, "USD", baseCur), baseCur, opts || {});

  const fc = React.useMemo(
    () => window.CB_INTEL.forecast(txState, { months: horizon, taxRate }),
    [txState, horizon, taxRate]
  );

  // For runway: assume starting cash from connected accounts
  const startingCash = window.CB_DATA.accounts
    .filter(a => a.balance != null && a.balance > 0)
    .reduce((s, a) => s + a.balance, 0);

  // Running cash projection
  let runningCash = startingCash;
  const cashLine = fc.future.map(m => {
    runningCash += m.net;
    return { month: m.month, cash: runningCash, net: m.net };
  });

  // Detect if cash dips below tax reserve at any point
  let cashShortMonth = null;
  let runningTaxReserve = 0;
  for (let i = 0; i < fc.future.length; i++) {
    runningTaxReserve += fc.future[i].income * taxRate;
    if (cashLine[i].cash < runningTaxReserve && !cashShortMonth) {
      cashShortMonth = fc.future[i].month;
    }
  }

  const endCash = cashLine[cashLine.length - 1]?.cash || startingCash;
  const endTaxReserve = fc.future.reduce((s, m) => s + m.income * taxRate, 0);
  const endAfterTax = endCash - endTaxReserve;

  return (
    <div className="page-fade">
      <div className="page-head">
        <div>
          <h1 className="page-title">Forecast</h1>
          <div className="page-sub">
            {horizon}-month cash projection · based on trailing 6 months of activity
          </div>
        </div>
        <div className="page-actions">
          <div className="segmented">
            <button className={horizon === 3 ? "on" : ""} onClick={() => setHorizon(3)}>3 mo</button>
            <button className={horizon === 6 ? "on" : ""} onClick={() => setHorizon(6)}>6 mo</button>
            <button className={horizon === 12 ? "on" : ""} onClick={() => setHorizon(12)}>12 mo</button>
          </div>
        </div>
      </div>

      {/* KPI strip */}
      <div className="kpi-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
        <div className="kpi">
          <div className="kpi-label">Avg monthly net</div>
          <div className="bignum-sm">{fmtFC(fc.avgNet, { cents: false })}</div>
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            {fmtFC(fc.avgIncome, { cents: false })} in · {fmtFC(fc.avgExpense, { cents: false })} out
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Projected net · {horizon}mo</div>
          <div className="bignum-sm" style={{ color: "var(--income-text)" }}>
            {fmtFC(fc.avgNet * horizon, { cents: false })}
          </div>
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            range ±{fmtFC((fc.incomeStd + fc.expenseStd) * horizon, { cents: false })}
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Tax reserve needed</div>
          <div className="bignum-sm" style={{ color: "var(--expense)" }}>
            {fmtFC(endTaxReserve, { cents: false })}
          </div>
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            {(taxRate * 100).toFixed(0)}% of projected income
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Cash after tax · end of period</div>
          <div className="bignum-sm" style={{ color: endAfterTax > 0 ? "var(--ink)" : "var(--expense)" }}>
            {fmtFC(endAfterTax, { cents: false })}
          </div>
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            from {fmtFC(startingCash, { cents: false })} today
          </div>
        </div>
      </div>

      {/* Forecast chart */}
      <div className="card" style={{ marginTop: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start" }}>
          <div>
            <div className="kpi-label">Cash flow projection</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, marginTop: 4 }}>
              Past 6 months + next {horizon}
            </div>
          </div>
          <div style={{ display: "flex", gap: 12, fontSize: 12, color: "var(--ink-soft)" }}>
            <span><span style={{ display: "inline-block", width: 10, height: 10, background: "var(--income)", borderRadius: 2, marginRight: 4 }} />Income</span>
            <span><span style={{ display: "inline-block", width: 10, height: 10, background: "var(--expense)", opacity: 0.75, borderRadius: 2, marginRight: 4 }} />Expense</span>
            <span><span style={{ display: "inline-block", width: 12, height: 2, background: "var(--primary)", marginRight: 4, verticalAlign: "middle" }} />Projected net</span>
          </div>
        </div>
        <div style={{ height: 320, marginTop: 14 }}>
          <ForecastChart history={fc.history} future={fc.future} cashLine={cashLine} />
        </div>
      </div>

      {/* Tax reserve breakdown */}
      <div className="dash-grid" style={{ marginTop: 16 }}>
        <div className="card">
          <div className="kpi-label">Tax reserve schedule</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 22, margin: "4px 0 14px" }}>
            What to set aside each month
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Month</th>
                <th>Projected income</th>
                <th>Reserve ({(taxRate * 100).toFixed(0)}%)</th>
                <th>Cumulative</th>
              </tr>
            </thead>
            <tbody>
              {fc.future.slice(0, 6).map(m => (
                <tr key={m.month}>
                  <td>{CB.monthLabel(m.month, true)}</td>
                  <td className="num">{fmtFC(m.income, { cents: false })}</td>
                  <td className="num" style={{ color: "var(--expense)" }}>{fmtFC(m.income * taxRate, { cents: false })}</td>
                  <td className="num"><b>{fmtFC(m.taxReserve, { cents: false })}</b></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card">
          <div className="kpi-label">Confidence</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 22, margin: "4px 0 14px" }}>
            How much we trust this
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ padding: 12, background: "var(--surface-2)", borderRadius: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
                <span style={{ color: "var(--muted)" }}>Income volatility</span>
                <span style={{ fontFamily: "var(--font-mono)" }}>±{((fc.incomeStd / fc.avgIncome) * 100).toFixed(0)}%</span>
              </div>
              <div style={{ height: 4, background: "var(--bg-deep)", borderRadius: 2 }}>
                <div style={{ height: "100%", background: "var(--income)", borderRadius: 2, width: Math.min(100, (fc.incomeStd / fc.avgIncome) * 200) + "%" }} />
              </div>
            </div>
            <div style={{ padding: 12, background: "var(--surface-2)", borderRadius: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
                <span style={{ color: "var(--muted)" }}>Expense volatility</span>
                <span style={{ fontFamily: "var(--font-mono)" }}>±{((fc.expenseStd / fc.avgExpense) * 100).toFixed(0)}%</span>
              </div>
              <div style={{ height: 4, background: "var(--bg-deep)", borderRadius: 2 }}>
                <div style={{ height: "100%", background: "var(--expense)", borderRadius: 2, width: Math.min(100, (fc.expenseStd / fc.avgExpense) * 200) + "%" }} />
              </div>
            </div>
          </div>
          <div style={{ marginTop: 14, fontSize: 12.5, color: "var(--ink-soft)" }}>
            {cashShortMonth ? (
              <div style={{ padding: 12, background: "var(--expense-soft)", color: "var(--expense-text-strong)", borderRadius: 10 }}>
                <Icon name="bell" size={13} /> &nbsp;Cash may dip below your tax reserve by <b>{CB.monthLabel(cashShortMonth, true)}</b>.
                Consider trimming expenses or chasing outstanding invoices.
              </div>
            ) : (
              <div style={{ padding: 12, background: "var(--income-soft)", color: "var(--income-text-strong)", borderRadius: 10 }}>
                <Icon name="check" size={13} /> &nbsp;On track — projected cash covers tax obligations across this period.
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="card-quiet" style={{ marginTop: 16, padding: 14, display: "flex", gap: 12, alignItems: "start" }}>
        <Icon name="sparkles" size={16} />
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)" }}>
          <b style={{ color: "var(--ink)" }}>How this is computed:</b> we average your trailing 6 full months of
          income and expenses to project a flat baseline, then compute a tax reserve at your blended rate ({(taxRate * 100).toFixed(0)}%).
          The confidence range uses standard deviation across your monthly history — wider bands mean less predictable income.
        </div>
      </div>
    </div>
  );
};

// SVG chart: bars for past + future income/expense, line for projected cumulative cash
const ForecastChart = ({ history, future, cashLine }) => {
  const all = [...history, ...future];
  const w = 880, h = 320, padL = 56, padR = 56, padT = 16, padB = 36;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const maxBar = Math.max(...all.map(m => Math.max(m.income, m.expense, 1))) * 1.15;
  const maxCash = Math.max(...cashLine.map(p => p.cash), 1) * 1.1;

  const barW = innerW / all.length;
  const groupW = barW * 0.62;
  const halfW = groupW / 2;

  const todayIdx = history.length - 0.5; // line between history & future

  // y-grid for bars
  const ticks = 4;
  const tickVals = [];
  for (let i = 0; i <= ticks; i++) tickVals.push((maxBar / ticks) * i);

  // Cash line points
  const cashPts = cashLine.map((p, i) => {
    const x = padL + (history.length + i + 0.5) * barW;
    const y = padT + innerH - (p.cash / maxCash) * innerH;
    return [x, y];
  });
  const cashPath = cashPts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ");

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "100%" }}>
      {/* Future region shading */}
      <rect x={padL + todayIdx * barW + barW / 2} y={padT}
            width={padL + innerW - (padL + todayIdx * barW + barW / 2)} height={innerH}
            fill="var(--surface-2)" opacity="0.5" />

      {/* Gridlines */}
      {tickVals.map((v, i) => {
        const y = padT + innerH - (v / maxBar) * innerH;
        return (
          <g key={i}>
            <line x1={padL} y1={y} x2={w - padR} y2={y} stroke="var(--hairline)" strokeDasharray={i === 0 ? "" : "2 4"} />
            <text x={padL - 8} y={y + 4} textAnchor="end" fontSize="10" fill="var(--muted)" fontFamily="var(--font-mono)">
              {v >= 1000 ? "$" + (v / 1000).toFixed(0) + "k" : "$" + v.toFixed(0)}
            </text>
          </g>
        );
      })}

      {/* Today divider */}
      <line x1={padL + (todayIdx + 0.5) * barW} y1={padT} x2={padL + (todayIdx + 0.5) * barW} y2={padT + innerH}
            stroke="var(--ink-soft)" strokeDasharray="3 4" opacity="0.6" />
      <text x={padL + (todayIdx + 0.5) * barW} y={padT - 4} textAnchor="middle"
            fontSize="9" fill="var(--ink-soft)" textTransform="uppercase" letterSpacing="0.06em">TODAY</text>

      {/* Bars */}
      {all.map((m, i) => {
        const x = padL + (i + 0.5) * barW;
        const incH = (m.income / maxBar) * innerH;
        const expH = (m.expense / maxBar) * innerH;
        const future = m.projected;
        return (
          <g key={m.month}>
            <rect x={x - halfW} y={padT + innerH - incH} width={halfW - 2} height={incH}
                  fill="var(--income)" opacity={future ? 0.5 : 1} rx="3" />
            <rect x={x + 2} y={padT + innerH - expH} width={halfW - 2} height={expH}
                  fill="var(--expense)" opacity={future ? 0.4 : 0.75} rx="3" />
            <text x={x} y={h - 12} textAnchor="middle" fontSize="10" fill="var(--muted)">
              {CB.monthLabel(m.month, true).split(" ")[0]}
            </text>
          </g>
        );
      })}

      {/* Cash line — secondary axis on the right */}
      <path d={cashPath} stroke="var(--primary)" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      {cashPts.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r="3.5" fill="var(--primary)" stroke="var(--surface)" strokeWidth="1.5" />
      ))}

      {/* Right-axis label */}
      {cashPts[cashPts.length - 1] && (
        <text x={w - padR + 6} y={cashPts[cashPts.length - 1][1] + 4} fontSize="10"
              fill="var(--primary)" fontFamily="var(--font-mono)" fontWeight="600">
          {CB.fmt(cashLine[cashLine.length - 1].cash, { cents: false })}
        </text>
      )}
    </svg>
  );
};

window.Forecast = Forecast;
