function Field({ label, type='text', placeholder, value, onChange, required }) {
  const [focus, setFocus] = React.useState(false);
  return (
    <label style={{display:'block'}}>
      <span className="ts-label" style={{color:'var(--ink)', display:'block', marginBottom:8, transition:'color var(--dur-fast)'}}>
        {label}{required && <span style={{color:'var(--ink-4)'}}> *</span>}
      </span>
      <input type={type} placeholder={placeholder} value={value}
        onChange={e=>onChange(e.target.value)}
        onFocus={()=>setFocus(true)} onBlur={()=>setFocus(false)}
        style={{
          width:'100%', boxSizing:'border-box', font:'inherit', fontSize:15, color:'var(--ink)',
          background:'transparent', border:0, borderBottom:'1px solid '+(focus?'var(--ink)':'var(--line)'),
          padding:'8px 0', outline:'none', transition:'border-color var(--dur-fast)'
        }} />
    </label>
  );
}

function JoinForm() {
  const [f, setF] = React.useState({ name:'', email:'', ig:'', city:'', height:'' });
  const [photos, setPhotos] = React.useState([]);
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(false);
  const fileRef = React.useRef(null);
  const set = k => v => setF(s=>({...s, [k]:v}));
  const valid = f.name.trim() && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim());

  const addFiles = (fileList) => {
    const incoming = Array.from(fileList || []).filter(file => file.type.startsWith('image/'));
    setPhotos(prev => [...prev, ...incoming].slice(0, 5));
  };
  const removePhoto = (i) => setPhotos(prev => prev.filter((_, idx) => idx !== i));

  const photoUrls = React.useMemo(() => photos.map(p => URL.createObjectURL(p)), [photos]);
  React.useEffect(() => () => photoUrls.forEach(u => URL.revokeObjectURL(u)), [photoUrls]);

  const submit = async (e) => {
    e.preventDefault();
    if (!valid || sending) return;
    setSending(true);
    setError(false);
    try {
      const body = new FormData();
      Object.entries(f).forEach(([k,v]) => body.append(k, v));
      photos.forEach(p => body.append('photos', p));
      const res = await fetch('/api/join', { method: 'POST', body });
      if (!res.ok) throw new Error('Request failed');
      setSent(true);
    } catch (err) {
      setError(true);
    } finally {
      setSending(false);
    }
  };

  if (sent) {
    return (
      <div className="fade-in shell" style={{paddingTop:'clamp(60px,10vw,140px)', paddingBottom:140, textAlign:'left'}}>
        <h1 style={{fontFamily:'var(--font-sans)', fontWeight:500, margin:0, fontSize:'clamp(2.5rem, 6vw, 5.5rem)', letterSpacing:'-0.03em', maxWidth:'16ch'}}>
          Thank you. We&rsquo;ll be in touch
        </h1>
        <p className="ts-body" style={{marginTop:20, maxWidth:'42ch', color:'var(--ink-2)'}}>
          If your look is right for the board, you&rsquo;ll hear from us at <strong style={{fontWeight:500, color:'var(--ink)'}}>{f.email || 'your email'}</strong>. See you on the other side.
        </p>
        <button onClick={()=>{setSent(false); setF({name:'',email:'',ig:'',city:'',height:''});}} style={{
          marginTop:32, border:'1.5px solid var(--ink)', background:'transparent', cursor:'pointer', padding:'13px 24px'
        }}><span className="ts-label">Send another</span></button>
      </div>
    );
  }

  return (
    <div className="fade-in shell" style={{paddingTop:'clamp(40px,7vw,96px)', paddingBottom:120}}>
      <div style={{display:'grid', gridTemplateColumns:'minmax(0,1fr) minmax(0,1fr)', gap:'clamp(28px,5vw,90px)', alignItems:'start'}} data-cols>
        <div style={{position:'relative'}}>
          <img
            src="assets/logo-mark.png"
            alt=""
            aria-hidden="true"
            className="join-logo-deco"
            style={{
              position:'absolute',
              width:'clamp(120px, 30vw, 280px)',
              height:'auto',
              top:'32%',
              left:'36%',
              transform:'translate(-50%, -50%)',
              opacity:0.07,
              pointerEvents:'none',
              userSelect:'none',
            }}
          />
          <div style={{position:'relative'}}>
            <h1 style={{fontFamily:'var(--font-sans)', fontWeight:500, margin:0, fontSize:'clamp(2.5rem, 6.5vw, 6rem)', letterSpacing:'-0.03em'}}>Join the board</h1>
            <p className="ts-body" style={{marginTop:10, maxWidth:'36ch', color:'var(--ink-2)'}}>
              We&rsquo;re always looking for new talents. If you are a good fit, send us digitals with no makeup and natural light.
            </p>
          </div>
        </div>

        <form onSubmit={submit} style={{display:'grid', gap:24}}>
          <Field label="Name" placeholder="Full name" value={f.name} onChange={set('name')} required />
          <Field label="Email" type="email" placeholder="you@email.com" value={f.email} onChange={set('email')} required />
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:24}}>
            <Field label="Instagram" placeholder="@username" value={f.ig} onChange={set('ig')} />
            <Field label="Height (cm)" placeholder="178" value={f.height} onChange={set('height')} />
          </div>
          <Field label="City" placeholder="Where are you based?" value={f.city} onChange={set('city')} />

          <div style={{paddingTop:18}}>
            <span className="ts-label" style={{color:'var(--ink-3)'}}>Digitals</span>
            <input ref={fileRef} type="file" accept="image/*" multiple
              onChange={e=>{ addFiles(e.target.files); e.target.value = ''; }}
              style={{display:'none'}} />
            <div
              onClick={()=>fileRef.current && fileRef.current.click()}
              onDragOver={e=>{ e.preventDefault(); }}
              onDrop={e=>{ e.preventDefault(); addFiles(e.dataTransfer.files); }}
              style={{marginTop:10, border:'1px solid var(--line)', padding:'22px 18px', textAlign:'center', color:'var(--ink-3)', cursor:'pointer'}}>
              <span className="ts-small">{photos.length ? `${photos.length} photo${photos.length>1?'s':''} selected — click to add more` : 'Drag photos here or click to browse — JPG, up to 5'}</span>
            </div>
            {photos.length > 0 && (
              <div style={{marginTop:12, display:'flex', flexWrap:'wrap', gap:10}}>
                {photos.map((p, i) => (
                  <div key={i} style={{position:'relative', width:64, height:64}}>
                    <img src={photoUrls[i]} alt="" style={{width:'100%', height:'100%', objectFit:'cover'}} />
                    <button type="button" onClick={()=>removePhoto(i)} aria-label="Remove" style={{
                      position:'absolute', top:-8, right:-8, width:20, height:20, borderRadius:'999px',
                      border:'1px solid var(--ink)', background:'var(--paper)', color:'var(--ink)',
                      fontSize:11, lineHeight:1, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', padding:0
                    }}>&#215;</button>
                  </div>
                ))}
              </div>
            )}
          </div>

          <button type="submit" disabled={!valid || sending} style={{
            marginTop:4, border:'1.5px solid var(--ink)',
            background: valid ? 'var(--ink)' : 'transparent',
            color: valid ? '#fff' : 'var(--ink-4)',
            borderColor: valid ? 'var(--ink)' : 'var(--ink-4)',
            padding:'14px 26px', cursor: (valid && !sending) ? 'pointer' : 'not-allowed',
            justifySelf:'start', transition:'all var(--dur-fast)', opacity: sending ? 0.6 : 1
          }}>
            <span className="ts-label" style={{color: valid ? '#fff' : 'var(--ink-4)'}}>{sending ? 'Sending…' : 'Send application'}</span>
          </button>
          {error && (
            <p className="ts-small" style={{color:'var(--ink-3)', margin:0}}>
              Something went wrong. Please try again or email us at booking@theotherside.agency.
            </p>
          )}
        </form>
      </div>
    </div>
  );
}
window.JoinForm = JoinForm;
