// ── JT Atelier — Affiliate Program Application Page ──────────────────
// Rendered when screen === 'affiliate-apply'.
// Submits to /api/affiliate-apply → saved to Supabase affiliate_applications.

function AffiliateApply({ goTo }) {
  const EMPTY = {
    name: '', email: '', age: '', location: '',
    instagram: '', instagram_followers: '',
    tiktok: '', tiktok_followers: '',
    youtube: '', youtube_subscribers: '',
    twitter: '', other_platforms: '', website: '',
    content_niche: '', audience_location: '',
    paypal_email: '',
    why_jt: '', promotion_plan: '',
    description: '',
  };

  const [form, setForm] = React.useState(EMPTY);
  const [ageOk, setAgeOk] = React.useState(false);
  const [status, setStatus] = React.useState('idle'); // idle | sending | success | error
  const [err, setErr] = React.useState('');

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim()) { setErr('Name and email are required.'); return; }
    if (!ageOk) { setErr('You must confirm you are 18 or older.'); return; }
    const age = parseInt(form.age, 10);
    if (form.age && (isNaN(age) || age < 18)) { setErr('You must be 18 or older to apply.'); return; }
    if (!form.paypal_email.trim()) { setErr('A PayPal email is required so we can pay your commissions.'); return; }
    const hasAnyPlatform = form.instagram || form.tiktok || form.youtube || form.twitter || form.other_platforms || form.website;
    if (!hasAnyPlatform) { setErr('Please include at least one social platform or website.'); return; }

    setErr('');
    setStatus('sending');
    try {
      const res = await fetch('/api/affiliate-apply', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, age_confirmed: true }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Something went wrong.');
      setStatus('success');
    } catch (e) {
      setErr(e.message || 'Could not submit. Please try again.');
      setStatus('idle');
    }
  };

  if (status === 'success') {
    return (
      <div style={{ maxWidth: 680, margin: '0 auto', padding: 'clamp(60px,8vw,120px) 24px' }}>
        <div style={{ textAlign: 'center', padding: '60px 32px', border: '.5px solid var(--line-2)' }}>
          <div className="display" style={{ fontSize: 'clamp(32px,5vw,52px)', marginBottom: 16 }}>
            <em className="gradient-text">Application received.</em>
          </div>
          <p style={{ color: 'var(--fg-2)', fontSize: 15, lineHeight: 1.7, maxWidth: 440, margin: '0 auto 32px' }}>
            We review applications within 3–5 business days. If approved, you'll receive your unique referral link and program details by email.
          </p>
          <button className="btn ghost" onClick={() => goTo('home')}>
            Back to JT Atelier <span className="arrow">→</span>
          </button>
        </div>
      </div>
    );
  }

  const inputStyle = {
    width: '100%', padding: '10px 14px',
    background: 'transparent', color: 'var(--fg)',
    border: '.5px solid var(--line-2)', borderRadius: 0,
    fontSize: 14, fontFamily: 'inherit', outline: 'none',
    transition: 'border-color .15s',
  };
  const labelStyle = {
    display: 'block', fontSize: 10, letterSpacing: '.14em',
    textTransform: 'uppercase', color: 'var(--fg-3)',
    marginBottom: 8, fontWeight: 500,
  };
  const sectionHead = (num, title) => (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 16, marginBottom: 28, paddingBottom: 14, borderBottom: '.5px solid var(--line)' }}>
      <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '.1em' }}>{num}</span>
      <span style={{ fontSize: 13, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--fg-2)' }}>{title}</span>
    </div>
  );

  return (
    <div style={{ maxWidth: 720, margin: '0 auto', padding: 'clamp(60px,8vw,120px) 24px' }}>

      {/* Page header */}
      <div style={{ marginBottom: 56 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '.2em', color: 'var(--fg-3)', marginBottom: 12 }}>
          JT Atelier · Affiliate Program
        </div>
        <h1 className="display" style={{ fontSize: 'clamp(32px,5vw,52px)', fontStyle: 'italic', fontWeight: 400, marginBottom: 16, lineHeight: 1.1 }}>
          Partner with us.
        </h1>
        <p style={{ color: 'var(--fg-2)', fontSize: 15, lineHeight: 1.7, maxWidth: 520 }}>
          We partner with creators who share our commitment to craft, quality, and considered style. Commission is earned on every sale made through your unique link.
        </p>
      </div>

      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 48 }}>

        {/* 01 — About you */}
        <section>
          {sectionHead('01', 'About You')}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div>
              <label style={labelStyle}>Full name *</label>
              <input style={inputStyle} type="text" required value={form.name} onChange={e => set('name', e.target.value)} />
            </div>
            <div>
              <label style={labelStyle}>Email address *</label>
              <input style={inputStyle} type="email" required value={form.email} onChange={e => set('email', e.target.value)} />
            </div>
            <div>
              <label style={labelStyle}>Age</label>
              <input style={inputStyle} type="number" min="18" max="99" placeholder="18+" value={form.age} onChange={e => set('age', e.target.value)} />
            </div>
            <div>
              <label style={labelStyle}>Location (City, Country)</label>
              <input style={inputStyle} type="text" placeholder="e.g. New York, US" value={form.location} onChange={e => set('location', e.target.value)} />
            </div>
          </div>
          <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}
            onClick={() => setAgeOk(v => !v)}>
            <div style={{
              width: 18, height: 18, border: `.5px solid ${ageOk ? 'var(--fg)' : 'var(--line-2)'}`,
              background: ageOk ? 'var(--fg)' : 'transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              transition: 'all .15s',
            }}>
              {ageOk && <svg width="10" height="8" viewBox="0 0 10 8" fill="none">
                <path d="M1 4l3 3 5-6" stroke="var(--bg)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>}
            </div>
            <span style={{ fontSize: 12, color: 'var(--fg-2)', lineHeight: 1.5, userSelect: 'none' }}>
              I confirm that I am 18 years of age or older *
            </span>
          </div>
        </section>

        {/* 02 — Social platforms */}
        <section>
          {sectionHead('02', 'Your Platforms')}
          <p style={{ color: 'var(--fg-3)', fontSize: 12, marginBottom: 20, lineHeight: 1.6 }}>
            At least one platform required. Leave blank if not applicable.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
              <div>
                <label style={labelStyle}>Instagram handle</label>
                <input style={inputStyle} type="text" placeholder="@yourhandle" value={form.instagram} onChange={e => set('instagram', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Followers</label>
                <input style={inputStyle} type="text" placeholder="e.g. 12,400" value={form.instagram_followers} onChange={e => set('instagram_followers', e.target.value)} />
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
              <div>
                <label style={labelStyle}>TikTok handle</label>
                <input style={inputStyle} type="text" placeholder="@yourhandle" value={form.tiktok} onChange={e => set('tiktok', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Followers</label>
                <input style={inputStyle} type="text" placeholder="e.g. 8,200" value={form.tiktok_followers} onChange={e => set('tiktok_followers', e.target.value)} />
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
              <div>
                <label style={labelStyle}>YouTube channel</label>
                <input style={inputStyle} type="text" placeholder="Channel name or URL" value={form.youtube} onChange={e => set('youtube', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Subscribers</label>
                <input style={inputStyle} type="text" placeholder="e.g. 5,000" value={form.youtube_subscribers} onChange={e => set('youtube_subscribers', e.target.value)} />
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <div>
                <label style={labelStyle}>Twitter / X</label>
                <input style={inputStyle} type="text" placeholder="@yourhandle" value={form.twitter} onChange={e => set('twitter', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Website or portfolio</label>
                <input style={inputStyle} type="url" placeholder="https://yoursite.com" value={form.website} onChange={e => set('website', e.target.value)} />
              </div>
            </div>
            <div>
              <label style={labelStyle}>Other platforms (Pinterest, Substack, blog, etc.)</label>
              <input style={inputStyle} type="text" placeholder="e.g. Pinterest — 3,200 followers" value={form.other_platforms} onChange={e => set('other_platforms', e.target.value)} />
            </div>
          </div>
        </section>

        {/* 03 — Audience */}
        <section>
          {sectionHead('03', 'Your Audience')}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div>
              <label style={labelStyle}>Content niche / style</label>
              <input style={inputStyle} type="text" placeholder="e.g. luxury menswear, editorial fashion" value={form.content_niche} onChange={e => set('content_niche', e.target.value)} />
            </div>
            <div>
              <label style={labelStyle}>Audience location</label>
              <input style={inputStyle} type="text" placeholder="e.g. 60% US, 20% UK" value={form.audience_location} onChange={e => set('audience_location', e.target.value)} />
            </div>
          </div>
        </section>

        {/* 04 — Partnership */}
        <section>
          {sectionHead('04', 'The Partnership')}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <label style={labelStyle}>Why do you want to partner with JT Atelier?</label>
              <textarea style={{ ...inputStyle, resize: 'vertical', minHeight: 90 }} rows={3}
                placeholder="Tell us what draws you to the brand and why this partnership makes sense."
                value={form.why_jt} onChange={e => set('why_jt', e.target.value)} />
            </div>
            <div>
              <label style={labelStyle}>How would you promote us?</label>
              <textarea style={{ ...inputStyle, resize: 'vertical', minHeight: 90 }} rows={3}
                placeholder="e.g. try-on content, editorial shoots, dedicated posts, story integrations, reviews…"
                value={form.promotion_plan} onChange={e => set('promotion_plan', e.target.value)} />
            </div>
          </div>
        </section>

        {/* 05 — Payout */}
        <section>
          {sectionHead('05', 'Payout Information')}
          <p style={{ color: 'var(--fg-3)', fontSize: 12, lineHeight: 1.6, marginBottom: 20 }}>
            Commissions are paid monthly via PayPal. Earnings are held 30 days to cover the return window before becoming payable.
          </p>
          <div>
            <label style={labelStyle}>PayPal email address *</label>
            <input style={inputStyle} type="email" required placeholder="your@paypal.email" value={form.paypal_email} onChange={e => set('paypal_email', e.target.value)} />
          </div>
        </section>

        {/* 06 — Anything else */}
        <section>
          {sectionHead('06', 'Anything Else')}
          <div>
            <label style={labelStyle}>Tell us anything else — your story, your aesthetic, links to representative content</label>
            <textarea style={{ ...inputStyle, resize: 'vertical', minHeight: 110 }} rows={4}
              placeholder="Optional but encouraged."
              value={form.description} onChange={e => set('description', e.target.value)} />
          </div>
        </section>

        {/* Submit */}
        {err && (
          <div className="mono" style={{ color: '#e57373', fontSize: 11, marginTop: -24 }}>{err}</div>
        )}
        <button type="submit" className="btn" style={{ alignSelf: 'flex-start' }} disabled={status === 'sending'}>
          {status === 'sending' ? 'Submitting…' : <>Submit application <span className="arrow">→</span></>}
        </button>

      </form>
    </div>
  );
}
