// Membership tab — the primary landing view for CAP.
//
// Built around the question Clemmie cares about most: how is membership
// growing, who is engaged, and where is the leak? All numbers come from
// window.CAP_MEMBERSHIP (see data.js) — deliberately mock for the demo so
// CAP can react to the *shape* of the dashboard rather than negotiate over
// any particular number.

const { useState: mtState } = React;
const MRC = window.Recharts;

const M_BRAND_RED = '#BE2E2B';
const M_RICH_BLACK = '#1A1919';
const M_DARK_GREEN = '#315A49';
const M_DARK_BLUE = '#29254E';
const M_DARK_GRAY = '#5B5C5B';
const M_LIGHT_GRAY = '#B4B5B4';
const M_TIER_COLORS = { rich: M_RICH_BLACK, red: M_BRAND_RED, green: M_DARK_GREEN, blue: M_DARK_BLUE, gray: M_DARK_GRAY };

function MembershipTab() {
  const m = window.CAP_MEMBERSHIP;
  const [range, setRange] = mtState('12M');
  const rangeMap = { '7D': -1, '30D': -1, '90D': -3, '12M': -12 };
  const trendSlice = m.acquisitionTrend.slice(rangeMap[range] || -12);

  const ChartTooltip = window.RcgChartTooltip;
  const axisProps = window.rcgAxisProps;
  const legendProps = window.rcgLegendProps;
  const FAINT_RULE = window.RCG_FAINT_RULE || 'rgba(26,25,25,0.06)';
  const ANIM = window.RCG_CHART_ANIM_MS || 650;

  return (
    <div className="tab-content" style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
      <TabHeader
        title={<>Membership<br /><span style={{ color: 'var(--brand-red)', fontStyle: 'italic', fontSize: '0.7em', textTransform: 'none' }}>College of American Pathologists</span></>}
        desc="The state of CAP's membership — growth, retention, engagement, and where new members are coming from."
        right={<RangeToggle value={range} onChange={setRange} options={['30D', '90D', '12M']} />}
      />

      {/* KPI row — membership-first */}
      <div className="kpi-grid">
        <KpiCell label="Active Members"     value={fmtNum(m.kpis.activeMembers, { compact: true })}
                 delta={m.kpis.activeMembersDelta} />
        <KpiCell label="New (last 30 days)" value={fmtNum(m.kpis.newMembers30d)}
                 delta={m.kpis.newMembers30dDelta} />
        <KpiCell label="Renewal Rate"       value={fmtPct(m.kpis.renewalRate)}
                 delta={m.kpis.renewalRateDelta} />
        <KpiCell label="Engagement Score"   value={m.kpis.engagementScore}
                 delta={m.kpis.engagementScoreDelta} />
        <KpiCell label="Annual Dues Revenue" value={fmtMoney(m.kpis.annualRevenue, { compact: true })}
                 delta={m.kpis.annualRevenueDelta} />
      </div>

      {/* Acquisition trend — net new = new − churn */}
      <Card
        title="New members vs. churn"
        sub="Net growth over the last 12 months. Annual Meeting spikes attendance-tied signups; December renewal cliff is normal."
        actions={<Pill size="sm" variant="outline">Export</Pill>}
        pad="lg"
      >
        <div style={{ width: '100%', height: 320, position: 'relative' }}>
          <MRC.ResponsiveContainer>
            <MRC.ComposedChart data={trendSlice} margin={{ top: 10, right: 18, left: 0, bottom: 0 }}>
              <defs>
                <linearGradient id="netGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={M_BRAND_RED} stopOpacity={0.22} />
                  <stop offset="100%" stopColor={M_BRAND_RED} stopOpacity={0} />
                </linearGradient>
              </defs>
              <MRC.CartesianGrid stroke={FAINT_RULE} vertical={false} strokeDasharray="2 4" />
              <MRC.XAxis dataKey="m" {...axisProps} interval="preserveStartEnd" />
              <MRC.YAxis {...axisProps} width={44} tickFormatter={(v) => fmtNum(v)} />
              <MRC.Tooltip
                cursor={{ fill: 'rgba(26,25,25,0.035)' }}
                content={(props) => <ChartTooltip {...props} valueFormatter={(v) => fmtNum(v)} />}
              />
              <MRC.Legend {...legendProps} />
              <MRC.Bar dataKey="new" name="New members" fill={M_RICH_BLACK} opacity={0.18} radius={[2,2,0,0]} barSize={18}
                animationDuration={ANIM} />
              <MRC.Bar dataKey="churn" name="Churn" fill={M_BRAND_RED} opacity={0.22} radius={[2,2,0,0]} barSize={18}
                animationDuration={ANIM} />
              <MRC.Area dataKey="net" name="Net" type="monotone"
                stroke={M_BRAND_RED} strokeWidth={2}
                fill="url(#netGrad)"
                dot={{ r: 3, fill: '#fff', stroke: M_BRAND_RED, strokeWidth: 1.6 }}
                activeDot={{ r: 5, fill: M_BRAND_RED, stroke: '#fff', strokeWidth: 2 }}
                animationDuration={ANIM} />
            </MRC.ComposedChart>
          </MRC.ResponsiveContainer>
        </div>
      </Card>

      <div className="row-2">
        {/* Tier breakdown */}
        <Card title="Tier breakdown" sub="Fellow makes up the lion's share. Resident pipeline feeds future Fellows." pad="lg">
          <table className="tbl">
            <thead>
              <tr>
                <th>Tier</th>
                <th className="num-head">Members</th>
                <th className="num-head">Dues</th>
                <th>Share</th>
              </tr>
            </thead>
            <tbody>
              {m.tiers.map((t) => {
                const total = m.tiers.reduce((s, x) => s + x.count, 0);
                const pct = (t.count / total) * 100;
                return (
                  <tr key={t.tier}>
                    <td className="strong">{t.tier}</td>
                    <td className="num">{fmtNum(t.count)}</td>
                    <td className="num">{fmtMoney(t.revenue, { compact: true })}</td>
                    <td style={{ width: 120 }}>
                      <div style={{ height: 4, background: 'var(--soft-rule)', position: 'relative' }}>
                        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: pct + '%', background: M_TIER_COLORS[t.color] || M_RICH_BLACK }} />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>

        {/* Acquisition channels */}
        <Card title="New-member acquisition" sub="Top channels driving signups in the last 90 days. Residency programs are accelerating." pad="lg">
          <div className="kv-list">
            {m.acquisitionChannels.map((c, i) => (
              <div className="row" key={i} style={{ display: 'flex', flexDirection: 'column', gap: 4, padding: '12px 0', borderBottom: i < m.acquisitionChannels.length - 1 ? '1px solid var(--soft-rule)' : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'baseline' }}>
                  <span className="strong" style={{ fontSize: 13 }}>{c.channel}</span>
                  <span style={{
                    fontSize: 11,
                    color: c.pctChange >= 0 ? M_DARK_GREEN : M_BRAND_RED,
                    fontWeight: 500,
                    fontVariantNumeric: 'tabular-nums',
                  }}>
                    {c.pctChange >= 0 ? '+' : ''}{c.pctChange}%
                  </span>
                </div>
                <div style={{ display: 'flex', gap: 12, fontSize: 11.5, color: 'var(--ink-stone)' }}>
                  <span>{fmtNum(c.members)} new members</span>
                </div>
                <div style={{ height: 3, background: 'var(--soft-rule)', marginTop: 4 }}>
                  <div style={{ height: '100%', width: Math.min(100, (c.members / 200) * 100) + '%', background: M_RICH_BLACK }} />
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Member journey funnel */}
      <Card title="Member journey" sub="Visitor → application → new member → renewing. The biggest drop is application-submitted → approved." pad="lg">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {m.journey.map((row, i) => {
            const max = m.journey[0].count;
            const pct = (row.count / max) * 100;
            const dropFromPrev = i > 0 ? (1 - row.count / m.journey[i - 1].count) * 100 : 0;
            const isCritical = i >= 3;
            return (
              <div key={row.stage} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
                  <span className="strong" style={{ fontSize: 13 }}>{row.stage}</span>
                  <span style={{ fontVariantNumeric: 'tabular-nums', fontSize: 13 }}>{fmtNum(row.count)}</span>
                  <span style={{ fontSize: 11, color: 'var(--ink-stone)', minWidth: 110, textAlign: 'right' }}>
                    {i > 0 ? `−${dropFromPrev.toFixed(1)}% step` : '100% top of funnel'}
                  </span>
                </div>
                <div style={{ height: 8, background: 'var(--soft-rule)', position: 'relative' }}>
                  <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: pct + '%', background: isCritical ? M_BRAND_RED : M_RICH_BLACK }} />
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      <div className="row-2">
        {/* Engagement breakdown */}
        <Card title="Engagement — last 90 days" sub="How engaged the existing member base is. Member portal logins are the leading indicator." pad="lg">
          <div className="kv-list">
            {m.engagement.map((e, i) => (
              <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: '14px 0', borderBottom: i < m.engagement.length - 1 ? '1px solid var(--soft-rule)' : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 10 }}>
                  <span className="strong" style={{ fontSize: 13 }}>{e.kind}</span>
                  <span style={{ fontVariantNumeric: 'tabular-nums', fontSize: 13 }}>{fmtNum(e.value)}</span>
                </div>
                <div style={{ height: 4, background: 'var(--soft-rule)' }}>
                  <div style={{ height: '100%', width: e.pct + '%', background: M_DARK_GREEN }} />
                </div>
                <div style={{ fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-stone)' }}>
                  {e.pct.toFixed(1)}% of active members
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* Churn risk */}
        <Card title="Churn risk cohorts" sub="Member groups flagged for likely non-renewal. Worth a targeted re-engagement touch." pad="lg">
          <table className="tbl">
            <thead>
              <tr>
                <th>Cohort</th>
                <th className="num-head">At risk</th>
                <th>Severity</th>
              </tr>
            </thead>
            <tbody>
              {m.churnRisk.map((c, i) => (
                <tr key={i}>
                  <td className="strong" style={{ fontSize: 12 }}>{c.cohort}</td>
                  <td className="num">{fmtNum(c.atRisk)}</td>
                  <td>
                    <span style={{
                      display: 'inline-block',
                      fontSize: 9.5,
                      letterSpacing: '0.10em',
                      textTransform: 'uppercase',
                      padding: '3px 8px',
                      background: c.severity === 'high' ? 'rgba(190, 46, 43, 0.10)' : 'rgba(190, 46, 43, 0.04)',
                      color: c.severity === 'high' ? M_BRAND_RED : 'var(--ink-stone)',
                      fontWeight: 600,
                    }}>{c.severity === 'high' ? 'High' : 'Medium'}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      {/* Editorial */}
      <Card title="This month at a glance" sub="Editorial summary. Three lines, no fluff." pad="lg">
        <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
          {m.monthAtAGlance.map((line, i) => (
            <li key={i} style={{
              padding: '14px 0 14px 22px',
              borderBottom: i < m.monthAtAGlance.length - 1 ? '1px solid var(--soft-rule)' : 'none',
              position: 'relative',
              fontSize: 14.5,
              color: 'var(--rich-black)',
              lineHeight: 1.55,
            }}>
              <span style={{ position: 'absolute', left: 0, top: 24, width: 10, height: 1, background: M_BRAND_RED }} />
              {line}
            </li>
          ))}
        </ul>
      </Card>
    </div>
  );
}
window.MembershipTab = MembershipTab;
