// JFJ HQ Console — Affiliates, Compensation, Contests

const { useState: useStateHQ, useMemo: useMemoHQ } = React;
const { Icon, fmtMoney, fmtPct, Pill, EntityChip, KPI, Card, Button, Sparkline, StageBar } = window;

// ============== HQ AFFILIATES ==============
const HQAffiliates = ({ onNav }) => {
  const { ENTITIES, LEADERBOARD } = window.JFJ;
  const [tab, setTab] = useStateHQ('all');
  const [q, setQ] = useStateHQ('');

  // Synthesize a richer affiliate roster from leaderboard + a few extra rows
  const roster = useMemoHQ(() => {
    const extras = [
      { rank: 11, name: 'Noor Patel',       handle: '@noorp',    gmv: 64200, deals: 8 },
      { rank: 12, name: 'Carlos Mendez',    handle: '@cmendez',  gmv: 58800, deals: 7 },
      { rank: 13, name: 'Ingrid Solberg',   handle: '@ingrid.s', gmv: 51200, deals: 7 },
      { rank: 14, name: 'Wesley Tran',      handle: '@wes',      gmv: 44900, deals: 6 },
      { rank: 15, name: 'Aisha Bello',      handle: '@abello',   gmv: 38400, deals: 5 },
      { rank: 16, name: 'Pavel Romero',     handle: '@pavel.r',  gmv: 31200, deals: 4 },
    ];
    const all = LEADERBOARD.concat(extras);
    const states = ['active', 'active', 'active', 'active', 'active', 'active', 'active', 'ramping', 'ramping', 'active', 'ramping', 'active', 'paused', 'ramping', 'ramping', 'paused'];
    const tiers = ['Diamond','Diamond','Platinum','Platinum','Platinum','Gold','Gold','Gold','Gold','Silver','Silver','Silver','Silver','Silver','Bronze','Bronze'];
    const certCounts = [6, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1];
    return all.map((a, i) => ({
      ...a,
      state: states[i] || 'active',
      tier: tiers[i] || 'Bronze',
      certs: certCounts[i] || 1,
      lastActive: i === 0 ? '2h ago' : i < 5 ? 'Today' : i < 10 ? 'Yesterday' : i < 14 ? '3d ago' : '11d ago',
      mainEntity: i % 4 === 0 ? 'trusts' : i % 4 === 1 ? 'tax' : i % 4 === 2 ? 'consulting' : 'leadgen',
      sevenDay: 0.5 + Math.random() * 1.5, // velocity multiplier
    }));
  }, []);

  const filtered = useMemoHQ(() => {
    let list = roster;
    if (tab !== 'all') list = list.filter(r => r.state === tab);
    if (q) {
      const qq = q.toLowerCase();
      list = list.filter(r => r.name.toLowerCase().includes(qq) || r.handle.toLowerCase().includes(qq));
    }
    return list;
  }, [roster, tab, q]);

  const totalActive = roster.filter(r => r.state === 'active').length;
  const totalRamping = roster.filter(r => r.state === 'ramping').length;
  const totalPaused = roster.filter(r => r.state === 'paused').length;

  const tierColor = (t) =>
    t === 'Diamond'  ? 'oklch(70% 0.16 220)' :
    t === 'Platinum' ? 'oklch(72% 0.04 250)' :
    t === 'Gold'     ? 'oklch(78% 0.14 80)'  :
    t === 'Silver'   ? 'oklch(75% 0.02 250)' :
                       'oklch(60% 0.10 40)';

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="crumbs">
            <span style={{ color: 'var(--accent)' }}>HQ</span>
            <Icon.Chevron size={12} />
            <span>Affiliates</span>
          </div>
          <h1>Affiliates</h1>
          <p className="mt-12">{roster.length} on the program · {totalActive} active · {totalRamping} ramping · {totalPaused} paused</p>
        </div>
        <div className="row gap-8">
          <Button variant="secondary" leading={<Icon.Filter size={14} />}>Export CSV</Button>
          <Button variant="primary" leading={<Icon.Plus size={14} />}>Invite affiliate</Button>
        </div>
      </div>

      <div className="kpi-row mb-24">
        <KPI label="Active" value={totalActive} sub="logged in past 7d" accent="var(--accent)" />
        <KPI label="Ramping" value={totalRamping} sub="<3 deals certified" />
        <KPI label="Avg. GMV / affiliate" value={fmtMoney(Math.round(roster.reduce((a, r) => a + r.gmv, 0) / roster.length))} sub="trailing 30d" />
        <KPI label="Top performer" value="Avery T." sub={fmtMoney(184500) + " · 31 deals"} />
      </div>

      <Card pad={false}>
        <div className="row middle between" style={{ padding: '12px 16px', borderBottom: '1px solid var(--line)', gap: 12 }}>
          <div className="row gap-6">
            {[
              { id: 'all',     label: 'All ' + roster.length },
              { id: 'active',  label: 'Active ' + totalActive },
              { id: 'ramping', label: 'Ramping ' + totalRamping },
              { id: 'paused',  label: 'Paused ' + totalPaused },
            ].map(t => (
              <button
                key={t.id}
                onClick={() => setTab(t.id)}
                style={{
                  padding: '6px 12px', borderRadius: 6, fontSize: 12.5, fontWeight: 600,
                  background: tab === t.id ? 'var(--surface-2)' : 'transparent',
                  color: tab === t.id ? 'var(--ink-1)' : 'var(--ink-3)',
                  border: '1px solid ' + (tab === t.id ? 'var(--line)' : 'transparent'),
                  cursor: 'pointer', fontFamily: 'inherit'
                }}
              >{t.label}</button>
            ))}
          </div>
          <div className="row gap-8 middle">
            <div style={{ position: 'relative' }}>
              <span style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)' }}><Icon.Search size={13} /></span>
              <input
                placeholder="Search by name or handle"
                value={q}
                onChange={(e) => setQ(e.target.value)}
                style={{
                  padding: '6px 10px 6px 28px', borderRadius: 6, fontSize: 12.5,
                  background: 'var(--surface-1)', border: '1px solid var(--line)',
                  color: 'var(--ink-1)', minWidth: 220, fontFamily: 'inherit', outline: 'none'
                }}
              />
            </div>
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Affiliate</th>
              <th>Tier</th>
              <th>Status</th>
              <th>Certs</th>
              <th>Main entity</th>
              <th>Deals (30d)</th>
              <th className="right">GMV (30d)</th>
              <th>Velocity 7d</th>
              <th>Last active</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const ent = window.JFJ.ENTITY_BY_ID[r.mainEntity];
              const stateTone = r.state === 'active' ? 'success' : r.state === 'ramping' ? 'accent' : 'neutral';
              return (
                <tr key={r.handle} style={{ cursor: 'pointer' }}>
                  <td>
                    <div className="row middle gap-10">
                      <div style={{
                        width: 28, height: 28, borderRadius: 999,
                        background: 'var(--surface-2)', display: 'grid', placeItems: 'center',
                        fontSize: 11, fontWeight: 700, color: 'var(--ink-2)'
                      }}>{r.name.split(' ').map(n => n[0]).slice(0, 2).join('')}</div>
                      <div className="col">
                        <div style={{ fontWeight: 500, fontSize: 13 }}>{r.name}</div>
                        <div className="muted size-12">{r.handle}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      padding: '2px 8px', borderRadius: 999, fontSize: 11.5, fontWeight: 600,
                      border: '1px solid ' + tierColor(r.tier), color: tierColor(r.tier),
                      background: 'transparent'
                    }}>{r.tier}</span>
                  </td>
                  <td><Pill tone={stateTone}>{r.state}</Pill></td>
                  <td className="num">{r.certs} / 6</td>
                  <td><EntityChip entity={ent} /></td>
                  <td className="num">{r.deals}</td>
                  <td className="right num">{fmtMoney(r.gmv)}</td>
                  <td>
                    <Sparkline
                      data={[8, 12, 10, 15, 13, 18, Math.round(20 * r.sevenDay)]}
                      w={60} h={20}
                      color={r.sevenDay > 1 ? 'var(--ok)' : r.sevenDay < 0.8 ? 'var(--warn)' : 'var(--accent)'}
                    />
                  </td>
                  <td className="muted size-12">{r.lastActive}</td>
                  <td><Button kind="ghost" size="sm">View</Button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

// ============== HQ COMPENSATION ==============
const HQCompensation = () => {
  const { ENTITIES } = window.JFJ;
  const [editing, setEditing] = useStateHQ(null);

  const tiers = [
    { name: 'Bronze', range: '0 – 5 deals',  multiplier: '1.00×', perks: 'Standard payout', count: 134 },
    { name: 'Silver', range: '6 – 14 deals', multiplier: '1.10×', perks: '+10% comp · weekly payouts', count: 78 },
    { name: 'Gold',   range: '15 – 29 deals', multiplier: '1.20×', perks: '+20% comp · contest priority', count: 24 },
    { name: 'Platinum', range: '30 – 59 deals', multiplier: '1.35×', perks: '+35% comp · co-marketing fund', count: 8 },
    { name: 'Diamond',  range: '60+ deals',     multiplier: '1.50×', perks: '+50% comp · 1:1 strategist · summit invite', count: 3 },
  ];

  const tierColor = (t) =>
    t === 'Diamond'  ? 'oklch(70% 0.16 220)' :
    t === 'Platinum' ? 'oklch(72% 0.04 250)' :
    t === 'Gold'     ? 'oklch(78% 0.14 80)'  :
    t === 'Silver'   ? 'oklch(75% 0.02 250)' :
                       'oklch(60% 0.10 40)';

  const upcomingPayout = [
    { batch: 'May 15 batch', count: 96,  total: 168320, status: 'Pending approval' },
    { batch: 'May 1 batch',  count: 88,  total: 142410, status: 'Paid' },
    { batch: 'Apr 15 batch', count: 84,  total: 138780, status: 'Paid' },
    { batch: 'Apr 1 batch',  count: 79,  total: 125940, status: 'Paid' },
  ];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="crumbs">
            <span style={{ color: 'var(--accent)' }}>HQ</span>
            <Icon.Chevron size={12} />
            <span>Compensation</span>
          </div>
          <h1>Compensation</h1>
          <p className="mt-12">Per-entity payouts, tier multipliers, and the next batch ready for approval.</p>
        </div>
        <div className="row gap-8">
          <Button kind="ghost" icon={<Icon.Book size={14} />}>Plan history</Button>
          <Button kind="primary" icon={<Icon.Plus size={14} />}>New plan version</Button>
        </div>
      </div>

      <div className="kpi-row mb-24">
        <KPI label="May payout (in flight)" value={fmtMoney(168320)} sub="96 affiliates · approve by May 14" accent="var(--accent)" />
        <KPI label="Paid YTD" value={fmtMoney(842100)} sub="across 4 batches" />
        <KPI label="Avg. comp / deal" value={fmtMoney(1685)} delta="+4%" deltaTone="up" sub="vs. Q1 avg" />
        <KPI label="Top earner · MTD" value={fmtMoney(18420)} sub="Avery T. · 31 deals" />
      </div>

      <Card title="Per-entity payout structure" subtitle="Affiliates earn the base amount on every Closed-Won, then multiplied by their tier."
        right={<Button kind="ghost" size="sm" icon={<Icon.Settings size={13} />}>Edit defaults</Button>}
        pad={false}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Entity</th>
              <th>Trigger event</th>
              <th>Base payout</th>
              <th>Avg. cycle</th>
              <th>Avg. ticket</th>
              <th>Margin band</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {ENTITIES.map(e => (
              <tr key={e.id}>
                <td>
                  <div className="row middle gap-10">
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: e.color }} />
                    <span style={{ fontWeight: 500 }}>{e.name}</span>
                  </div>
                </td>
                <td className="muted size-12">{e.id === 'leadgen' ? 'Qualified appointment set' : 'Invoice paid'}</td>
                <td className="num" style={{ fontWeight: 600 }}>{e.payoutModel}</td>
                <td className="muted">{e.avgDealCycle}</td>
                <td className="num">{fmtMoney(e.avgCommission * 4)}</td>
                <td>
                  <div style={{ width: 120, height: 6, borderRadius: 3, background: 'var(--surface-2)', position: 'relative' }}>
                    <div style={{
                      position: 'absolute', left: '15%', width: '55%', height: '100%',
                      background: 'color-mix(in oklab, ' + (e.color || 'var(--accent)') + ' 70%, transparent)',
                      borderRadius: 3
                    }} />
                  </div>
                </td>
                <td><Button kind="ghost" size="sm">Edit</Button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div className="grid grid-12-8 mt-24">
        <Card title="Tier multipliers" subtitle="Applied to base payouts on Closed Won. Re-evaluated monthly." pad={false}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Tier</th>
                <th>Range (90d)</th>
                <th>Multiplier</th>
                <th>Perks</th>
                <th className="right">Affiliates</th>
              </tr>
            </thead>
            <tbody>
              {tiers.map(t => (
                <tr key={t.name}>
                  <td>
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      padding: '2px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700,
                      border: '1px solid ' + tierColor(t.name), color: tierColor(t.name)
                    }}>{t.name}</span>
                  </td>
                  <td className="muted size-12">{t.range}</td>
                  <td className="num" style={{ fontWeight: 700, fontFamily: 'var(--mono)' }}>{t.multiplier}</td>
                  <td className="muted size-12">{t.perks}</td>
                  <td className="right num">{t.count}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title="Payout batches" pad={false}>
          {upcomingPayout.map((b, i) => (
            <div key={i} className="row middle between" style={{
              padding: '14px 18px', borderTop: i ? '1px solid var(--line-2)' : 'none'
            }}>
              <div className="col" style={{ flex: 1 }}>
                <div className="size-13 weight-5">{b.batch}</div>
                <div className="muted size-12">{b.count} affiliates · {fmtMoney(b.total)}</div>
              </div>
              {b.status === 'Pending approval'
                ? <Button kind="primary" size="sm">Review &amp; approve</Button>
                : <Pill tone="success">Paid</Pill>}
            </div>
          ))}
          <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line-2)', background: 'var(--surface-2)' }}>
            <div className="row middle between">
              <span className="muted size-12">YTD paid</span>
              <span className="num weight-6">{fmtMoney(842100)}</span>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
};

// ============== HQ CONTESTS ==============
const HQContests = () => {
  const { CONTESTS, ENTITIES } = window.JFJ;
  const [tab, setTab] = useStateHQ('live');

  // Enrich + add some past/upcoming contests
  const live = CONTESTS.map(c => {
    const e = c.entity ? window.JFJ.ENTITY_BY_ID[c.entity] : null;
    return {
      ...c,
      status: 'live',
      participants: c.id === 'spring-newbie' ? 84 : c.id === 'may-trust-blitz' ? 142 : 96,
      progress: c.id === 'spring-newbie' ? 0.78 : c.id === 'may-trust-blitz' ? 0.55 : 0.30,
      entityObj: e,
    };
  });

  const past = [
    { id: 'apr-trust-rush', title: 'April Trust Rush', entity: 'trusts', prize: '$3,000 + Bose pkg', endsIn: 'Ended Apr 30', metric: 'Closed Won', participants: 118, winner: 'Avery Thompson', winnerValue: '14 deals', status: 'past' },
    { id: 'q1-tax-finale',  title: 'Q1 Tax Finale',    entity: 'tax',    prize: '$5,000 cash',     endsIn: 'Ended Mar 31', metric: 'Invoice Sent', participants: 94,  winner: 'Marcus Liu',     winnerValue: '21 invoices', status: 'past' },
  ];

  const draft = [
    { id: 'jun-cert-blitz', title: 'June Certification Blitz', entity: null, prize: 'TBD', startsIn: 'Starts Jun 1', metric: 'New certifications', status: 'draft' },
  ];

  const showing = tab === 'live' ? live : tab === 'past' ? past : draft;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="crumbs">
            <span style={{ color: 'var(--accent)' }}>HQ</span>
            <Icon.Chevron size={12} />
            <span>Contests</span>
          </div>
          <h1>Contests</h1>
          <p className="mt-12">Spin up time-boxed pushes around an entity, a stage, or a behaviour.</p>
        </div>
        <div className="row gap-8">
          <Button kind="ghost" icon={<Icon.Trophy size={14} />}>Templates</Button>
          <Button kind="primary" icon={<Icon.Plus size={14} />}>New contest</Button>
        </div>
      </div>

      <div className="kpi-row mb-24">
        <KPI label="Live contests" value={live.length} sub={`${live.reduce((a, c) => a + c.participants, 0)} participants`} accent="var(--accent)" />
        <KPI label="Prize pool · MTD" value={fmtMoney(7500)} sub="$5k cash + travel" />
        <KPI label="Lift on participating affiliates" value="+38%" deltaTone="up" sub="vs. non-participants" />
        <KPI label="Avg. participation rate" value="62%" sub="of eligible affiliates" />
      </div>

      <div className="row gap-6 mb-16">
        {[
          { id: 'live', label: 'Live ' + live.length },
          { id: 'past', label: 'Past ' + past.length },
          { id: 'draft', label: 'Drafts ' + draft.length },
        ].map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            style={{
              padding: '6px 12px', borderRadius: 6, fontSize: 12.5, fontWeight: 600,
              background: tab === t.id ? 'var(--surface-2)' : 'transparent',
              color: tab === t.id ? 'var(--ink-1)' : 'var(--ink-3)',
              border: '1px solid ' + (tab === t.id ? 'var(--line)' : 'transparent'),
              cursor: 'pointer', fontFamily: 'inherit'
            }}
          >{t.label}</button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 16 }}>
        {showing.map(c => {
          const ent = c.entity ? window.JFJ.ENTITY_BY_ID[c.entity] : null;
          const accent = ent ? ent.color : 'var(--accent)';
          return (
            <div key={c.id} style={{
              background: 'var(--surface-1)', border: '1px solid var(--line)',
              borderRadius: 10, overflow: 'hidden', display: 'flex', flexDirection: 'column'
            }}>
              <div style={{
                padding: '14px 16px', borderBottom: '1px solid var(--line)',
                display: 'flex', flexDirection: 'column', gap: 8,
                background: 'linear-gradient(180deg, color-mix(in oklab, ' + accent + ' 8%, transparent), transparent)'
              }}>
                <div className="row middle between">
                  {ent ? <EntityChip entity={ent} /> : <Pill tone="neutral">All entities</Pill>}
                  {c.status === 'live' && <Pill tone="success">● Live</Pill>}
                  {c.status === 'past' && <Pill tone="neutral">Ended</Pill>}
                  {c.status === 'draft' && <Pill tone="warn">Draft</Pill>}
                </div>
                <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink-1)', fontFamily: 'var(--display)' }}>{c.title}</div>
                <div className="muted size-12">{c.metric} · {c.endsIn || c.startsIn}</div>
              </div>

              <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
                <div className="row middle between">
                  <div className="col">
                    <div className="muted size-12" style={{ textTransform: 'uppercase', letterSpacing: 0.4, fontWeight: 600 }}>Prize</div>
                    <div className="size-13 weight-6" style={{ marginTop: 2 }}>{c.prize}</div>
                  </div>
                  {c.status === 'live' && (
                    <div className="col" style={{ textAlign: 'right' }}>
                      <div className="muted size-12" style={{ textTransform: 'uppercase', letterSpacing: 0.4, fontWeight: 600 }}>Participants</div>
                      <div className="num size-13 weight-6" style={{ marginTop: 2 }}>{c.participants}</div>
                    </div>
                  )}
                  {c.status === 'past' && (
                    <div className="col" style={{ textAlign: 'right' }}>
                      <div className="muted size-12" style={{ textTransform: 'uppercase', letterSpacing: 0.4, fontWeight: 600 }}>Winner</div>
                      <div className="size-13 weight-6" style={{ marginTop: 2 }}>{c.winner}</div>
                    </div>
                  )}
                </div>

                {c.status === 'live' && (
                  <div>
                    <div className="row middle between mb-8">
                      <span className="muted size-12">Time elapsed</span>
                      <span className="num size-12">{Math.round(c.progress * 100)}%</span>
                    </div>
                    <div style={{ height: 6, borderRadius: 3, background: 'var(--surface-2)', overflow: 'hidden' }}>
                      <div style={{ width: (c.progress * 100) + '%', height: '100%', background: accent }} />
                    </div>
                  </div>
                )}

                {c.status === 'past' && (
                  <div className="row middle between" style={{ padding: '8px 10px', background: 'var(--surface-2)', borderRadius: 6 }}>
                    <span className="muted size-12">Winning value</span>
                    <span className="num size-13 weight-6">{c.winnerValue}</span>
                  </div>
                )}
              </div>

              <div className="row gap-8" style={{ padding: '10px 16px', borderTop: '1px solid var(--line)', background: 'var(--surface-2)' }}>
                {c.status === 'live' && <>
                  <Button kind="ghost" size="sm">Leaderboard</Button>
                  <Button kind="ghost" size="sm" icon={<Icon.Settings size={12} />}>Edit</Button>
                </>}
                {c.status === 'past' && <Button kind="ghost" size="sm">View results</Button>}
                {c.status === 'draft' && <>
                  <Button kind="primary" size="sm">Launch</Button>
                  <Button kind="ghost" size="sm">Edit draft</Button>
                </>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

Object.assign(window, { HQAffiliates, HQCompensation, HQContests });
