/* request.jsx — The Request Line: contact / contribution form */
const { useState: _rState, useEffect: _rEffect, useRef: _rRef } = React;

/* Delivery + spam protection (both values are public/client-safe).
   Submissions are emailed by Web3Forms to whichever inbox created the access key.
   hCaptcha uses Web3Forms' shared free sitekey; Web3Forms verifies the token with
   its own secret server-side, so no secret key lives in this repo. */
const WEB3FORMS_ACCESS_KEY = 'd91ab06a-6878-485b-a1dc-599811068bcf';
const HCAPTCHA_SITEKEY = '50b2fe65-b00b-4b9e-ad62-3ba471098be2';

function Field({ label, children, hint }) {
  return (
    <label className="block">
      <span className="font-mono text-[10.5px] uppercase tracking-[0.22em] text-ink-faint">{label}</span>
      {children}
      {hint && <span className="mt-1.5 block font-mono text-[10px] tracking-wide text-ink-ghost">{hint}</span>}
    </label>
  );
}

const inputCls =
  "mt-2 w-full border border-white/12 bg-coal px-4 py-3 text-[15px] text-ink placeholder:text-ink-ghost transition-colors focus:border-[color:var(--accent)] focus:outline-none focus:ring-1 focus:ring-[color:var(--accent)]";

function RequestLine() {
  const types = window.REQUEST_TYPES;
  const [type, setType] = _rState(types[0]);
  const [name, setName] = _rState('');
  const [email, setEmail] = _rState('');
  const [msg, setMsg] = _rState('');
  const [token, setToken] = _rState('');
  const [err, setErr] = _rState(null);
  const [sent, setSent] = _rState(false);
  const [submitting, setSubmitting] = _rState(false);

  const capRef = _rRef(null);
  const widgetId = _rRef(null);

  // Render the hCaptcha widget once the script is ready. The form is always mounted,
  // so this runs a single time on mount.
  _rEffect(() => {
    let cancelled = false;
    const render = () => {
      if (cancelled || !capRef.current || widgetId.current !== null) return;
      if (!window.hcaptcha || !window.hcaptcha.render) { setTimeout(render, 200); return; }
      widgetId.current = window.hcaptcha.render(capRef.current, {
        sitekey: HCAPTCHA_SITEKEY,
        theme: 'dark',
        callback: (t) => setToken(t),
        'expired-callback': () => setToken(''),
        'error-callback': () => setToken(''),
      });
    };
    render();
    return () => { cancelled = true; widgetId.current = null; };
  }, []);

  const resetCaptcha = () => {
    setToken('');
    try { if (widgetId.current !== null && window.hcaptcha) window.hcaptcha.reset(widgetId.current); } catch (_) {}
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!name.trim() || !email.trim() || !msg.trim()) { setErr('Please complete name, email and message.'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setErr('Please enter a valid email address.'); return; }
    if (!token) { setErr('Please complete the captcha.'); return; }
    setErr(null); setSubmitting(true);

    const fd = new FormData(e.target);
    fd.append('access_key', WEB3FORMS_ACCESS_KEY);
    fd.append('subject', `The Billy Joel Piano: Contact — ${type}`);
    fd.append('from_name', name);
    fd.append('replyto', email);
    fd.append('type', type);
    // hCaptcha injects its own h-captcha-response field inside the form, already captured
    // by new FormData(e.target); `token` state is only the client-side "solved" gate.

    try {
      const res = await fetch('https://api.web3forms.com/submit', { method: 'POST', body: fd });
      const data = await res.json();
      if (data.success) {
        setSent(true);
        setName(''); setEmail(''); setMsg(''); setType(types[0]);
        resetCaptcha();
      }
      else { setErr(data.message || 'Something went wrong. Please try again.'); resetCaptcha(); }
    } catch (_) {
      setErr('Network error — please check your connection and try again.');
      resetCaptcha();
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="contact" className="relative mx-auto w-full max-w-[1320px] px-6 py-28 md:px-10 md:py-40">
      <SectionHead index="06 / Contact" kicker="Open archive · contact"
        title={<>Drop us <span className="accent-word">a line.</span></>} />

      <div className="grid grid-cols-1 gap-14 lg:grid-cols-12 lg:gap-16">
        {/* intro copy */}
        <div className="lg:col-span-5">
          <div data-reveal className="lg:sticky lg:top-24">
            <p className="text-[16px] leading-relaxed text-ink-dim">
              This instrument is a preserved piece of music history and is currently
              <span className="text-ink"> not for sale</span>. However, the digital archive is always open.
            </p>
            <p className="mt-5 text-[16px] leading-relaxed text-ink-dim">
              Whether you have a memory of seeing it live on tour, or rare archival photos to contribute — drop us a line.
            </p>
            <dl className="mt-10 space-y-5 border-t border-white/12 pt-8">
              {[['Status', 'Preserved · not for sale'], ['Response', 'Typically within 5 business days'], ['Contributions', 'Photos · stubs · stories welcome']].map(([k, v]) => (
                <div key={k} className="flex items-baseline justify-between gap-6">
                  <dt className="font-mono text-[10.5px] uppercase tracking-[0.2em] text-ink-faint">{k}</dt>
                  <dd className="text-right text-[14px] text-ink-dim">{v}</dd>
                </div>
              ))}
            </dl>
          </div>
        </div>

        {/* form */}
        <div className="lg:col-span-7">
          {sent && (
            <div className="mb-6 flex items-center gap-3 border px-5 py-4"
                 style={{ borderColor: 'var(--accent)', background: 'rgba(58,95,174,0.08)' }}>
              <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full border" style={{ borderColor: 'var(--accent)', color: 'var(--accent)' }}>✓</span>
              <p className="text-[14px] leading-relaxed text-ink">
                Message received. We'll be in touch soon.
              </p>
            </div>
          )}
          <form onSubmit={submit} noValidate className="space-y-7" data-reveal>
              {/* request type */}
              <fieldset>
                <legend className="font-mono text-[10.5px] uppercase tracking-[0.22em] text-ink-faint">Select request type</legend>
                <div className="mt-3 grid grid-cols-1 gap-px sm:grid-cols-2">
                  {types.map((t) => {
                    const active = type === t;
                    return (
                      <button type="button" key={t} onClick={() => setType(t)}
                        className="flex items-center gap-3 border p-4 text-left transition-colors"
                        style={{ borderColor: active ? 'var(--accent)' : 'rgba(255,255,255,0.12)', background: active ? 'rgba(58,95,174,0.08)' : 'var(--bg-2)' }}>
                        <span className="grid h-4 w-4 shrink-0 place-items-center rounded-full border" style={{ borderColor: active ? 'var(--accent)' : 'rgba(255,255,255,0.3)' }}>
                          {active && <span className="h-2 w-2 rounded-full" style={{ background: 'var(--accent)' }}></span>}
                        </span>
                        <span className={`text-[13.5px] leading-snug ${active ? 'text-ink' : 'text-ink-dim'}`}>{t}</span>
                      </button>
                    );
                  })}
                </div>
              </fieldset>

              <div className="grid grid-cols-1 gap-7 sm:grid-cols-2">
                <Field label="Full name">
                  <input className={inputCls} name="name" value={name} onChange={(e) => { setName(e.target.value); if (sent) setSent(false); }} placeholder="Your name" autoComplete="name" />
                </Field>
                <Field label="Email address">
                  <input className={inputCls} name="email" type="email" value={email} onChange={(e) => { setEmail(e.target.value); if (sent) setSent(false); }} placeholder="you@example.com" autoComplete="email" />
                </Field>
              </div>

              <Field label="Your message / question">
                <textarea className={inputCls + ' min-h-[150px] resize-y'} name="message" value={msg} onChange={(e) => { setMsg(e.target.value); if (sent) setSent(false); }} placeholder="Tell us what's on your mind — a question, a memory, or what you'd like to contribute." />
              </Field>

              {/* honeypot — bots that fill this are silently dropped by Web3Forms */}
              <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ display: 'none' }} />

              {/* hCaptcha — verified server-side by Web3Forms */}
              <div ref={capRef}></div>

              {err && <p className="font-mono text-[12px] tracking-wide" style={{ color: '#e7766b' }}>{err}</p>}

              <div className="flex items-center gap-5 pt-2">
                <button type="submit" disabled={submitting}
                  className="group relative overflow-hidden border px-9 py-4 font-mono text-[12px] uppercase tracking-[0.28em] text-ink transition-colors disabled:cursor-not-allowed disabled:opacity-60"
                  style={{ borderColor: 'var(--accent)', background: 'rgba(58,95,174,0.1)' }}>
                  <span className="relative z-10">{submitting ? 'Sending…' : 'Send request'}</span>
                  <span className="absolute inset-0 -translate-x-full transition-transform duration-500 group-hover:translate-x-0" style={{ background: 'var(--accent)' }}></span>
                  <span className="absolute inset-0 z-10 grid -translate-x-full place-items-center font-mono text-[12px] uppercase tracking-[0.28em] text-white transition-transform duration-500 group-hover:translate-x-0">{submitting ? 'Sending…' : 'Send request'}</span>
                </button>
                <span className="font-mono text-[10.5px] uppercase tracking-[0.18em] text-ink-ghost">Archive · SF 223781</span>
              </div>
            </form>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { RequestLine });
