/* atelier onboarding — app shell + state */
const { useState: useS, useEffect: useE, useRef: useR } = React;

const EMPTY_ANSWERS = { style: [], fit: [], colors: [], painPoint: null, firstFeature: null };

function makeReferralCode() {
  const alpha = 'abcdefghijklmnopqrstuvwxyz0123456789';
  const rand4 = Array.from({ length: 4 }, () => alpha[Math.floor(Math.random() * alpha.length)]).join('');
  return 'atlr-' + rand4;
}

function initSignup() {
  const params = new URLSearchParams(location.search);

  // Detect referral from ?ref= param or /r/ path and store it
  const refParam =
    params.get('ref') ||
    (location.pathname.match(/\/r\/([a-z0-9-]+)/i) || [])[1] ||
    null;
  if (refParam) {
    try { localStorage.setItem('atelier_ref', refParam); } catch (e) {}
  }

  // Reuse existing signup if already generated — preserves queue_position and referral_code
  try {
    const stored = JSON.parse(localStorage.getItem('atelier_signup') || 'null');
    if (stored?.referral_code) return stored;
  } catch (e) {}

  // Generate fresh values for a first-time visitor
  const isReferred = !!(refParam || (() => { try { return localStorage.getItem('atelier_ref'); } catch (e) { return null; } })());
  const basePos = 2400 + Math.floor(Math.random() * 701); // 2400–3100
  const queuePosition = isReferred
    ? Math.max(1, basePos - (15 + Math.floor(Math.random() * 21))) // bump 15–35 places up the list
    : basePos;
  const referralCode = makeReferralCode();

  return {
    firstName: '',
    email: '',
    authMethod: null,
    emailCapturedAt: null,
    answers: { ...EMPTY_ANSWERS },
    skipped: [],
    ctaSource: params.get('cta') || 'direct',
    startedAt: new Date().toISOString(),
    completedAt: null,
    queue_position: queuePosition,
    referral_code: referralCode,
    referral_link: 'myatelier.io/r/' + referralCode,
  };
}

function persist(signup) {
  window.__atelierSignup = signup;
  try { localStorage.setItem('atelier_signup', JSON.stringify(signup)); } catch (e) {}
}

function App() {
  const [phase, setPhase] = useS('account');
  const [qIndex, setQIndex] = useS(0);
  const [dir, setDir] = useS(1);
  const [signup, setSignup] = useS(initSignup);
  const cardRef = useR(null);

  useE(() => { persist(signup); }, [signup]);

  useE(() => {
    const t = setTimeout(() => {
      const el = document.getElementById('firstName');
      if (el) el.focus();
    }, 480);
    return () => clearTimeout(t);
  }, []);

  useE(() => {
    function onKey(e) { if (e.key === 'Escape') closeFlow(); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  function closeFlow() { window.location.href = '/'; }

  function patchSignup(patch) { setSignup((s) => ({ ...s, ...patch })); }

  function toggleMulti(qid, value) {
    setSignup((s) => {
      const cur = s.answers[qid];
      const next = cur.includes(value) ? cur.filter((v) => v !== value) : [...cur, value];
      return { ...s, answers: { ...s.answers, [qid]: next }, skipped: s.skipped.filter((id) => id !== qid) };
    });
  }
  function setSingle(qid, value) {
    setSignup((s) => ({
      ...s,
      answers: { ...s.answers, [qid]: value },
      skipped: s.skipped.filter((id) => id !== qid),
    }));
  }

  function reachAccountConversion(method) {
    setSignup((s) => {
      const next = { ...s, authMethod: method, emailCapturedAt: s.emailCapturedAt || new Date().toISOString() };
      if (method !== 'email' && !next.email) next.email = '';
      persist(next);
      return next;
    });
    console.log('[atelier] conversion · email captured via ' + method);
    setDir(1); setPhase('quiz'); setQIndex(0);
  }

  function quizNext() {
    if (qIndex < QUESTIONS.length - 1) { setDir(1); setQIndex(qIndex + 1); }
    else finish();
  }
  function quizSkip() {
    const qid = QUESTIONS[qIndex].id;
    setSignup((s) => ({
      ...s,
      skipped: s.skipped.includes(qid) ? s.skipped : [...s.skipped, qid],
    }));
    quizNext();
  }
  function finish() {
    setSignup((s) => { const next = { ...s, completedAt: new Date().toISOString() }; persist(next); return next; });
    console.log('[atelier] signup complete', window.__atelierSignup);
    setDir(1); setPhase('confirm');
  }

  function goBack() {
    if (phase === 'quiz') {
      if (qIndex === 0) { setDir(-1); setPhase('account'); }
      else { setDir(-1); setQIndex(qIndex - 1); }
    } else if (phase === 'confirm') {
      setDir(-1); setPhase('quiz'); setQIndex(QUESTIONS.length - 1);
    }
  }

  const showProgress = phase === 'quiz';
  const showBack = phase === 'quiz';
  const pct = showProgress ? ((qIndex + 1) / QUESTIONS.length) * 100 : 0;

  return (
    <div className="stage">
      <div className={'card' + (phase === 'confirm' ? ' is-wide' : '')} ref={cardRef} role="dialog" aria-modal="true" aria-label="Join atelier early access">
        <div className="card-top">
          {showBack
            ? <button className="icon-btn back" onClick={goBack} aria-label="Back"><Icon.back /> Back</button>
            : <Mark />}
          <div className="top-actions">
            <button className="icon-btn" onClick={closeFlow} aria-label="Close"><Icon.close /></button>
          </div>
        </div>

        {showProgress && (
          <div className="progress-wrap">
            <div className="progress-row">
              <span className="eyebrow"><span className="dot"></span>Style quiz</span>
              <span className="progress-count"><b>{qIndex + 1}</b>/{QUESTIONS.length}</span>
            </div>
            <div className="progress-track"><div className="progress-fill" style={{ width: pct + '%' }}></div></div>
          </div>
        )}

        {phase === 'account' && (
          <AccountStep
            data={signup}
            setData={patchSignup}
            onContinue={() => reachAccountConversion('email')}
            onSocial={(m) => reachAccountConversion(m)}
          />
        )}

        {phase === 'quiz' && (
          <QuizStep
            index={qIndex}
            dir={dir}
            data={signup}
            toggleMulti={toggleMulti}
            setSingle={setSingle}
            onNext={quizNext}
            onSkip={quizSkip}
          />
        )}

        {phase === 'confirm' && (
          <ConfirmStep
            data={signup}
            queuePos={signup.queue_position}
            refCode={signup.referral_code}
            onExplore={closeFlow}
          />
        )}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
