// Single account + contact + consent step — collected AFTER "We heard you", BEFORE paywall.
// Replaces both the old standalone AccountSetup and the old contact step.

const ContactStep = ({ name, track, onContinue, onBack }) => {
  const [form, setForm] = React.useState({
    legalName: name || '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    sms: true,
    emailOk: true,
    community: true,
    medicalConsent: false,
  });
  const [showPw, setShowPw] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');

  const trackName = (CATEGORIES.find(t => t.id === track) || {}).name || 'Your category';

  const valid =
    form.legalName.trim().length > 1 &&
    form.email.includes('@') &&
    form.phone.replace(/[^0-9]/g, '').length >= 10 &&
    form.password.length >= 8 &&
    form.confirmPassword === form.password &&
    form.sms && form.emailOk &&
    form.medicalConsent; // require core comms consent + medical records consent

  const submit = async () => {
    if (!valid || saving) return;
    setSaving(true);
    setError('');
    try {
      const res = await fetch('/api/site/account', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          legalName: form.legalName,
          email: form.email,
          phone: form.phone,
          password: form.password,
          visitorId: window.localStorage?.getItem('axo_site_visitor_id') || null,
          track,
          consents: {
            sms: form.sms,
            emailOk: form.emailOk,
            community: form.community,
            medicalConsent: form.medicalConsent,
          },
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Could not create account');
      const { password, confirmPassword, ...safeForm } = form;
      onContinue({ ...safeForm, userId: data.user_id, sessionId: data.session_id });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Could not create account');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="q-shell">
      <div className="q-top">
        <Logo size={20} asLink />
        <div className="q-progress">
          <div className="q-progress-fill" style={{ width: '85%' }} />
        </div>
        <div className="q-counter">CREATE ACCOUNT · {trackName.toUpperCase()}</div>
      </div>

      <div className="q-stage">
        <div className="q-card" style={{ maxWidth: 680 }}>
          <div className="q-eyebrow">— LAST STEP BEFORE YOUR PLAN</div>
          <h1 className="q-title serif">Create your <em>account.</em></h1>
          <p className="q-sub">
            We'll use this to send your plan, ship cold-chain, and check in along the way. You can adjust any of it later.
          </p>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, background: 'var(--bg-card)', border: '1px solid var(--rule)', borderRadius: 6, padding: 24 }}>
            <Field label="Legal name (for shipping)" value={form.legalName} onChange={(v) => setForm({ ...form, legalName: v })} placeholder="First Last" />
            <Field label="Email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} placeholder="you@somewhere.com" />
            <Field label="Mobile phone" type="tel" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} placeholder="(555) 555-5555" />

            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-mute)' }}>Password</label>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <input
                  type={showPw ? 'text' : 'password'}
                  value={form.password}
                  onChange={(e) => setForm({ ...form, password: e.target.value })}
                  placeholder="At least 8 characters"
                  style={{ flex: 1, background: 'transparent', border: '1px solid var(--rule)', borderRadius: 4, padding: '14px 16px', fontSize: 16, color: 'var(--ink)', outline: 'none' }}
                />
                <button type="button" onClick={() => setShowPw(!showPw)} style={{ background: 'transparent', border: '1px solid var(--rule)', borderRadius: 4, padding: '14px 12px', fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.1em', cursor: 'pointer' }}>
                  {showPw ? 'HIDE' : 'SHOW'}
                </button>
              </div>
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.05em', color: 'var(--ink-mute)' }}>
                {form.password.length >= 8 ? '✓ Looks good' : `${Math.max(0, 8 - form.password.length)} more characters`}
              </span>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <label style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-mute)' }}>Confirm password</label>
              <input
                type={showPw ? 'text' : 'password'}
                value={form.confirmPassword}
                onChange={(e) => setForm({ ...form, confirmPassword: e.target.value })}
                placeholder="Type it again"
                style={{ background: 'transparent', border: '1px solid var(--rule)', borderRadius: 4, padding: '14px 16px', fontSize: 16, color: 'var(--ink)', outline: 'none' }}
              />
              <span style={{ fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.05em', color: 'var(--ink-mute)' }}>
                {form.confirmPassword && form.confirmPassword === form.password ? '✓ Passwords match' : 'Passwords must match'}
              </span>
            </div>

            <div style={{ borderTop: '1px solid var(--rule)', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <Check
                checked={form.sms}
                onChange={(v) => setForm({ ...form, sms: v })}
                label="Text me"
                detail="Shipment updates, dose timing nudges, and short check-ins. Reply STOP to stop. Msg & data rates may apply."
              />
              <Check
                checked={form.emailOk}
                onChange={(v) => setForm({ ...form, emailOk: v })}
                label="Email me"
                detail="Order confirmations, your COA, and account communications."
              />
              <Check
                checked={form.community}
                onChange={(v) => setForm({ ...form, community: v })}
                label="Send me letters from our community"
                detail="Optional. Stories, member-only essays, and member-led events."
              />
            </div>

            <div style={{ borderTop: '1px solid var(--rule)', paddingTop: 16, marginTop: 4 }}>
              <div style={{ fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 12 }}>— REQUIRED</div>
              <Check
                checked={form.medicalConsent}
                onChange={(v) => setForm({ ...form, medicalConsent: v })}
                label="I consent to AmazingXO and its network reviewing and storing my medical and health information"
                detail="Your assessment, ID verification video, and any provider conversations are stored securely so we can match the right peptides to your situation, ship safely, and step in if anything changes. You can request your records or delete your account at any time."
              />
            </div>
            <div style={{ fontFamily: 'JetBrains Mono', fontSize: 10, letterSpacing: '0.05em', color: 'var(--ink-mute)', textTransform: 'uppercase' }}>
              By continuing you consent to receive communications from our community at the contact info above.
            </div>
            {error && <div style={{ color: 'var(--accent)', fontSize: 14, lineHeight: 1.4 }}>{error}</div>}
          </div>

          <div className="q-actions">
            <button className="btn btn-soft" onClick={onBack}>← Back</button>
            <button
              className="btn btn-primary"
              onClick={submit}
              disabled={!valid || saving}
              style={{ opacity: valid ? 1 : 0.4, pointerEvents: valid ? 'auto' : 'none' }}
            >
              {saving ? 'Creating account...' : 'Continue to membership →'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

const Check = ({ checked, onChange, label, detail }) => (
  <label style={{ display: 'flex', gap: 12, alignItems: 'flex-start', cursor: 'pointer' }}>
    <span
      onClick={() => onChange(!checked)}
      style={{
        width: 20, height: 20, borderRadius: 4,
        border: `1.5px solid ${checked ? 'var(--ink)' : 'var(--rule)'}`,
        background: checked ? 'var(--ink)' : 'transparent',
        color: 'var(--bg)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 12, flexShrink: 0, marginTop: 2,
      }}
    >{checked ? '✓' : ''}</span>
    <span onClick={() => onChange(!checked)} style={{ flex: 1 }}>
      <div style={{ fontWeight: 500, fontSize: 15 }}>{label}</div>
      <div style={{ fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.5 }}>{detail}</div>
    </span>
  </label>
);

const Field = ({ label, value, onChange, placeholder, type = 'text' }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontFamily: 'JetBrains Mono', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-mute)' }}>{label}</label>
    <input
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      style={{ background: 'transparent', border: '1px solid var(--rule)', borderRadius: 4, padding: '14px 16px', fontSize: 16, color: 'var(--ink)', outline: 'none' }}
    />
  </div>
);

Object.assign(window, { ContactStep });
