// JFJ Affiliate Portal — Dashboard, Entity workspace, Training, Quiz screens

const { useState, useMemo, useEffect } = React;
const { Icon, fmtMoney, fmtPct, fmtPctRaw, Pill, EntityChip, StagePill, KPI, Card, Button, Sparkline, StageBar } = window;

// ============== DASHBOARD ==============
const Dashboard = ({ onNav, onSelectEntity }) => {
  const { ENTITIES, KPIS, REFERRALS, LEADERBOARD, CONTESTS, ANNOUNCEMENTS, ME } = window.JFJ;
  const recent = REFERRALS.slice(0, 6);
  const liveContest = CONTESTS[0];
  const contestEntity = window.JFJ.ENTITY_BY_ID[liveContest.entity];

  // distribution by entity
  const byEntity = ENTITIES.map(e => ({
    ...e,
    count: REFERRALS.filter(r => r.entity === e.id).length,
    won: REFERRALS.filter(r => r.entity === e.id && r.stage === 'won').length,
  }));

  return (
    <div className="page">
      <div className="welcome">
        <h1 className="welcome-name">Good morning, Ryan.</h1>
        <span className="welcome-sub">You're #6 on the May leaderboard. 3 deals from #5.</span>
      </div>

      {/* Hype ribbon */}
      <div className="hype mt-24 mb-24">
        <div>
          <div className="hype-eyebrow">Live contest · ends in {liveContest.endsIn}</div>
          <div className="hype-title">{liveContest.title}</div>
          <div className="hype-meta">
            <span>Prize · {liveContest.prize}</span>
            <span>Your rank · #{liveContest.myRank}</span>
            <span>Leader · {liveContest.leaderRank} ({liveContest.leaderValue})</span>
          </div>
        </div>
        <div className="hype-cta">
          <Button variant="secondary" size="md" onClick={() => onNav('leaderboard')} trailing={<Icon.Chevron size={14} />}>View board</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="kpi-row mb-24">
        <KPI label="Earned this month" value={fmtMoney(KPIS.earnedThisMonth)} delta={fmtPct(KPIS.earnedDelta, 0)} deltaTone={KPIS.earnedDelta < 0 ? 'down' : 'up'} sub="vs. April" accent="var(--accent)" />
        <KPI label="Pending payout" value={fmtMoney(KPIS.pendingPayout)} sub="6 deals in flight" />
        <KPI label="Live referrals" value={KPIS.liveReferrals} delta={fmtPct(KPIS.liveReferralsDelta, 0)} deltaTone={KPIS.liveReferralsDelta < 0 ? 'down' : 'up'} sub={`${ME.stalledCount} stalled — needs action`} />
        <KPI label="Conversion rate" value={fmtPct(KPIS.conversionRate, 0)} delta={fmtPct(KPIS.conversionDelta, 0)} deltaTone={KPIS.conversionDelta < 0 ? 'down' : 'up'} sub="Lead → Won, 30d" />
      </div>

      <div className="grid grid-12-8">
        {/* Left column */}
        <div className="col gap-16">
          {/* Entities grid */}
          <Card
            title="Your entities"
            action={<Button variant="ghost" size="sm" trailing={<Icon.Chevron size={12} />}>Browse offers</Button>}
            pad={false}
          >
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }}>
              {byEntity.map((e, i) => (
                <button
                  key={e.id}
                  onClick={() => onSelectEntity(e.id)}
                  className="entity-tile"
                  style={{
                    textAlign: 'left',
                    background: 'transparent',
                    border: 0,
                    borderRight: i % 2 === 0 ? '1px solid var(--line)' : 'none',
                    borderBottom: i < 2 ? '1px solid var(--line)' : 'none',
                    padding: '20px',
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                  }}
                >
                  <div className="row middle gap-10 mb-8">
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: e.color }} />
                    <span style={{ fontWeight: 600, fontSize: 14, letterSpacing: '-0.01em' }}>{e.name}</span>
                    {e.certified ? (
                      <span className="tag pos" style={{ marginLeft: 'auto' }}>Certified</span>
                    ) : (
                      <span className="tag warn" style={{ marginLeft: 'auto' }}>Not certified</span>
                    )}
                  </div>
                  <div className="muted size-12 mb-12">{e.tagline}</div>
                  <div className="row gap-16 tabular size-12 muted">
                    <span><span style={{ color: 'var(--ink)' }}>{e.count}</span> live</span>
                    <span><span style={{ color: 'var(--ink)' }}>{e.won}</span> won</span>
                    <span>avg {fmtMoney(e.avgCommission)}</span>
                  </div>
                </button>
              ))}
            </div>
          </Card>

          {/* Recent activity */}
          <Card
            title="Recent referrals"
            action={<Button variant="ghost" size="sm" onClick={() => onNav('pipeline')} trailing={<Icon.Chevron size={12} />}>View pipeline</Button>}
            pad={false}
          >
            <table className="tbl">
              <thead>
                <tr>
                  <th>Lead</th>
                  <th>Entity</th>
                  <th>Stage</th>
                  <th>Progress</th>
                  <th className="right">Potential</th>
                </tr>
              </thead>
              <tbody>
                {recent.map(r => {
                  const ent = window.JFJ.ENTITY_BY_ID[r.entity];
                  const stage = window.JFJ.STAGE_BY_ID[r.stage];
                  return (
                    <tr key={r.id} onClick={() => onNav('pipeline')} style={{ cursor: 'pointer' }}>
                      <td>
                        <div style={{ fontWeight: 500 }}>{r.name}</div>
                        <div className="muted size-12">{r.company}</div>
                      </td>
                      <td><EntityChip entity={ent} /></td>
                      <td><StagePill stage={stage} won={r.stage === 'won'} /></td>
                      <td style={{ width: 140 }}><StageBar currentStageId={r.stage} won={r.stage === 'won'} stalled={r.stalled} /></td>
                      <td className="right num">{fmtMoney(r.potential)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </Card>
        </div>

        {/* Right column */}
        <div className="col gap-16">
          {/* Mini leaderboard */}
          <Card
            title="Leaderboard · May"
            action={<Button variant="ghost" size="sm" onClick={() => onNav('leaderboard')} trailing={<Icon.Chevron size={12} />}>Full board</Button>}
            pad={false}
          >
            {LEADERBOARD.slice(0, 7).map(r => {
              const max = LEADERBOARD[0].gmv;
              return (
                <div key={r.rank} className={`lb-row ${r.you ? 'you' : ''}`}>
                  <div className={`lb-rank ${r.rank <= 3 ? 'top' : ''} ${r.rank === 2 ? 'r2' : ''} ${r.rank === 3 ? 'r3' : ''}`}>{r.rank}</div>
                  <div className="lb-name">
                    <div className="col">
                      <div style={{ fontWeight: 500, fontSize: 13 }}>{r.name}</div>
                      <div className="lb-handle">{r.handle}</div>
                    </div>
                  </div>
                  <div className="lb-bar"><div style={{ width: `${(r.gmv / max) * 100}%` }} /></div>
                  <div className="lb-gmv">{fmtMoney(r.gmv)}</div>
                </div>
              );
            })}
          </Card>

          {/* Announcements */}
          <Card
            title="Announcements"
            action={<Button variant="ghost" size="sm" onClick={() => onNav('announcements')} trailing={<Icon.Chevron size={12} />}>All</Button>}
            pad={false}
          >
            {ANNOUNCEMENTS.slice(0, 3).map(a => (
              <div key={a.id} className={`ann-row ${a.priority}`}>
                <div className="ann-icon"><Icon.Megaphone size={16} /></div>
                <div className="col" style={{ flex: 1, minWidth: 0 }}>
                  <div className="ann-title">{a.title}</div>
                  <div className="ann-meta">{a.from.toUpperCase()} · {a.ts}</div>
                  <div className="ann-body" style={{ overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>{a.body}</div>
                </div>
              </div>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
};

// ============== ENTITY WORKSPACE ==============
const EntityWorkspace = ({ entityId, onNav, onBack }) => {
  const entity = window.JFJ.ENTITY_BY_ID[entityId];
  const [tab, setTab] = useState('overview');
  const training = window.JFJ.TRAINING[entityId];
  const myRefs = window.JFJ.REFERRALS.filter(r => r.entity === entityId);
  const myAssets = window.JFJ.ASSETS.filter(a => a.entity === entityId);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="crumbs">
            <button onClick={onBack}>Dashboard</button>
            <Icon.Chevron size={12} />
            <span>Entities</span>
            <Icon.Chevron size={12} />
            <span style={{ color: 'var(--ink)' }}>{entity.name}</span>
          </div>
          <div className="row middle gap-12">
            <span style={{ width: 12, height: 12, borderRadius: 3, background: entity.color }} />
            <h1>{entity.name}</h1>
            {entity.certified && <span className="tag pos">Certified</span>}
          </div>
          <p className="mt-12" style={{ maxWidth: 560 }}>{entity.tagline}. {entity.payoutModel}. Average deal closes in {entity.avgDealCycle}.</p>
        </div>
        <div className="page-actions">
          {entity.certified ? (
            <Button variant="primary" leading={<Icon.Link size={14} />} onClick={() => onNav('linkgen')}>Get my link</Button>
          ) : (
            <Button variant="primary" leading={<Icon.Bolt size={14} />} onClick={() => setTab('training')}>Start certification</Button>
          )}
          <Button variant="secondary" leading={<Icon.Folder size={14} />} onClick={() => setTab('assets')}>Assets</Button>
        </div>
      </div>

      <div className="tabs">
        {[
          { id: 'overview', label: 'Overview' },
          { id: 'training', label: `Training${entity.certified ? ' ✓' : ''}` },
          { id: 'assets', label: `Assets · ${myAssets.length}` },
          { id: 'pipeline', label: `My pipeline · ${myRefs.length}` },
        ].map(t => (
          <button key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>{t.label}</button>
        ))}
      </div>

      {tab === 'overview' && <EntityOverview entity={entity} myRefs={myRefs} training={training} onTab={setTab} />}
      {tab === 'training' && <EntityTraining entity={entity} training={training} onNav={onNav} />}
      {tab === 'assets' && <AssetsList assets={myAssets} entity={entity} />}
      {tab === 'pipeline' && <EntityPipeline myRefs={myRefs} />}
    </div>
  );
};

const EntityOverview = ({ entity, myRefs, training, onTab }) => {
  const won = myRefs.filter(r => r.stage === 'won').length;
  const live = myRefs.filter(r => r.stage !== 'won').length;
  const myEarned = myRefs.filter(r => r.stage === 'won').reduce((a, r) => a + r.potential, 0);
  const myPending = myRefs.filter(r => r.stage !== 'won').reduce((a, r) => a + r.potential, 0);

  return (
    <div className="grid grid-7-5">
      <div className="col gap-16">
        <div className="kpi-row">
          <KPI label="My earned" value={fmtMoney(myEarned)} sub={`${won} closed deals`} accent="var(--accent)" />
          <KPI label="My pending" value={fmtMoney(myPending)} sub={`${live} in flight`} />
          <KPI label="Avg payout" value={fmtMoney(entity.avgCommission)} sub={entity.payoutModel} />
          <KPI label="Avg cycle" value={entity.avgDealCycle} sub="lead → won" mono={false} />
        </div>

        <Card title="What you're selling" action={<Button variant="ghost" size="sm">Watch deck (12 min)</Button>}>
          <div className="col gap-12">
            <div>
              <h2 style={{ fontSize: 16, marginBottom: 8 }}>The pitch in 30 seconds</h2>
              <p style={{ fontSize: 13.5, lineHeight: 1.6 }}>
                {entity.id === 'trusts' && 'Most high earners have an LLC and a will. Neither protects them from a creditor or a probate fight. A properly-structured trust does both, and it sets up generational wealth transfer at the same time. JFJ Trusts handles the legal architecture end-to-end with attorneys in 47 states.'}
                {entity.id === 'tax' && 'A CPA files. A tax strategist plans. JFJ Tax Strategy works with business owners netting $500k+ to legally reduce effective tax rate by 8–14 points using structures most CPAs are too busy (or too cautious) to recommend. Engagements pay for themselves in year one or we refund.'}
                {entity.id === 'consulting' && 'Founders hit a ceiling around $5M ARR. JFJ Consulting parachutes in a fractional COO + GTM team for 6 months to break the ceiling. Fixed retainer, fixed scope, no fluff decks.'}
                {entity.id === 'leadgen' && 'B2B sales teams burn 60% of rep time on prospecting. JFJ Lead Gen replaces that with a done-for-you appointment-setting team using JFJ\'s proprietary outbound playbook. Pay only for qualified, showed-up appointments.'}
              </p>
            </div>
            <div className="divider" />
            <div className="grid grid-2">
              <div>
                <div className="muted size-12 mb-8">Who it's for</div>
                <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.7 }}>
                  {entity.id === 'trusts' && <><li>Net worth $1M+</li><li>Owns a business or real estate</li><li>Has children or wants legacy</li></>}
                  {entity.id === 'tax' && <><li>Profits $500k+/yr</li><li>S-corp, C-corp, or 1099</li><li>Files in CA, NY, TX, FL</li></>}
                  {entity.id === 'consulting' && <><li>$2M–$20M ARR</li><li>Founder-led, sub-50 employees</li><li>Stuck on growth or ops</li></>}
                  {entity.id === 'leadgen' && <><li>B2B with $5k+ ACV</li><li>In-house SDR team or none</li><li>Outbound-friendly market</li></>}
                </ul>
              </div>
              <div>
                <div className="muted size-12 mb-8">Disqualifiers</div>
                <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.7 }}>
                  {entity.id === 'trusts' && <><li>W-2 only, &lt;$200k</li><li>No assets to protect</li><li>Existing trust they're happy with</li></>}
                  {entity.id === 'tax' && <><li>W-2 only</li><li>Profits below $250k</li><li>Already with a strategist</li></>}
                  {entity.id === 'consulting' && <><li>Pre-revenue</li><li>VC-controlled</li><li>Not the decision-maker</li></>}
                  {entity.id === 'leadgen' && <><li>Pre-product-market-fit</li><li>B2C only</li><li>&lt;$1k ACV</li></>}
                </ul>
              </div>
            </div>
          </div>
        </Card>
      </div>

      <div className="col gap-16">
        <Card title="Your certification">
          <div className="col gap-12">
            <div className="row middle between">
              <div className="size-13">{Math.round((training?.progress || 0) * 100)}% complete</div>
              <div className="muted size-12 tabular">
                {training?.modules.filter(m => m.done).length}/{training?.modules.length} modules
              </div>
            </div>
            <div className="rail-cert-bar">
              <div style={{ width: `${(training?.progress || 0) * 100}%` }} />
            </div>
            <Button variant={entity.certified ? 'secondary' : 'primary'} full onClick={() => onTab('training')}>
              {entity.certified ? 'Review training' : 'Continue training'}
            </Button>
          </div>
        </Card>

        <Card title="Your link" pad={false}>
          <div style={{ padding: 16 }}>
            <div className="link-display">
              <Icon.Link size={14} />
              <span className="link-url">jfj.aff/{entity.id}/ryanm</span>
              <button className="icon-btn" title="Copy"><Icon.Copy size={14} /></button>
            </div>
            <div className="row gap-8 mt-12">
              <Button variant="secondary" size="sm" full leading={<Icon.Mail size={12} />}>Email</Button>
              <Button variant="secondary" size="sm" full leading={<Icon.Phone size={12} />}>SMS</Button>
            </div>
          </div>
        </Card>

        <Card title="Top objections" pad={false}>
          <div>
            {[
              { q: '"It\'s too expensive"', uses: 504 },
              { q: '"I need to think about it"', uses: 318 },
              { q: '"My CPA / lawyer handles this"', uses: 274 },
            ].map((o, i) => (
              <div key={i} className="row middle between" style={{ padding: '12px 18px', borderTop: i ? '1px solid var(--line-2)' : 'none' }}>
                <div className="size-13">{o.q}</div>
                <div className="muted size-12 tabular">{o.uses}×</div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
};

const EntityTraining = ({ entity, training, onNav }) => {
  if (!training) return <div>No training available.</div>;
  return (
    <div className="grid grid-7-5">
      <Card title="Modules" pad={false}>
        {training.modules.map((m, i) => (
          <div key={m.id} className={`module-row ${m.done ? 'done' : ''} ${m.current ? 'current' : ''} ${m.locked ? 'locked' : ''}`}>
            <div className="module-num">
              {m.done ? <Icon.Check size={14} /> : m.locked ? <Icon.Lock size={12} /> : i + 1}
            </div>
            <div className="col" style={{ flex: 1 }}>
              <div className="module-title">{m.title}</div>
              {m.isQuiz && <div className="muted size-12">Required for certification</div>}
            </div>
            <div className="module-meta">{m.length}</div>
            {m.current && (
              <Button variant="primary" size="sm" leading={<Icon.Play size={10} />} onClick={() => m.isQuiz ? onNav('quiz') : null}>
                {m.isQuiz ? 'Take quiz' : 'Resume'}
              </Button>
            )}
            {m.done && !m.isQuiz && (
              <Button variant="ghost" size="sm">Replay</Button>
            )}
            {m.done && m.isQuiz && (
              <span className="tag pos">Passed · 9/10</span>
            )}
          </div>
        ))}
      </Card>

      <div className="col gap-16">
        <Card title="Why certify?">
          <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.8, color: 'var(--ink-2)' }}>
            <li>Unlock your unique referral link</li>
            <li>Access pre-approved scripts & templates</li>
            <li>Get listed in the partner directory</li>
            <li>Eligible for monthly contests + bonuses</li>
            <li>Compliance: only certified affiliates can pitch</li>
          </ul>
        </Card>

        <Card title="Office hours">
          <div className="col gap-8">
            <div className="size-13">Live Q&A with the {entity.short} team every Thursday, 2pm CT.</div>
            <Button variant="secondary" leading={<Icon.Clock size={12} />}>Add to calendar</Button>
          </div>
        </Card>
      </div>
    </div>
  );
};

const EntityPipeline = ({ myRefs }) => {
  if (myRefs.length === 0) {
    return <div className="muted" style={{ padding: 40, textAlign: 'center' }}>No referrals yet.</div>;
  }
  return (
    <Card pad={false}>
      <table className="tbl">
        <thead>
          <tr>
            <th>Lead</th><th>Stage</th><th>Progress</th><th>Days</th><th className="right">Potential</th>
          </tr>
        </thead>
        <tbody>
          {myRefs.map(r => {
            const stage = window.JFJ.STAGE_BY_ID[r.stage];
            return (
              <tr key={r.id}>
                <td>
                  <div style={{ fontWeight: 500 }}>{r.name}</div>
                  <div className="muted size-12">{r.company}</div>
                </td>
                <td><StagePill stage={stage} won={r.stage === 'won'} /></td>
                <td style={{ width: 160 }}><StageBar currentStageId={r.stage} won={r.stage === 'won'} stalled={r.stalled} /></td>
                <td className="num">{r.days}d {r.stalled && <span className="tag warn" style={{ marginLeft: 6 }}>Stalled</span>}</td>
                <td className="right num">{fmtMoney(r.potential)}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </Card>
  );
};

const AssetsList = ({ assets, entity }) => (
  <div className="grid" style={{ gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
    {assets.map(a => (
      <div key={a.id} className="asset-card">
        <div className="row middle between">
          <div className="row gap-10 middle">
            <span className="asset-kind">{a.kind}</span>
            {entity && <span className="muted size-12">·</span>}
            {entity && <EntityChip entity={entity} />}
          </div>
          <button className="icon-btn"><Icon.Copy size={14} /></button>
        </div>
        <div className="asset-title">{a.title}</div>
        <div className="asset-copy">{a.copy}</div>
        <div className="asset-foot">
          <span>Used {a.uses}× by team</span>
          <Button variant="ghost" size="sm" trailing={<Icon.Chevron size={12} />}>Open</Button>
        </div>
      </div>
    ))}
  </div>
);

// ============== QUIZ ==============
const Quiz = ({ onExit }) => {
  const quiz = window.JFJ.QUIZ;
  const entity = window.JFJ.ENTITY_BY_ID[quiz.entityId];
  const [qIdx, setQIdx] = useState(0);
  const [answers, setAnswers] = useState({});
  const [done, setDone] = useState(false);

  const q = quiz.questions[qIdx];
  const total = quiz.questions.length;
  const selected = answers[qIdx];

  const advance = () => {
    if (qIdx < total - 1) setQIdx(qIdx + 1);
    else setDone(true);
  };

  const score = Object.entries(answers).filter(([i, a]) => quiz.questions[+i].correct === a).length;

  if (done) {
    const passed = score / total >= 0.7;
    return (
      <div className="page">
        <div className="quiz-shell" style={{ textAlign: 'center', paddingTop: 40 }}>
          <div style={{
            width: 80, height: 80, borderRadius: '50%', margin: '0 auto 24px',
            background: passed ? 'var(--accent-soft)' : 'var(--surface-2)',
            color: passed ? 'var(--accent-on-soft)' : 'var(--ink-2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {passed ? <Icon.Check size={36} /> : <Icon.Alert size={36} />}
          </div>
          <h1>{passed ? `You're certified for ${entity.short}.` : 'Almost there.'}</h1>
          <p className="mt-12" style={{ maxWidth: 460, margin: '12px auto' }}>
            You scored {score}/{total} ({Math.round((score / total) * 100)}%). {passed ? 'Your referral link is unlocked. Go close some deals.' : 'You need 70% to pass. Review the materials and retry.'}
          </p>
          <div className="row gap-8 center mt-24">
            <Button variant="secondary" onClick={onExit}>Back to entity</Button>
            {passed
              ? <Button variant="primary" leading={<Icon.Link size={14} />}>Get my link</Button>
              : <Button variant="primary" onClick={() => { setQIdx(0); setAnswers({}); setDone(false); }}>Retry quiz</Button>
            }
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page">
      <div className="quiz-shell">
        <div className="row middle between mb-16">
          <div className="row middle gap-10">
            <EntityChip entity={entity} size="md" />
            <span className="muted size-13">{quiz.title}</span>
          </div>
          <Button variant="ghost" size="sm" onClick={onExit}>Save & exit</Button>
        </div>
        <div className="quiz-progress">
          {quiz.questions.map((_, i) => (
            <div key={i} className={i < qIdx ? 'done' : i === qIdx ? 'current' : ''} />
          ))}
        </div>
        <div className="muted size-12 mb-12 tabular">Question {qIdx + 1} of {total}</div>
        <div className="quiz-q">{q.q}</div>
        <div className="col gap-8">
          {q.options.map((opt, i) => (
            <label key={i} className={`quiz-opt ${selected === i ? 'selected' : ''}`}>
              <input type="radio" name={`q${qIdx}`} checked={selected === i} onChange={() => setAnswers({ ...answers, [qIdx]: i })} style={{ display: 'none' }} />
              <div className="quiz-opt-letter">{String.fromCharCode(65 + i)}</div>
              <div>{opt}</div>
            </label>
          ))}
        </div>
        <div className="row between mt-24">
          <Button variant="ghost" disabled={qIdx === 0} onClick={() => setQIdx(Math.max(0, qIdx - 1))}>Back</Button>
          <Button variant="primary" disabled={selected === undefined} onClick={advance} trailing={<Icon.Chevron size={14} />}>
            {qIdx === total - 1 ? 'Submit' : 'Next'}
          </Button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Dashboard, EntityWorkspace, Quiz });
