/* atelier onboarding — step screens */
const { useState, useRef } = React;

// ─── STEP 1 · Account creation ─────────────────────────────
function AccountStep({ data, setData, onContinue, onSocial }) {
  const [touched, setTouched] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const [showSocialToast, setShowSocialToast] = useState(false);
  const emailRef = useRef(null);
  const toastTimerRef = useRef(null);

  function handleSocial() {
    setShowSocialToast(true);
    if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
    toastTimerRef.current = setTimeout(() => setShowSocialToast(false), 3000);
    setTimeout(() => {
      if (emailRef.current) {
        emailRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
        emailRef.current.focus({ preventScroll: true });
      }
    }, 180);
  }

  const email = data.email || '';
  const name = data.firstName || '';
  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const showErr = touched && email.length > 0 && !emailValid;

  async function submit(e) {
    e && e.preventDefault();
    setTouched(true);
    if (!emailValid) {
      emailRef.current && emailRef.current.focus();
      return;
    }
    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: email.trim(),
          name: name.trim(),
          queue_position: data.queue_position,
          referral_code: data.referral_code,
        }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || 'Something went wrong. Please try again.');
      }
      onContinue();
    } catch (err) {
      setSubmitError(err.message || 'Could not save your spot — please try again.');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="card-body step-anim">
      <span className="eyebrow"><span className="dot"></span>About 20 seconds</span>
      <h1 className="serif-h h-lg" style={{ marginTop: 12 }}>
        Let's build your <em>wardrobe.</em>
      </h1>
      <p className="lede">Save anything, snap what you own, and get a stylist's read on the whole closet.</p>

      <div className="auth-stack" style={{ marginTop: 26 }}>
        <button className="auth-btn" onClick={handleSocial}>
          <Icon.google /> Continue with Google
        </button>
        <button className="auth-btn" onClick={handleSocial}>
          <Icon.apple /> Continue with Apple
        </button>
      </div>

      <div className="divider"><span>or with email</span></div>

      <form onSubmit={submit} noValidate>
        <div className="field">
          <label htmlFor="firstName">First name</label>
          <div className="control">
            <input
              id="firstName" type="text" autoComplete="given-name"
              placeholder="Cosima"
              value={name}
              onChange={(e) => setData({ firstName: e.target.value })}
            />
          </div>
        </div>

        <div className={'field ' + (showErr ? 'invalid' : (emailValid ? 'valid' : ''))}>
          <label htmlFor="email">Email</label>
          <div className="control">
            <input
              id="email" ref={emailRef} type="email" autoComplete="email" inputMode="email"
              placeholder="you@email.com"
              value={email}
              onChange={(e) => setData({ email: e.target.value })}
              onBlur={() => setTouched(true)}
            />
            <span className="tick"><Icon.tick /></span>
          </div>
          {showErr && <div className="field-msg">Enter a valid email so we can save your spot.</div>}
          <p style={{ margin: '8px 0 0', fontSize: '11.5px', color: 'var(--text-3)', lineHeight: 1.5 }}>
            We'll only email you about early access. Contact data is processed by Resend&nbsp;(US).{' '}
            <a href="/privacy" style={{ color: 'var(--text-2)', textDecoration: 'underline', textUnderlineOffset: '2px' }}>See our Privacy Notice</a>.
          </p>
        </div>

        {submitError && (
          <div className="field-msg" style={{ marginBottom: '10px' }}>{submitError}</div>
        )}

        <div className="step-foot">
          <PrimaryButton type="submit" disabled={!emailValid || submitting}>
            {submitting ? 'Saving…' : 'Continue'}
          </PrimaryButton>
        </div>
      </form>

      <div className="social-proof">
        <span className="avatars">
          <span style={{ background: '#C19A6B' }}></span>
          <span style={{ background: '#5C5F3F' }}></span>
          <span style={{ background: '#1F2A3C' }}></span>
        </span>
        Joining <b>3,200+</b> early shoppers.
      </div>

      <p className="fineprint">
        By continuing you agree to our <a href="#terms">Terms</a> and <a href="/privacy">Privacy Notice</a>.
        No spam — just one note when early access opens.
      </p>

      {showSocialToast && (
        <div className="social-toast" onClick={() => setShowSocialToast(false)}>
          <span className="social-toast-dot"></span>
          Google / Apple sign-in coming at launch — join the waitlist with your email for now
        </div>
      )}
    </div>
  );
}

// ─── STEP 2 · Style quiz ───────────────────────────────────
function QuizStep({ index, dir, data, toggleMulti, setSingle, onNext, onSkip }) {
  const q = QUESTIONS[index];
  const answer = data.answers[q.id];
  const hasAnswer = Array.isArray(answer) ? answer.length > 0 : !!answer;

  return (
    <div className={'card-body tight-top q-anim ' + (dir < 0 ? 'back' : '')} key={q.id}>
      <div className="q-head">
        <h2 className="serif-h h-md">{q.title}</h2>
        {q.sub && <p className="q-sub">{q.sub}</p>}
      </div>

      {q.type === 'multi' && (
        <div className="chip-wrap">
          {q.options.map((opt) => (
            <button
              key={opt}
              className={'chip ' + (answer.includes(opt) ? 'sel' : '')}
              onClick={() => toggleMulti(q.id, opt)}
            >{opt}</button>
          ))}
        </div>
      )}

      {q.type === 'color' && (
        <div className="swatch-wrap">
          {q.options.map((opt) => {
            const sel = answer.includes(opt.label);
            const light = ['White', 'Cream'].includes(opt.label);
            return (
              <button key={opt.label} className={'swatch ' + (sel ? 'sel' : '')} onClick={() => toggleMulti(q.id, opt.label)}>
                <span className="swatch-dot" style={{ background: opt.hex }}>
                  <span className="check" style={{ color: light ? '#15140F' : '#FAFAF7' }}><Icon.check /></span>
                </span>
                <span className="swatch-label">{opt.label}</span>
              </button>
            );
          })}
        </div>
      )}

      {q.type === 'single' && (
        <div className="opt-list">
          {q.options.map((opt) => (
            <button
              key={opt.value}
              className={'opt-card ' + (answer === opt.value ? 'sel' : '')}
              onClick={() => setSingle(q.id, opt.value)}
            >
              <span className="opt-radio"></span>
              <span className="opt-text"><span className="opt-title">{opt.value}</span></span>
              <span className="opt-emoji">{opt.glyph}</span>
            </button>
          ))}
        </div>
      )}

      <div className="q-foot">
        <button className="skip-btn" onClick={onSkip}>Skip</button>
        {hasAnswer
          ? <button className="pill" onClick={onNext} style={{ padding: '11px 8px 11px 18px' }}>
              <span>{index === QUESTIONS.length - 1 ? 'See my profile' : 'Next'}</span>
              <span className="knob"><Icon.arrow /></span>
            </button>
          : <span className="sel-hint">{q.type === 'single' ? 'Pick one' : 'Pick any that apply'}</span>}
      </div>
    </div>
  );
}

Object.assign(window, { AccountStep, QuizStep });
