/* P&L Reports — monthly + yearly views, by category */

const Reports = ({ goTo, txState, profile }) => {
  const [view, setView] = React.useState("monthly"); // monthly | yearly
  const months = Object.keys(window.CB_DATA.monthly).sort().reverse();
  const [selectedMonth, setSelectedMonth] = React.useState(months[0]);
  const [selectedYear, setSelectedYear] = React.useState(months[0].slice(0, 4));
  const [basis, setBasis] = React.useState("cash"); // cash | accrual
  const [compareMode, setCompareMode] = React.useState("prior"); // prior | yoy | none

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

  // Tax currency — derived from country (Tax Setup), never editable directly.
  // Shows as a secondary line in the P&L table and KPI cards when it differs
  // from the base currency (e.g. base = USD, tax = RON for Romania).
  const taxCur = (() => {
    const code = profile?.countryCode || profile?.country;
    return window.COUNTRIES?.find(c => c.code === code)?.currency || null;
  })();
  const showTax = !!(taxCur && taxCur !== baseCur);
  const fmtTax = (n) => CB.fmtCur(CB.convert(n, "USD", taxCur), taxCur, { cents: false });

  // Basis filter — cash counts only cleared transactions, accrual includes
  // pending (invoiced but not yet received) too. The model is a useful
  // simplification of the GAAP definitions for a prototype.
  const basisFilter = (t) => basis === "accrual" ? true : t.status !== "pending";

  // Normalize a transaction amount to USD so all sums are currency-consistent
  const toUSD = (t) => CB.txToUSD(t);

  // Aggregate by selected period
  const inRange = (date) => {
    if (view === "monthly") return date.startsWith(selectedMonth);
    return date.startsWith(selectedYear);
  };
  const periodTxs = txState.filter(t => inRange(t.date) && basisFilter(t));

  // Build category totals
  const incCats = window.CB_DATA.categories.income.map(c => ({
    ...c,
    value: periodTxs.filter(t => t.category === c.id).reduce((s, t) => s + toUSD(t), 0),
    count: periodTxs.filter(t => t.category === c.id).length,
  }));
  const expCats = window.CB_DATA.categories.expense.map(c => ({
    ...c,
    value: periodTxs.filter(t => t.category === c.id).reduce((s, t) => s + toUSD(t), 0),
    count: periodTxs.filter(t => t.category === c.id).length,
  }));

  const totalIncome = incCats.reduce((s, c) => s + c.value, 0);
  const totalExpense = expCats.reduce((s, c) => s + c.value, 0);
  const net = totalIncome - totalExpense;
  const margin = totalIncome > 0 ? (net / totalIncome) * 100 : 0;

  // Compare period depends on the user's compareMode choice.
  // "prior" = previous month/year. "yoy" = same period one year ago.
  // "none" hides the comparison columns entirely.
  let prevPeriod = null;
  if (compareMode === "prior") {
    prevPeriod = view === "monthly"
      ? months[months.indexOf(selectedMonth) + 1]
      : (parseInt(selectedYear) - 1).toString();
  } else if (compareMode === "yoy") {
    if (view === "monthly") {
      const [y, m] = selectedMonth.split("-");
      prevPeriod = `${parseInt(y) - 1}-${m}`;
    } else {
      prevPeriod = (parseInt(selectedYear) - 1).toString();
    }
  }

  const prevTxs = prevPeriod
    ? txState.filter(t => (view === "monthly" ? t.date.startsWith(prevPeriod) : t.date.startsWith(prevPeriod)) && basisFilter(t))
    : [];
  const prevIncome = prevTxs.filter(t => t.type === "income").reduce((s, t) => s + toUSD(t), 0);
  const prevExpense = prevTxs.filter(t => t.type === "expense").reduce((s, t) => s + toUSD(t), 0);
  const prevNet = prevIncome - prevExpense;

  const compareLabel =
    compareMode === "none" ? "No comparison" :
    !prevPeriod ? "—" :
    view === "monthly" ? CB.monthLabel(prevPeriod, true) : prevPeriod;

  const years = [...new Set(months.map(m => m.slice(0, 4)))];

  const pctOf = (v, total) => total > 0 ? ((v / total) * 100).toFixed(1) : "0.0";

  const periodLabel = view === "monthly" ? CB.monthLabel(selectedMonth) : selectedYear;

  return (
    <div className="page-fade">
      <div className="page-head">
        <div>
          <h1 className="page-title">Profit & Loss</h1>
          <div className="page-sub">{periodLabel} · {basis === "cash" ? "Cash basis" : "Accrual basis"} · {baseCur}</div>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={() => goTo("export")}><Icon name="download" size={14} /> Export PDF</button>
          <button className="btn" onClick={() => goTo("export")}><Icon name="file" size={14} /> Export CSV</button>
        </div>
      </div>

      {/* Period controls */}
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 22 }}>
        <div className="segmented">
          <button className={view === "monthly" ? "on" : ""} onClick={() => setView("monthly")}>Monthly</button>
          <button className={view === "yearly" ? "on" : ""} onClick={() => setView("yearly")}>Yearly</button>
        </div>
        {view === "monthly" ? (
          <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
            <button className="btn btn-ghost btn-sm"
              onClick={() => {
                const idx = months.indexOf(selectedMonth);
                if (idx < months.length - 1) setSelectedMonth(months[idx + 1]);
              }}>
              <Icon name="chevronLeft" size={14} />
            </button>
            <select className="input" style={{ width: "auto" }} value={selectedMonth} onChange={(e) => setSelectedMonth(e.target.value)}>
              {months.map(m => <option key={m} value={m}>{CB.monthLabel(m)}</option>)}
            </select>
            <button className="btn btn-ghost btn-sm"
              onClick={() => {
                const idx = months.indexOf(selectedMonth);
                if (idx > 0) setSelectedMonth(months[idx - 1]);
              }}>
              <Icon name="chevronRight" size={14} />
            </button>
          </div>
        ) : (
          <select className="input" style={{ width: "auto" }} value={selectedYear} onChange={(e) => setSelectedYear(e.target.value)}>
            {years.map(y => <option key={y} value={y}>{y}</option>)}
          </select>
        )}
        <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
          <select className="input" style={{ width: "auto", padding: "6px 28px 6px 10px", fontSize: 12 }}
            value={basis} onChange={(e) => setBasis(e.target.value)}
            title="Cash counts cleared transactions only. Accrual includes pending too.">
            <option value="cash">Cash basis</option>
            <option value="accrual">Accrual basis</option>
          </select>
          <select className="input" style={{ width: "auto", padding: "6px 28px 6px 10px", fontSize: 12 }}
            value={compareMode} onChange={(e) => setCompareMode(e.target.value)}
            title="Choose what to compare this period against">
            <option value="prior">Compare: prior period</option>
            <option value="yoy">Compare: year-over-year</option>
            <option value="none">No comparison</option>
          </select>
        </div>
      </div>

      {/* Summary cards */}
      <div className="kpi-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
        <div className="kpi">
          <div className="kpi-label">Total income</div>
          <div className="bignum-sm" style={{ color: "var(--income-text)" }}>
            {fc(totalIncome, { cents: false })}
          </div>
          {showTax && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 1 }}>{fmtTax(totalIncome)}</div>}
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            {compareMode === "none" || !prevIncome ? "—" : `${((totalIncome - prevIncome) / prevIncome * 100).toFixed(1)}% vs ${compareMode === "yoy" ? "YoY" : "prior"}`}
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Total expenses</div>
          <div className="bignum-sm" style={{ color: "var(--expense)" }}>
            {fc(totalExpense, { cents: false })}
          </div>
          {showTax && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 1 }}>{fmtTax(totalExpense)}</div>}
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            {compareMode === "none" || !prevExpense ? "—" : `${((totalExpense - prevExpense) / prevExpense * 100).toFixed(1)}% vs ${compareMode === "yoy" ? "YoY" : "prior"}`}
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Net profit</div>
          <div className="bignum-sm">{fc(net, { cents: false })}</div>
          {showTax && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 1 }}>{fmtTax(net)}</div>}
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            {compareMode === "none" ? "—" : `vs ${compareMode === "yoy" ? "YoY" : "prior"}: ${fc(prevNet, { cents: false })}`}
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Net margin</div>
          <div className="bignum-sm">{margin.toFixed(1)}%</div>
          <div style={{ fontSize: 11, color: "var(--muted)" }}>
            Est. tax (27%): <b style={{ color: "var(--ink)" }}>{fc(net * 0.27, { cents: false })}</b>
          </div>
        </div>
      </div>

      {/* P&L Table */}
      <div className="card" style={{ marginTop: 16, padding: 0, overflow: "hidden" }}>
        <table className="pnl-tbl">
          <thead>
            <tr>
              <th>Category</th>
              <th>{periodLabel}</th>
              <th>% of revenue</th>
              <th>Txns</th>
              <th>{compareMode === "none" ? "" : `vs ${compareMode === "yoy" ? "YoY" : "prior"}`}</th>
            </tr>
          </thead>
          <tbody>
            <tr className="section-head"><td colSpan="5">Revenue</td></tr>
            {incCats.map(c => {
              const prev = prevTxs.filter(t => t.category === c.id).reduce((s, t) => s + toUSD(t), 0);
              const change = prev > 0 ? ((c.value - prev) / prev) * 100 : (c.value > 0 ? 100 : 0);
              return (
                <tr key={c.id}>
                  <td className="indent">
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                      <span className="cat-swatch" style={{ background: c.color }} />
                      {c.name}
                    </span>
                  </td>
                  <td className="num">
                    {fc(c.value)}
                    {showTax && c.value !== 0 && <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>{fmtTax(c.value)}</div>}
                  </td>
                  <td className="num" style={{ color: "var(--muted)" }}>{pctOf(c.value, totalIncome)}%</td>
                  <td className="num" style={{ color: "var(--muted)" }}>{c.count}</td>
                  <td className="num" style={{ color: change >= 0 ? "var(--income-text)" : "var(--expense)" }}>
                    {prev > 0 ? `${change >= 0 ? "+" : ""}${change.toFixed(1)}%` : "—"}
                  </td>
                </tr>
              );
            })}
            <tr className="subtotal">
              <td>Total revenue</td>
              <td className="num">
                {fc(totalIncome)}
                {showTax && <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>{fmtTax(totalIncome)}</div>}
              </td>
              <td className="num">100.0%</td>
              <td className="num">{incCats.reduce((s, c) => s + c.count, 0)}</td>
              <td className="num" style={{ color: totalIncome >= prevIncome ? "var(--income-text)" : "var(--expense)" }}>
                {prevIncome > 0 ? `${((totalIncome - prevIncome) / prevIncome * 100).toFixed(1)}%` : "—"}
              </td>
            </tr>

            <tr className="section-head"><td colSpan="5">Operating expenses</td></tr>
            {expCats.map(c => {
              const prev = prevTxs.filter(t => t.category === c.id).reduce((s, t) => s + toUSD(t), 0);
              const change = prev > 0 ? ((c.value - prev) / prev) * 100 : (c.value > 0 ? 100 : 0);
              return (
                <tr key={c.id}>
                  <td className="indent">
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                      <span className="cat-swatch" style={{ background: c.color }} />
                      {c.name}
                      <span style={{ fontSize: 10.5, color: "var(--muted)", fontWeight: 400, marginLeft: 4 }}>
                        · {c.tax}
                      </span>
                    </span>
                  </td>
                  <td className="num">
                    {fc(c.value)}
                    {showTax && c.value !== 0 && <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>{fmtTax(c.value)}</div>}
                  </td>
                  <td className="num" style={{ color: "var(--muted)" }}>{pctOf(c.value, totalIncome)}%</td>
                  <td className="num" style={{ color: "var(--muted)" }}>{c.count}</td>
                  <td className="num" style={{ color: change <= 0 ? "var(--income-text)" : "var(--expense)" }}>
                    {prev > 0 ? `${change >= 0 ? "+" : ""}${change.toFixed(1)}%` : "—"}
                  </td>
                </tr>
              );
            })}
            <tr className="subtotal">
              <td>Total expenses</td>
              <td className="num">
                {fc(totalExpense)}
                {showTax && <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>{fmtTax(totalExpense)}</div>}
              </td>
              <td className="num">{pctOf(totalExpense, totalIncome)}%</td>
              <td className="num">{expCats.reduce((s, c) => s + c.count, 0)}</td>
              <td className="num" style={{ color: totalExpense <= prevExpense ? "var(--income-text)" : "var(--expense)" }}>
                {prevExpense > 0 ? `${((totalExpense - prevExpense) / prevExpense * 100).toFixed(1)}%` : "—"}
              </td>
            </tr>

            <tr className="total">
              <td>Net profit</td>
              <td className="num">
                {fc(net)}
                {showTax && <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>{fmtTax(net)}</div>}
              </td>
              <td className="num">{margin.toFixed(1)}%</td>
              <td className="num">{periodTxs.length}</td>
              <td className="num">{prevNet !== 0 ? `${((net - prevNet) / Math.abs(prevNet) * 100).toFixed(1)}%` : "—"}</td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Tax-ready ledger summary */}
      <div className="card" style={{ marginTop: 16, background: "var(--surface-2)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12, background: "var(--primary-soft)",
            display: "grid", placeItems: "center", color: "var(--primary-ink)",
          }}>
            <Icon name="file" size={20} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 19 }}>
              Tax-ready ledger for {periodLabel}
            </div>
            <div style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 2 }}>
              {periodTxs.length} transactions categorized to Schedule C lines · ready to hand to your accountant
            </div>
          </div>
          <button className="btn" onClick={() => goTo("export")}>
            <Icon name="download" size={14} /> Tax bundle (CSV + PDF)
          </button>
        </div>
      </div>
    </div>
  );
};

window.Reports = Reports;
