// onboarding.jsx — 5-step first-run flow that recommends the right tier.

const OB_STEPS = [
  { label: 'Subjects',  done: true,  text: '4 picked' },
  { label: 'Year',      done: true,  text: 'Year 12 · 2026' },
  { label: 'Goals',     done: true,  text: 'Target 95+' },
  { label: 'Style',     active: true, text: 'How you study' },
  { label: 'Plan',      text: 'Get matched' },
];

const OB_TIER_MAP = {
  solo:  { tier: 'free',  label: 'Solo',  price: '$0',  priceSub: '· free forever',  why: 'You learn best alone with good tools — our question bank, AI Marker, and Mastery Map are yours at no cost. Upgrade any time if you want a human in your corner.', includes: ['Full question bank · all subjects', 'AI Marker · 10 extended responses/mo', 'Mastery Map · read-only', 'Weekly Challenge access'] },
  group: { tier: 'class', label: 'Class', price: '$59', priceSub: '/mo · $15/wk · cancel any time', why: 'You picked group lessons help, you\'re aiming 95+ (you need 2.6 ATAR points to break Biomedical\'s cutoff), and your weak dots are concentrated in Module 7 — exactly where Theo Park runs his Wednesday workshop.', includes: ['1 live group lesson / wk · 50 min · tutor-led', 'Unlimited AI Marker · extended responses', 'Full Mastery Map · all 4 subjects', '2 tutor-marked assignments / wk · 24h reply', 'Peer Focus Rooms · unlimited'] },
  '1on1':{ tier: 'coach', label: 'Coach', price: '$169', priceSub: '/mo · cancel any time', why: 'You want focused, personal attention. A dedicated tutor builds a session plan around your exact weak spots and meets you 1-on-1 every week — no group, no waiting, no generic advice.', includes: ['1× 50-min 1-on-1 with your tutor every week', 'Unlimited group sessions', 'Unlimited AI Marker', 'Full Mastery Map · all 4 subjects', 'Private tutor chat · ~3h reply time'] },
};

function Onboarding() {
  const [style, setStyle] = React.useState('group');
  const [pending, setPending] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  function showToast(msg, ok = true) {
    setToast({ msg, ok });
    setTimeout(() => setToast(null), 3500);
  }

  async function handleSeePlan() {
    const sb = window.HSC && window.HSC.supabase;
    if (!sb) { window.location.href = '/subjects/'; return; }

    const { data: { user } } = await sb.auth.getUser();
    if (!user) { window.location.href = '/auth/login.html?next=' + encodeURIComponent(window.location.href); return; }

    const { tier } = OB_TIER_MAP[style];
    setPending(true);

    const params = new URLSearchParams(window.location.search);
    const tutorId = params.get('tutor_id') || undefined;

    const row = { user_id: user.id, tier, status: tier === 'free' ? 'active' : 'trialing' };
    if (tutorId) row.tutor_id = tutorId;

    const { error } = await sb.from('subscriptions').upsert(row, { onConflict: tutorId ? 'user_id,tutor_id' : 'user_id' });
    setPending(false);

    if (error) { showToast('Could not save — try again.', false); return; }
    showToast('All set! Taking you to your dashboard…');
    setTimeout(() => { window.location.href = '/subjects/'; }, 1400);
  }

  const rec = OB_TIER_MAP[style];

  return (
    <div className="tier-screen wc-scope">
      {toast && (
        <div style={{ position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)', background: toast.ok ? '#1a3a2a' : '#3a1a1a', color: '#fff', padding: '10px 20px', borderRadius: 10, fontSize: 13, fontWeight: 600, zIndex: 9999, pointerEvents: 'none', boxShadow: '0 4px 16px rgba(0,0,0,0.25)' }}>
          {toast.msg}
        </div>
      )}

      <div className="ob-wrap">
        {/* Stepper */}
        <div className="ob-stepper">
          <div className="ob-brand">
            <span className="ob-brand-mark">H</span>
            HSCScience · setting you up
          </div>
          <div className="ob-steps">
            {OB_STEPS.map((s, i) => (
              <div key={i} className={`ob-step ${s.done ? 'done' : ''} ${s.active ? 'active' : ''}`}>
                <div className="ob-step-num">{s.done ? <Icon name="check" style={{ width: 12, height: 12 }}/> : i + 1}</div>
                <div className="ob-step-text">
                  <strong>STEP {i + 1}</strong>
                  {s.label}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Body */}
        <div className="ob-body">
          {/* Left: current step + summary of past answers */}
          <div className="ob-step-shell">
            <div className="ob-eye">STEP 4 · ALMOST THERE</div>
            <h2>How do you<br/>study <em>best</em>?</h2>
            <p>Last question. Your answer changes which tier we suggest — the rest of the platform stays the same. You can always switch later.</p>

            <div className="ob-pick">
              <div className="ob-pick-q">Pick the option that fits you most.</div>
              <div className="ob-pick-opts">
                <div className={`ob-opt ${style === 'solo' ? 'active' : ''}`} onClick={() => setStyle('solo')} style={{ cursor: 'pointer' }}>
                  {style === 'solo' && <div className="ob-opt-tick"><Icon name="check"/></div>}
                  <div className="ob-opt-emoji">🎯</div>
                  <div className="ob-opt-name">Solo · self-paced</div>
                  <div className="ob-opt-sub">"I'd rather grind alone with good tools"</div>
                </div>

                <div className={`ob-opt ${style === 'group' ? 'active' : ''}`} onClick={() => setStyle('group')} style={{ cursor: 'pointer' }}>
                  {style === 'group' && <div className="ob-opt-tick"><Icon name="check"/></div>}
                  <div className="ob-opt-emoji">👥</div>
                  <div className="ob-opt-name">Group lessons help</div>
                  <div className="ob-opt-sub">"I like hearing a teacher explain things & seeing classmates' Qs"</div>
                </div>

                <div className={`ob-opt ${style === '1on1' ? 'active' : ''}`} onClick={() => setStyle('1on1')} style={{ cursor: 'pointer' }}>
                  {style === '1on1' && <div className="ob-opt-tick"><Icon name="check"/></div>}
                  <div className="ob-opt-emoji">🧑‍🏫</div>
                  <div className="ob-opt-name">1-on-1 is best</div>
                  <div className="ob-opt-sub">"I want a tutor focused only on me & my weak spots"</div>
                </div>
              </div>
            </div>

            <div className="ob-summary">
              <h4>Your answers so far</h4>
              <dl>
                <div className="ob-sum-row">
                  <dt>Subjects</dt>
                  <dd>Biology, Chemistry, Maths Adv., English Adv.</dd>
                </div>
                <div className="ob-sum-row">
                  <dt>Year & cohort</dt>
                  <dd>Year 12 · Riverside High · Class of 2026</dd>
                </div>
                <div className="ob-sum-row">
                  <dt>Current trajectory</dt>
                  <dd>B5 average · predicted ATAR <em>92.4</em></dd>
                </div>
                <div className="ob-sum-row">
                  <dt>Where you want to be</dt>
                  <dd>ATAR <em>95+</em> · Biomedical Science (USYD)</dd>
                </div>
              </dl>
            </div>

            <div className="ob-actions">
              <button type="button" className="ob-back"><Icon name="chevronR" style={{ width: 12, height: 12, transform: 'rotate(180deg)', marginRight: 6, verticalAlign: -2 }}/> Back</button>
              <button type="button" className="ob-next" disabled={pending} onClick={handleSeePlan}>
                {pending ? 'Saving…' : 'See my plan'} {!pending && <Icon name="chevronR"/>}
              </button>
            </div>
          </div>

          {/* Right: live recommendation */}
          <div className="ob-reveal">
            <div className="ob-reveal-card">
              <div className="ob-reveal-eye">★ YOUR MATCH</div>
              <h3>We'd start you on <em>{rec.label}</em></h3>
              <div className="ob-reveal-price">
                <strong>{rec.price}</strong>{rec.priceSub && <small>{rec.priceSub}</small>}
              </div>
              <div className="ob-reveal-because">
                <h5>WHY THIS TIER</h5>
                {rec.why}
              </div>
            </div>

            <div className="ob-included">
              <h5>What's included on {rec.label}</h5>
              {rec.includes.map((item, i) => {
                const [bold, ...rest] = item.split(' · ');
                return (
                  <div key={i} className="ob-incl-row">
                    <Icon name="check"/>
                    <span><strong>{bold}</strong></span>
                    {rest.length > 0 && <em>{rest.join(' · ')}</em>}
                  </div>
                );
              })}
            </div>

            <div className="ob-alt">
              Not quite right? <a href="#" onClick={e => { e.preventDefault(); setStyle('solo'); }}>Try Solo ($0) →</a> &nbsp;·&nbsp; <a href="#" onClick={e => { e.preventDefault(); setStyle('1on1'); }}>Or Coach ($169/mo) →</a><br/>
              {rec.tier !== 'free' && <span style={{ color: 'var(--adv-green)', fontWeight: 700 }}>First week is on us</span>}
              {rec.tier !== 'free' && ' — no card required to try.'}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Onboarding = Onboarding;
