/* AIWine CRM — Memberships (consumer plans + winery tiers) */
function Memberships({ country }) {
  const store = window.UI.useStore();
  const { Badge, CTag, Ic, rel, fmtDate, money, StatTile } = window.UI;
  const [tab, setTab] = React.useState('consumers');
  const F = (rows) => rows.filter((r) => window.UI.inCountry(r, country));

  const consumers = F(store.t('consumers'));
  const premium = consumers.filter((c) => c.plan === 'premium');
  const renewals = premium.filter((c) => c.renewsAt).sort((a, b) => a.renewsAt.localeCompare(b.renewsAt));
  const due = renewals.filter((c) => new Date(c.renewsAt) < new Date(Date.now() + 30 * 86400000));
  const overdue = renewals.filter((c) => new Date(c.renewsAt) < new Date());

  const wineries = F(store.t('wineries'));
  const tiers = ['founding', 'partner', 'listed', 'prospect'];
  const TIER_PRICE = { founding: 149, partner: 99, listed: 49, prospect: 0 };

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>Recurring revenue · both sides of the marketplace</div>
          <h1 className="page-title">Memberships</h1>
        </div>
      </div>

      <window.UI.Tabs value={tab} onChange={setTab} items={[
        { id: 'consumers', label: 'Consumer plans', count: premium.length },
        { id: 'wineries', label: 'Winery tiers', count: wineries.filter((w) => w.tier !== 'prospect').length },
      ]} />

      {tab === 'consumers' && (
        <div>
          <div className="stat-grid" style={{ marginBottom: 18 }}>
            <StatTile label="Premium members" num={premium.length} delta={Math.round((premium.length / Math.max(consumers.length, 1)) * 100) + '% of ' + consumers.length} />
            <StatTile label="Renewals · 30 days" num={due.length} delta={overdue.length + ' overdue'} deltaClass={overdue.length ? 'bad' : 'up'} />
            <StatTile label="Est. annual value" num={money(premium.length * 79, country === 'AU' ? 'AU' : 'NZ')} delta="at $79/yr premium" />
            <StatTile label="Free tasters" num={consumers.length - premium.length} delta="upgrade pipeline" />
          </div>
          <div className="tbl-wrap">
            <table className="tbl">
              <thead><tr><th>Member</th><th></th><th>Renews</th><th>Status</th><th>LTV</th><th></th></tr></thead>
              <tbody>
                {renewals.map((c) => {
                  const days = Math.round((new Date(c.renewsAt) - Date.now()) / 86400000);
                  return (
                    <tr key={c.id} className="rowlink" onClick={() => window.go('consumers', c.id)}>
                      <td className="main-cell" style={{ display: 'flex', alignItems: 'center', gap: 10 }}><window.UI.Avatar name={c.name} />{c.name}<div className="sub mono" style={{ fontSize: 10.5 }}>{c.email}</div></td>
                      <td><CTag c={c.country} /></td>
                      <td className="num">{fmtDate(c.renewsAt)}</td>
                      <td>{days < 0 ? <Badge v="open" dot>Overdue</Badge> : days < 30 ? <Badge v="scheduled">Due in {days}d</Badge> : <Badge v="complete">Current</Badge>}</td>
                      <td className="num">{money(c.ltv, c.country)}</td>
                      <td onClick={(e) => e.stopPropagation()}>
                        {days < 30 && <button className="btn btn-ghost btn-sm" onClick={() => { store.update('consumers', c.id, { renewsAt: new Date(Date.now() + 365 * 86400000).toISOString() }); store.audit('Renewed ' + c.name, 'consumer'); window.UI.toast('Renewed for 12 months'); }}>Record renewal</button>}
                      </td>
                    </tr>
                  );
                })}
                {renewals.length === 0 && <tr><td colSpan="6"><window.UI.Empty msg="No premium memberships in this market yet" /></td></tr>}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'wineries' && (
        <div className="split">
          <div className="tbl-wrap">
            <table className="tbl">
              <thead><tr><th>Winery</th><th></th><th>Tier</th><th>Engagement</th><th>Member since</th></tr></thead>
              <tbody>
                {wineries.filter((w) => w.tier !== 'prospect').sort((a, b) => tiers.indexOf(a.tier) - tiers.indexOf(b.tier)).map((w) => (
                  <tr key={w.id} className="rowlink" onClick={() => window.go('wineries', w.id)}>
                    <td className="main-cell">{w.name}<div className="sub">{w.region}</div></td>
                    <td><CTag c={w.country} /></td>
                    <td><Badge v={w.tier}>{window.UI.TIER_LABEL[w.tier]}</Badge></td>
                    <td><window.UI.Score v={w.engagement} /></td>
                    <td className="num">{fmtDate(w.createdAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="card card-pad">
            <div className="label" style={{ marginBottom: 14 }}>Tier mix</div>
            {tiers.map((t) => (
              <window.UI.HBar key={t} label={window.UI.TIER_LABEL[t]} value={wineries.filter((w) => w.tier === t).length} max={wineries.length}
                color={t === 'founding' ? 'var(--claret)' : t === 'partner' ? 'var(--brass)' : t === 'listed' ? 'var(--green)' : 'var(--faint)'} />
            ))}
            <div style={{ borderTop: '1px solid var(--line-soft)', marginTop: 14, paddingTop: 12, fontSize: 12.5, color: 'var(--muted)' }}>
              Est. monthly winery revenue<br />
              <span className="serif" style={{ fontSize: 26, color: 'var(--ink)', fontWeight: 500 }}>
                {money(wineries.reduce((s, w) => s + (TIER_PRICE[w.tier] || 0), 0), country === 'AU' ? 'AU' : 'NZ')}
              </span>
              <span className="mono" style={{ fontSize: 10 }}> /MO</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
window.Memberships = Memberships;
