// §3.9 Rebate Monitor — Contracts, Tiers, Accrual, Settlement, Dashboard

function RebateMonitor({ user, perms }) {
  const [tab, setTab] = useState("dashboard");
  const [openRebate, setOpenRebate] = useState(null);
  const [openSettlement, setOpenSettlement] = useState(false);

  const tabs = [
    { id: "dashboard", label: "Dashboard" },
    { id: "contracts", label: "Rebate Contracts", count: REBATES.length },
    { id: "accrual", label: "Monthly Accrual" },
    { id: "settlement", label: "Settlements", count: SETTLEMENTS.filter(s => s.status !== "Settled").length },
  ];

  return (
    <div>
      <PageHeader
        title="Rebate Monitor"
        sub="Tracks the lifecycle of terminal rebate clauses · prevents revenue leakage"
        right={
          <>
            <button className="btn"><Icon name="download" size={14} /> Export accruals</button>
            {(perms.admin || user.role === "procurement") && (
              <button className="btn primary"><Icon name="plus" size={14} /> New rebate contract</button>
            )}
          </>
        }
      />
      <RebateKPIs />
      <Tabs tabs={tabs} current={tab} onChange={setTab} />
      {tab === "dashboard" && <RebateDashboard onOpen={setOpenRebate} />}
      {tab === "contracts" && <RebateContracts onOpen={setOpenRebate} />}
      {tab === "accrual" && <AccrualView />}
      {tab === "settlement" && <SettlementTracker onNew={() => setOpenSettlement(true)} perms={perms} />}

      {openRebate && <RebateDetail rebate={openRebate} onClose={() => setOpenRebate(null)} perms={perms} />}
      {openSettlement && <NewSettlement onClose={() => setOpenSettlement(false)} />}
    </div>
  );
}

function RebateKPIs() {
  const totalUSD = REBATES.reduce((s, r) => s + r.accruedYTD, 0);
  const atRisk = REBATES.filter(r => r.atRisk || r.currentTier === 0).length;
  const eoyForecast = totalUSD * 2.4;
  const unsettled = SETTLEMENTS.filter(s => s.status !== "Settled").reduce((acc, s) => acc + (s.accrued / (ROE[s.ccy] || 1)), 0);
  return (
    <div className="grid-4" style={{ marginBottom: 18 }}>
      <KPI label="YTD Accrual (USD)" value={fmt.usd(totalUSD)} sub={`${REBATES.length} active contracts`} delta="↑ +18% vs prior year" deltaDir="up" />
      <KPI label="EoY Forecast" value={fmt.usd(eoyForecast)} sub="based on current pace" />
      <KPI label="At-Risk Rebates" value={atRisk} sub={atRisk > 0 ? "trailing tier targets" : "all on pace"} deltaDir={atRisk > 0 ? "down" : "up"} />
      <KPI label="Unsettled" value={fmt.usd(unsettled)} sub={`${SETTLEMENTS.filter(s => s.status === "Overdue").length} overdue`} />
    </div>
  );
}

// ============== REBATE DASHBOARD ==============
function RebateDashboard({ onOpen }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
      <Card title="Tier Progress Tracker" sub="YTD volume vs next tier threshold · $ uplift on tier crossing"
        right={<span className="tiny muted">Updated 2 hours ago</span>}>
        <div style={{ padding: "4px 0" }}>
          {REBATES.filter(r => r.currentTier >= 0).map((r, i) => {
            const ytd = YTD_VOLUME[r.terminal] || 18000;
            const nextTier = r.tiers[r.currentTier];
            const prevTier = r.tiers[r.currentTier - 1];
            const min = prevTier?.max ? prevTier.max + 1 : 0;
            const max = nextTier?.max || ytd * 1.4;
            const pct = ((ytd - min) / (max - min)) * 100;
            const uplift = r.accruedYTD * 0.4;
            return (
              <div key={r.id} style={{ padding: "12px 16px", borderTop: i > 0 ? "1px solid var(--line)" : 0, cursor: "pointer" }} onClick={() => onOpen(r)}>
                <div className="row gap-8" style={{ marginBottom: 6 }}>
                  <div className="bold tiny">{TERMINAL_BY_CODE[r.terminal]?.name}</div>
                  <div className="tiny muted mono">{r.id}</div>
                  <div className="grow" />
                  <Pill className="plain" style={{ fontSize: 10 }}>{nextTier?.name || "Maxed"} @ {nextTier?.rate || "—"}%</Pill>
                </div>
                <div style={{ position: "relative", height: 8, background: "var(--paper-2)", borderRadius: 4, overflow: "hidden" }}>
                  <div style={{ width: `${Math.min(100, Math.max(0, pct))}%`, height: "100%", background: pct > 70 ? "var(--green)" : pct > 30 ? "var(--teal)" : "var(--amber)" }} />
                </div>
                <div className="row" style={{ marginTop: 4, justifyContent: "space-between" }}>
                  <span className="tiny mono muted">{fmt.num(ytd, 0)} TEU YTD</span>
                  <span className="tiny mono muted">→ {fmt.num(max, 0)} TEU (next tier)</span>
                </div>
                <div className="tiny muted" style={{ marginTop: 4 }}>
                  Reach next tier: <b style={{ color: "var(--green)" }}>+{fmt.usd(uplift)}</b> uplift
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Card title="At-Risk Rebates" sub="Trailing pace · $ impact if Tier 2+ missed">
          <div style={{ padding: 14 }}>
            {REBATES.filter(r => r.atRisk || r.currentTier === 0).map((r, i) => (
              <div key={r.id} style={{ padding: "10px 0", borderTop: i > 0 ? "1px solid var(--line)" : 0, display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 6, height: 30, borderRadius: 2, background: "var(--amber)" }} />
                <div style={{ flex: 1 }}>
                  <div className="bold tiny">{TERMINAL_BY_CODE[r.terminal]?.name}</div>
                  <div className="tiny muted mono">{r.id} · {r.type}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="mono tiny bold" style={{ color: "var(--amber)" }}>-{fmt.usd(54200)}</div>
                  <div className="tiny muted">if missed</div>
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card title="Forecast to Year-End" right={<button className="btn ghost tiny">Adjust assumptions</button>}>
          <div style={{ padding: 18 }}>
            <div className="row gap-12" style={{ marginBottom: 12 }}>
              <div>
                <div className="tiny mono muted" style={{ textTransform: "uppercase" }}>YTD actual</div>
                <div className="serif" style={{ fontSize: 20, fontWeight: 500 }}>{fmt.usd(403800)}</div>
              </div>
              <div>
                <div className="tiny mono muted" style={{ textTransform: "uppercase" }}>EoY projection</div>
                <div className="serif" style={{ fontSize: 20, fontWeight: 500, color: "var(--green)" }}>{fmt.usd(969100)}</div>
              </div>
              <div>
                <div className="tiny mono muted" style={{ textTransform: "uppercase" }}>vs Plan</div>
                <div className="serif" style={{ fontSize: 20, fontWeight: 500, color: "var(--green)" }}>+12%</div>
              </div>
            </div>

            {/* mini chart */}
            <Sparkline data={[78000, 92000, 84000, 88000, 96000, 102000, 108000, 112000, 118000, 122000, 124000, 128000]} w={400} h={50} color="var(--teal)" fill strokeWidth={2} />

            <div className="tiny muted" style={{ marginTop: 8 }}>
              Pace assumption: <b>+0.5% MoM</b> · Tier 3 reached at Shanghai by Sep 2025 (forecast)
            </div>
          </div>
        </Card>
      </div>

      <div className="span-2" style={{ gridColumn: "span 2" }}>
        <Card title="Rebate Portfolio Summary" sub="Active contracts by region · YTD accrual">
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>Region</th>
                  <th>Contracts</th>
                  <th className="num">YTD Accrual (USD)</th>
                  <th className="num">Prior Year YTD</th>
                  <th className="num">% Change</th>
                  <th>Pace</th>
                </tr>
              </thead>
              <tbody>
                {REGIONS.map(r => {
                  const contracts = REBATES.filter(rb => TERMINAL_BY_CODE[rb.terminal]?.region === r);
                  const accrued = contracts.reduce((s, c) => s + c.accruedYTD, 0);
                  const prior = accrued * 0.85;
                  const pct = ((accrued - prior) / prior) * 100;
                  return (
                    <tr key={r}>
                      <td className="bold">{r}</td>
                      <td className="mono">{contracts.length}</td>
                      <td className="num mono bold">{fmt.usd(accrued)}</td>
                      <td className="num mono muted">{fmt.usd(prior)}</td>
                      <td className="num mono" style={{ color: pct > 0 ? "var(--green)" : "var(--red)" }}>
                        {pct > 0 ? "↑" : "↓"} {Math.abs(pct).toFixed(1)}%
                      </td>
                      <td><Sparkline data={[60, 68, 72, 78, 82, 88, 96, 102, 108, 114]} w={80} h={20} color="var(--teal)" /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      </div>
    </div>
  );
}

// ============== CONTRACTS LIST ==============
function RebateContracts({ onOpen }) {
  return (
    <div>
      <div className="filterbar">
        <FilterChip keyLabel="Status" value="Active" set />
        <FilterChip keyLabel="Type" value="" />
        <FilterChip keyLabel="Region" value="" />
        <div className="grow" />
        <div className="search"><Icon name="search" size={14} /><input placeholder="Contract ref, terminal…" /></div>
      </div>
      <Card>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Terminal</th>
                <th>Contract Ref</th>
                <th>Type</th>
                <th>Scope</th>
                <th>Period</th>
                <th>Settlement</th>
                <th>Current Tier</th>
                <th className="num">YTD Accrual</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {REBATES.map(r => (
                <tr key={r.id} onClick={() => onOpen(r)} style={{ cursor: "pointer" }}>
                  <td className="mono tiny bold">{r.id}</td>
                  <td>
                    <div className="bold tiny">{TERMINAL_BY_CODE[r.terminal]?.name}</div>
                    <div className="tiny muted mono">{r.terminal}</div>
                  </td>
                  <td className="mono tiny muted">{r.contractRef}</td>
                  <td><Pill className="plain">{r.type}</Pill></td>
                  <td className="tiny">{r.scope}</td>
                  <td className="tiny">{r.period}</td>
                  <td className="tiny">{r.settlement}</td>
                  <td>
                    <span className="mono tiny bold">{r.tiers[r.currentTier]?.name.replace(" (Base)", "").replace(" (Elite)", "") || "—"}</span>
                    <div className="tiny muted">@ {r.tiers[r.currentTier]?.rate}%</div>
                  </td>
                  <td className="num mono">
                    {fmt.usd(r.accruedYTD)}
                    <div className="tiny muted">{fmt.num(r.accruedYTDLocal)} {r.currency}</div>
                  </td>
                  <td><Pill status={r.atRisk ? "Pending" : r.status} /></td>
                  <td><button className="icon-btn" style={{ width: 24, height: 24 }} onClick={e=>e.stopPropagation()}><Icon name="dots" size={12} /></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

// ============== ACCRUAL VIEW ==============
function AccrualView() {
  // Build a monthly accrual matrix per rebate
  const months = ["2025-01", "2025-02", "2025-03", "2025-04", "2025-05"];
  return (
    <div>
      <div className="filterbar">
        <FilterChip keyLabel="Year" value="2025" set />
        <FilterChip keyLabel="Region" value="" />
        <div className="grow" />
        <button className="btn"><Icon name="refresh" size={14} /> Recalculate all</button>
        <button className="btn"><Icon name="download" size={14} /> Export to Excel</button>
      </div>

      <Card title="Period Accrual Table" sub="Auto-calculated after each monthly volume import · USD">
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>Rebate</th>
                <th>Terminal</th>
                {months.map(m => <th key={m} className="num">{m}</th>)}
                <th className="num">YTD Total</th>
                <th>Notes</th>
              </tr>
            </thead>
            <tbody>
              {REBATES.map((r, ri) => {
                const monthly = months.map((m, i) => Math.round(r.accruedYTD / months.length * (0.7 + (ri + i) % 8 / 10)));
                const total = monthly.reduce((a, b) => a + b, 0);
                const hasUpgrade = ri === 0;
                return (
                  <tr key={r.id}>
                    <td>
                      <div className="bold tiny mono">{r.id}</div>
                      <div className="tiny muted">{r.type}</div>
                    </td>
                    <td className="tiny">{TERMINAL_BY_CODE[r.terminal]?.name}</td>
                    {monthly.map((v, i) => (
                      <td key={i} className="num mono tiny" style={{ color: i === 2 && hasUpgrade ? "var(--teal)" : null, fontWeight: i === 2 && hasUpgrade ? 600 : 400 }}>
                        {fmt.usd(v)}
                        {i === 2 && hasUpgrade && <div className="tiny" style={{ color: "var(--teal)", fontSize: 9 }}>↑ Tier upgrade adj.</div>}
                      </td>
                    ))}
                    <td className="num mono bold">{fmt.usd(total)}</td>
                    <td className="tiny muted">{hasUpgrade ? "Mar: Tier 3 crossed, retroactive uplift" : ""}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      <div style={{ marginTop: 14, padding: 12, background: "var(--teal-soft)", border: "1px solid #c8e3ea", borderRadius: 6, display: "flex", gap: 10 }}>
        <Icon name="bolt" size={16} stroke="var(--teal)" />
        <div className="tiny">
          <b style={{ color: "var(--teal)" }}>Auto-recalculation.</b> Accruals refresh automatically after every Volume Tracker import.
          For retroactive tiers, when a threshold is crossed mid-period, the system writes a <b>Tier Upgrade Adjustment</b> for the prior-period delta and logs it in the audit trail.
        </div>
      </div>
    </div>
  );
}

// ============== SETTLEMENT ==============
function SettlementTracker({ onNew, perms }) {
  return (
    <div>
      <div className="filterbar">
        <FilterChip keyLabel="Status" value="" />
        <FilterChip keyLabel="Year" value="2025" set />
        <div className="grow" />
        {(perms.admin || true) && <button className="btn primary" onClick={onNew}><Icon name="plus" size={14} /> Log settlement</button>}
        <button className="btn"><Icon name="download" size={14} /> Export for ERP</button>
      </div>

      <Card title="Settlement records" sub="Variance > 5% flagged for review · overdue highlighted in red">
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Rebate</th>
                <th>Period</th>
                <th className="num">Calculated</th>
                <th className="num">Claimed</th>
                <th className="num">Variance</th>
                <th>Claimed Date</th>
                <th>Settled Date</th>
                <th>Reference</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {SETTLEMENTS.map(s => (
                <tr key={s.id} style={s.status === "Overdue" ? { background: "#fef4f4" } : null}>
                  <td className="mono tiny bold">{s.id}</td>
                  <td className="mono tiny">{s.rebate}</td>
                  <td className="tiny">{s.period}</td>
                  <td className="num mono tiny">{fmt.num(s.accrued, 0)} {s.ccy}</td>
                  <td className="num mono tiny">{fmt.num(s.claimed, 0)} {s.ccy}</td>
                  <td className="num mono tiny" style={{ color: Math.abs(s.variance) > 5 ? "var(--amber)" : "var(--ink-mute)", fontWeight: Math.abs(s.variance) > 5 ? 600 : 400 }}>
                    {s.variance === 0 ? "—" : (s.variance > 0 ? "+" : "") + s.variance.toFixed(1) + "%"}
                  </td>
                  <td className="mono tiny muted">{s.claimedDate}</td>
                  <td className="mono tiny muted">{s.settledDate || "—"}</td>
                  <td className="mono tiny">{s.ref}</td>
                  <td>
                    {s.status === "Settled" && <Pill status="Approved">Settled</Pill>}
                    {s.status === "Awaiting Credit" && <Pill status="Pending">Awaiting Credit</Pill>}
                    {s.status === "In Review" && <Pill status="Draft">In Review</Pill>}
                    {s.status === "Overdue" && <Pill className="rejected">Overdue · {s.daysOverdue}d</Pill>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

// ============== REBATE DETAIL ==============
function RebateDetail({ rebate, onClose, perms }) {
  const t = TERMINAL_BY_CODE[rebate.terminal];
  const ytd = YTD_VOLUME[rebate.terminal] || 0;
  return (
    <SlideOver
      open={true}
      onClose={onClose}
      wide
      title={`${rebate.type} · ${t?.name}`}
      sub={`${rebate.id} · ${rebate.contractRef}`}
      foot={
        <>
          <button className="btn" onClick={onClose}>Close</button>
          <div className="grow" />
          {perms.admin && <button className="btn"><Icon name="edit" size={14} /> Edit terms</button>}
          {perms.admin && <button className="btn primary"><Icon name="plus" size={14} /> Log settlement</button>}
        </>
      }
    >
      <div className="grid-3" style={{ marginBottom: 18 }}>
        <div>
          <div className="tiny muted mono" style={{ textTransform: "uppercase" }}>YTD Accrual</div>
          <div className="serif" style={{ fontSize: 24, fontWeight: 500 }}>{fmt.usd(rebate.accruedYTD)}</div>
          <div className="tiny muted mono">{fmt.num(rebate.accruedYTDLocal)} {rebate.currency}</div>
        </div>
        <div>
          <div className="tiny muted mono" style={{ textTransform: "uppercase" }}>YTD Volume</div>
          <div className="serif" style={{ fontSize: 24, fontWeight: 500 }}>{fmt.num(ytd, 0)} <span className="tiny muted">TEU</span></div>
        </div>
        <div>
          <div className="tiny muted mono" style={{ textTransform: "uppercase" }}>Current Tier</div>
          <div className="serif" style={{ fontSize: 24, fontWeight: 500 }}>{rebate.tiers[rebate.currentTier]?.name || "—"}</div>
          <div className="tiny muted mono">@ {rebate.tiers[rebate.currentTier]?.rate}%</div>
        </div>
      </div>

      <Card title="Tier structure" sub="Inline editor · retroactive vs incremental"
        right={perms.admin ? <button className="btn ghost tiny"><Icon name="plus" size={12} /> Add tier</button> : null}
        style={{ marginBottom: 16 }}>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>Tier</th>
                <th className="num">Min Volume</th>
                <th className="num">Max Volume</th>
                <th className="num">Rate</th>
                <th>Type</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {rebate.tiers.map((t, i) => (
                <tr key={i} style={i === rebate.currentTier ? { background: "var(--teal-soft)" } : null}>
                  <td className="bold tiny">{t.name}</td>
                  <td className="num mono">{fmt.num(t.min, 0)}</td>
                  <td className="num mono">{t.max ? fmt.num(t.max, 0) : "∞"}</td>
                  <td className="num mono bold">{t.rate.toFixed(1)}%</td>
                  <td><Pill className="plain">{t.type}</Pill></td>
                  <td>{i === rebate.currentTier ? <Pill status="Active">Current</Pill> : i < rebate.currentTier ? <span className="tiny muted">✓ achieved</span> : <span className="tiny muted">pending</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      <Card title="Contract terms" style={{ marginBottom: 16 }}>
        <div style={{ padding: 16 }}>
          <table style={{ width: "100%", fontSize: 13 }}>
            <tbody>
              <DRow k="Terminal" v={<><b>{t?.name}</b> <span className="mono tiny muted">({rebate.terminal})</span></>} />
              <DRow k="Type" v={rebate.type} />
              <DRow k="Applicable scope" v={rebate.scope} />
              <DRow k="Measurement period" v={rebate.period} />
              <DRow k="Settlement method" v={rebate.settlement} />
              <DRow k="Settlement deadline" v={`${rebate.deadline} days after period end`} />
              <DRow k="Effective" v={<span className="mono">{rebate.effective} → {rebate.expiry}</span>} />
              <DRow k="Currency" v={<span className="mono">{rebate.currency}</span>} />
            </tbody>
          </table>
        </div>
      </Card>
    </SlideOver>
  );
}

function NewSettlement({ onClose }) {
  return (
    <SlideOver
      open={true}
      onClose={onClose}
      title="Log new settlement"
      sub="Procurement workflow · validates against calculated accrual"
      foot={
        <>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={onClose}><Icon name="check" size={14} /> Submit for review</button>
        </>
      }
    >
      <div style={{ display: "grid", gap: 14 }}>
        <Field label="Rebate contract" required>
          <select className="select">
            {REBATES.map(r => <option key={r.id}>{r.id} — {TERMINAL_BY_CODE[r.terminal]?.name}</option>)}
          </select>
        </Field>
        <Field label="Settlement period" required>
          <select className="select"><option>Q1 2025</option><option>Q2 2025</option><option>Apr 2025</option><option>May 2025</option></select>
        </Field>
        <Field label="Amount claimed (local)" required>
          <div className="row gap-4">
            <input className="input mono" placeholder="0.00" />
            <select className="select" style={{ width: 90 }}><option>SGD</option><option>CNY</option><option>USD</option></select>
          </div>
        </Field>
        <Field label="Settlement reference" required>
          <input className="input mono" placeholder="CRN-… / Cash receipt #" />
        </Field>
        <Field label="Settlement date" required>
          <input className="input mono" type="date" />
        </Field>
        <Field label="Notes">
          <textarea className="input" rows={3} placeholder="Any context for FBP / audit reviewers…" />
        </Field>

        <div style={{ background: "var(--paper)", padding: 12, borderRadius: 6 }}>
          <div className="tiny mono muted" style={{ textTransform: "uppercase" }}>Calculated accrual (for validation)</div>
          <div className="serif" style={{ fontSize: 20, fontWeight: 500 }}>312,800 CNY · {fmt.usd(43130)}</div>
          <div className="tiny muted" style={{ marginTop: 4 }}>System will flag for review if claim deviates &gt; 5%</div>
        </div>
      </div>
    </SlideOver>
  );
}

Object.assign(window, { RebateMonitor });
