// Cash Flow & Insights — main page.
// Composes header, stat row, balance chart, flow bars + spending donut,
// transactions ledger, and industry comparison section.

const { useState: useCFState, useMemo: useCFMemo } = React;

const CF_DEFAULTS = /*EDITMODE-BEGIN*/{
  "period": "30d",
  "txFilter": "all",
  "editorialSerif": true,
  "compactTable": false
} /*EDITMODE-END*/;

const CAT_LABELS = {
  deposit: { label: "Card deposit", color: "var(--funding-pool)" },
  ar: { label: "Wholesale AR", color: "var(--growth-galaxy)" },
  payroll: { label: "Payroll", color: "#7790F6" },
  supplies: { label: "Supplies", color: "#A4C3FF" },
  rent: { label: "Rent / utils", color: "#5DD8B6" },
  fees: { label: "Fees", color: "var(--color-warning)" },
  equipment: { label: "Equipment", color: "#C0C8D8" }
};

// CFTopbar — delegates to shared topbar.jsx
function CFTopbar({ business, onTweaks }) {
  return (
    <window.RBITopbar
      business={business}
      activeView="cashflow"
      onTweaks={onTweaks}
    />
  );
}

// ── Page header with period selector ─────────────────────────────────────
function CFHeader({ business, period, onPeriod, serif, copy }) {
  return (
    <div className="cf-header">
      <div>
        <p className="cf-eb">Cash flow &amp; insights · {business.bank}</p>
        <h1 className={"cf-title" + (serif ? " serif" : "")}>
          What your money <span className="accent">{copy.pageTitleAccent}</span> this month.
        </h1>
        <p className="cf-sub">{copy.pageSub}</p>
      </div>
      <div className="cf-period">
        {[
          { v: "30d", l: "30 days" },
          { v: "90d", l: "90 days" },
          { v: "ytd", l: "YTD" }].
          map((o) =>
            <button
              key={o.v}
              className={"cf-period-btn" + (period === o.v ? " active" : "")}
              onClick={() => onPeriod(o.v)}>
              {o.l}</button>
          )}
      </div>
    </div>);

}

// ── Stat card row ────────────────────────────────────────────────────────
function StatCard({ label, value, delta, tone, sparkValues, sparkColor, sparkFill }) {
  return (
    <div className="cf-stat">
      <div className="cf-stat-lab">{label}</div>
      <div className="cf-stat-row">
        <div className="cf-stat-val">{value}</div>
        <CFSparkline values={sparkValues} color={sparkColor} fill={sparkFill} />
      </div>
      <div className={"cf-stat-delta cf-tone-" + tone}>{delta}</div>
    </div>);

}

function StatRow({ profile, cf }) {
  const b = cf.balance90;
  const last30 = b.slice(-30);
  const weeklyIn = cf.weekly.map((w) => w.inflow);
  const weeklyOut = cf.weekly.map((w) => w.outflow);
  const netSpark = cf.weekly.map((w) => w.net);
  const bufferSpark = last30.map((v) => Math.max(0, Math.round(v / 2640)));

  const sparkMap = {
    "Revenue · 30d": { values: weeklyIn, color: "var(--funding-pool)", fill: "rgba(4,196,158,0.12)" },
    "Spending · 30d": { values: weeklyOut, color: "var(--color-warning)", fill: "rgba(224,123,57,0.14)" },
    "Cash buffer": { values: bufferSpark, color: "var(--color-error)" },
    "Net margin · 30d": { values: netSpark, color: "var(--growth-galaxy)" },
  };

  return (
    <div className="cf-stat-row-grid">
      {profile.cashflow.metrics.map((m) => {
        const sp = sparkMap[m.label] || { values: [], color: "var(--fg-3)" };
        return (
          <StatCard
            key={m.label}
            label={m.label}
            value={m.value}
            delta={m.delta}
            tone={m.tone === "good" ? "good" : m.tone === "warn" ? "warn" : "neutral"}
            sparkValues={sp.values}
            sparkColor={sp.color}
            sparkFill={sp.fill}
          />
        );
      })}
    </div>
  );
}

// ── Section card wrapper ─────────────────────────────────────────────────
function SectionCard({ eyebrow, title, subtitle, children, action, accent }) {
  return (
    <section className="cf-section">
      <div className="cf-section-hd">
        <div>
          {eyebrow ? <p className="cf-section-eb" style={accent ? { color: accent } : null}>{eyebrow}</p> : null}
          <h2 className="cf-section-title">{title}</h2>
          {subtitle ? <p className="cf-section-sub">{subtitle}</p> : null}
        </div>
        {action ? <div className="cf-section-action">{action}</div> : null}
      </div>
      <div className="cf-section-body">{children}</div>
    </section>);

}

// ── Transactions table ───────────────────────────────────────────────────
function TransactionsTable({ rows, filter, onFilter, compact }) {
  const visible = useCFMemo(
    () => filter === "all" ? rows : rows.filter((r) => r.cat === filter || filter === "flagged" && r.flag),
    [rows, filter]
  );

  const filters = [
    { v: "all", l: "All", n: rows.length },
    { v: "flagged", l: "Flagged", n: rows.filter((r) => r.flag).length },
    { v: "deposit", l: "Card deposits", n: rows.filter((r) => r.cat === "deposit").length },
    { v: "ar", l: "Wholesale AR", n: rows.filter((r) => r.cat === "ar").length },
    { v: "supplies", l: "Supplies", n: rows.filter((r) => r.cat === "supplies").length },
    { v: "fees", l: "Fees", n: rows.filter((r) => r.cat === "fees").length },
    { v: "payroll", l: "Payroll", n: rows.filter((r) => r.cat === "payroll").length },
    { v: "rent", l: "Rent / utils", n: rows.filter((r) => r.cat === "rent").length },
    { v: "equipment", l: "Equipment", n: rows.filter((r) => r.cat === "equipment").length }];


  return (
    <div>
      <div className="cf-tx-filters">
        {filters.map((f) =>
          <button
            key={f.v}
            className={"cf-chip" + (filter === f.v ? " active" : "")}
            onClick={() => onFilter(f.v)}>

            {f.l} <span className="n">{f.n}</span>
          </button>
        )}
      </div>
      <div className={"cf-tx-table" + (compact ? " compact" : "")}>
        <div className="cf-tx-hd">
          <span>Date</span>
          <span>Memo</span>
          <span>Category</span>
          <span className="right">Amount</span>
          <span className="right">Balance</span>
        </div>
        {visible.map((t, i) => {
          const cat = CAT_LABELS[t.cat] || { label: t.cat, color: "var(--fg-3)" };
          const isOut = t.amount < 0;
          return (
            <div key={i} className={"cf-tx-row" + (t.flag ? " flagged" : "")}>
              <span className="cf-tx-date">{t.date}</span>
              <span className="cf-tx-memo">
                <span>{t.memo}</span>
                {t.flag ? <span className="cf-tx-flag">{t.flag}</span> : null}
              </span>
              <span className="cf-tx-cat">
                <span className="dot" style={{ background: cat.color }} />
                {cat.label}
              </span>
              <span className={"cf-tx-amt right " + (isOut ? "out" : "in")}>
                {cfFmtAmt(t.amount)}
              </span>
              <span className="cf-tx-bal right">{cfFmtUSD(t.running)}</span>
            </div>);

        })}
        {visible.length === 0 ?
          <div className="cf-tx-empty">No transactions match this filter.</div> :
          null}
      </div>
    </div>);

}

// ── Main app ─────────────────────────────────────────────────────────────
function CFApp() {
  const [t, setTweak] = useTweaks(CF_DEFAULTS);
  const scenario = window.useScenario();
  const profile = window.RBI_PROFILES[scenario] || window.RBI_PROFILES.declined;
  const cf = window.RBI_CASHFLOW[scenario] || window.RBI_CASHFLOW.declined;
  const copy = cf.copy;

  return (
    <div className="rbi-app">
      <CFTopbar
        business={profile.business}
        onTweaks={() => window.postMessage({ type: "__activate_edit_mode" }, "*")} />

      <div className="rbi-body cf-body">
        <CFHeader
          business={profile.business}
          period={t.period}
          onPeriod={(v) => setTweak("period", v)}
          serif={t.editorialSerif}
          copy={copy} />


        <StatRow profile={profile} cf={cf} />

        <SectionCard
          eyebrow="Daily balance · 90 days"
          title={copy.balanceTitle}
          subtitle={"Window: " + cf.windowLabel + " · pulled from " + cf.bank + " via Plaid."}>

          <BalanceChart balance={cf.balance90} overdraftDays={cf.overdraftDays} todayLabel="Today" />
        </SectionCard>

        <div className="cf-row-2">
          <SectionCard
            eyebrow="Inflow vs outflow · 12 weeks"
            title={copy.flowTitle}
            subtitle={copy.flowSub}
            accent="var(--funding-pool)">

            <FlowBars weekly={cf.weekly} />
          </SectionCard>

          <SectionCard
            eyebrow="Where the money went · 30d"
            title={copy.spendTitle}
            subtitle={copy.spendSub}
            accent="var(--growth-galaxy)">

            <SpendingDonut spending={cf.spending30d} />
          </SectionCard>
        </div>

        <SectionCard
          eyebrow="Transactions · last 30 days"
          title={copy.txTitle}
          subtitle={copy.txSub}>

          <TransactionsTable
            rows={cf.transactions}
            filter={t.txFilter}
            onFilter={(v) => setTweak("txFilter", v)}
            compact={t.compactTable} />

        </SectionCard>

        <div className="cf-crosslink">
          <div>
            <p className="cf-crosslink-eb">Where Atlas stands in its cohort →</p>
            <p className="cf-crosslink-body">Compare these numbers to 247 NYC commercial bakeries your size — percentile rings, full distributions, comparative callouts.</p>
          </div>
          <a className="cf-crosslink-cta" href="rbi_industry_insights.html" onClick={(e) => { e.preventDefault(); window.RBI_NAV("insights"); }}>
            Open industry insights
            <span className="arrow">→</span>
          </a>
        </div>

        <div className="rbi-footer">
          <div className="rbi-footer-links">
            <span className="plaid-status">
              <span className="dot" /> Plaid connected · {profile.business.bank} · refreshed 8m ago
            </span>
            <div>
              <a href="index.html" onClick={(e) => { e.preventDefault(); window.RBI_NAV("home"); }}>← Back to overview</a>
              <a>Export this report (PDF)</a>
              <a>Your data — what we see, what we don't</a>
            </div>
          </div>
        </div>
      </div>

      <TweaksPanel>
        <TweakSection label="Scenario" />
        <TweakSelect
          label="Story shown"
          value={scenario}
          options={[
            { value: "declined", label: "Declined · tight runway" },
            { value: "improving", label: "Healthy & improving" },
            { value: "reeligible", label: "Re-eligible for Revenued" },
          ]}
          onChange={(v) => window.RBI_STATE.set(v)}
        />
        <TweakSection label="Period" />
        <TweakSelect
          label="Time window"
          value={t.period}
          options={[
            { value: "30d", label: "30 days" },
            { value: "90d", label: "90 days (default views)" },
            { value: "ytd", label: "Year to date" }]
          }
          onChange={(v) => setTweak("period", v)} />

        <TweakSection label="Transactions" />
        <TweakSelect
          label="Filter"
          value={t.txFilter}
          options={[
            { value: "all", label: "All transactions" },
            { value: "flagged", label: "Flagged only" },
            { value: "deposit", label: "Card deposits" },
            { value: "ar", label: "Wholesale AR" },
            { value: "supplies", label: "Supplies" },
            { value: "fees", label: "Fees" },
            { value: "payroll", label: "Payroll" },
            { value: "rent", label: "Rent / utilities" },
            { value: "equipment", label: "Equipment" }]
          }
          onChange={(v) => setTweak("txFilter", v)} />

        <TweakToggle label="Compact table" value={t.compactTable} onChange={(v) => setTweak("compactTable", v)} />
        <TweakSection label="Type" />
        <TweakToggle label="Editorial serif accents" value={t.editorialSerif} onChange={(v) => setTweak("editorialSerif", v)} />
      </TweaksPanel>
    </div>);

}

window.CFApp = CFApp;