/* AIWine CRM — Payouts: monthly winery statements under the Discovery Cart model.
   Formula (per winery, per month):
     wine total (after Discovery Dozen 10%)            = W
     app-member rebate given to consumers              = R  (funded by AIWine)
     winery payout = 0.80 × W  +  R×0.80 is NOT deducted — winery is made whole:
                     payout = 0.80 × W + delivery fees collected on its shipments
     AIWine keeps   = 0.20 × W − R   (the rebate comes out of AIWine's commission)
   Demo data below until live orders flow through Supabase. */
function Payouts({ country }) {
  const store = window.UI.useStore();
  const { Ic, Badge, StatTile, Field } = window.UI;
  const money = (n) => '$' + Number(n).toLocaleString('en-NZ', { maximumFractionDigits: 0 });

  // ---- demo month of shipments (replace with live orders when wired) ----
  const DEMO = [
    { winery: 'Three Chimneys', shipments: [
      { id: 'AW-3101', bottles: 6, wine: 312, dozenDisc: 0, appRebate: 0, delivery: 0 },
      { id: 'AW-3120', bottles: 3, wine: 141, dozenDisc: 0, appRebate: 14, delivery: 12 },
      { id: 'AW-3155', bottles: 12, wine: 588, dozenDisc: 65, appRebate: 0, delivery: 0 },
    ]},
    { winery: 'Foley Wines (group)', group: true, shipments: [
      { id: 'AW-3092', bottles: 12, wine: 640, dozenDisc: 71, appRebate: 64, delivery: 0 },
      { id: 'AW-3141', bottles: 6, wine: 289, dozenDisc: 0, appRebate: 0, delivery: 0 },
    ]},
    { winery: 'The Good Way', shipments: [
      { id: 'AW-3110', bottles: 4, wine: 176, dozenDisc: 0, appRebate: 0, delivery: 12 },
      { id: 'AW-3167', bottles: 6, wine: 264, dozenDisc: 0, appRebate: 26, delivery: 0 },
    ]},
  ];
  const COMMISSION = 0.20;

  const rows = DEMO.map((w) => {
    const wine = w.shipments.reduce((s, x) => s + x.wine - x.dozenDisc, 0);
    const rebate = w.shipments.reduce((s, x) => s + x.appRebate, 0);
    const delivery = w.shipments.reduce((s, x) => s + x.delivery, 0);
    const commission = Math.round(wine * COMMISSION);
    const payout = wine - commission + delivery;      // winery made whole on rebates
    const aiwine = commission - rebate;                // rebate funded from commission
    return { ...w, wine, rebate, delivery, commission, payout, aiwine, bottles: w.shipments.reduce((s, x) => s + x.bottles, 0) };
  });
  const T = (k) => rows.reduce((s, r) => s + r[k], 0);
  const [open, setOpen] = React.useState(null);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="label">Revenue · Discovery Cart</div>
          <h1 className="page-title">Payouts</h1>
          <div className="page-sub">Monthly statements — paid in the first week of the following month. Payout = wine total (after Discovery Dozen) − 20% commission + delivery fees collected. App-member rebates are funded from AIWine's commission; the winery's return never changes.</div>
        </div>
        <Badge v="onboarding">Demo data · June 2026</Badge>
      </div>

      <div className="stat-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(170px,1fr))', gap: 12, marginBottom: 18 }}>
        <StatTile label="Wine revenue" num={money(T('wine'))} delta={T('bottles') + ' bottles across ' + rows.reduce((s, r) => s + r.shipments.length, 0) + ' shipments'} />
        <StatTile label="Winery payouts" num={money(T('payout'))} delta="incl. delivery fees passed through" />
        <StatTile label="AIWine commission" num={money(T('commission'))} delta="20% of discounted wine total" />
        <StatTile label="App rebates funded" num={'−' + money(T('rebate'))} delta={'AIWine keeps ' + money(T('aiwine')) + ' net'} />
      </div>

      <div className="card">
        <div className="tbl-wrap"><table className="tbl">
          <thead><tr><th>Winery</th><th>Shipments</th><th>Wine total*</th><th>Commission 20%</th><th>App rebate (AIWine-funded)</th><th>Delivery fees</th><th>Payout</th><th></th></tr></thead>
          <tbody>
            {rows.map((r) => (
              <React.Fragment key={r.winery}>
                <tr style={{ cursor: 'pointer' }} onClick={() => setOpen(open === r.winery ? null : r.winery)}>
                  <td><b>{r.winery}</b>{r.group ? <span className="mono" style={{ fontSize: 9.5, color: 'var(--muted)', marginLeft: 6 }}>pooled carton</span> : null}</td>
                  <td>{r.shipments.length} · {r.bottles} btls</td>
                  <td>{money(r.wine)}</td>
                  <td style={{ color: 'var(--muted)' }}>−{money(r.commission)}</td>
                  <td style={{ color: 'var(--muted)' }}>{r.rebate ? money(r.rebate) : '—'}</td>
                  <td>{r.delivery ? '+' + money(r.delivery) : '—'}</td>
                  <td><b>{money(r.payout)}</b></td>
                  <td><Ic name={open === r.winery ? 'chevron-up' : 'chevron-down'} w={14} /></td>
                </tr>
                {open === r.winery && (
                  <tr><td colSpan={8} style={{ background: 'var(--card-2)', padding: '10px 16px' }}>
                    <table className="tbl" style={{ fontSize: 12 }}>
                      <thead><tr><th>Order</th><th>Bottles</th><th>Tier</th><th>Wine</th><th>Dozen −10%</th><th>App rebate</th><th>Delivery</th></tr></thead>
                      <tbody>
                        {r.shipments.map((s) => (
                          <tr key={s.id}>
                            <td className="mono">{s.id}</td>
                            <td>{s.bottles}</td>
                            <td>{s.bottles >= 12 ? <Badge v="active">Discovery Dozen</Badge> : s.bottles >= 6 ? <Badge v="onboarding">Discovery Six</Badge> : <Badge v="prospect">Under 6 · $12</Badge>}</td>
                            <td>{money(s.wine)}</td>
                            <td>{s.dozenDisc ? '−' + money(s.dozenDisc) : '—'}</td>
                            <td>{s.appRebate ? money(s.appRebate) : '—'}</td>
                            <td>{s.delivery ? money(s.delivery) : 'Free'}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </td></tr>
                )}
              </React.Fragment>
            ))}
          </tbody>
          <tfoot><tr style={{ fontWeight: 700 }}><td>Total</td><td>{rows.reduce((s, r) => s + r.shipments.length, 0)} · {T('bottles')} btls</td><td>{money(T('wine'))}</td><td>−{money(T('commission'))}</td><td>{money(T('rebate'))}</td><td>+{money(T('delivery'))}</td><td>{money(T('payout'))}</td><td></td></tr></tfoot>
        </table></div>
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 12, lineHeight: 1.55 }}>
        * Wine total is after the Discovery Dozen 10% case discount (shared 80/20 like any sale). Statements reconcile per winery in Xero — one invoice, one payment, first week of the following month. Delivery fees collected on under-6 shipments pass through to the winery in full.
      </div>
    </div>
  );
}
Object.assign(window, { Payouts });
