// FRANCIS - enquiry form, footer (mobile-first)

function Enquiry({ t, lang }) {
  const ref = useReveal();
  const turnstileRef = useRef(null);
  const turnstileWidgetRef = useRef(null);
  const turnstileSiteKey = window.FRANCIS_TURNSTILE_SITE_KEY || '';
  const [form, setForm] = useState({
    name: '', email: '', phone: '', address: '', zip: '', vat: '', qty: '', city: '', message: '',
    age: false, consent: false, website: '',
  });
  const [turnstileToken, setTurnstileToken] = useState('');
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState('idle'); // idle | sending | success | error

  function update(k, v) { setForm(s => ({ ...s, [k]: v })); }

  useEffect(() => {
    if (!turnstileSiteKey || !turnstileRef.current) return;
    if (turnstileWidgetRef.current !== null) return;

    let cancelled = false;
    let attempts = 0;

    function renderTurnstile() {
      if (cancelled || turnstileWidgetRef.current !== null) return;
      if (window.turnstile && turnstileRef.current) {
        turnstileWidgetRef.current = window.turnstile.render(turnstileRef.current, {
          sitekey: turnstileSiteKey,
          theme: 'dark',
          size: 'flexible',
          appearance: 'interaction-only',
          callback: token => setTurnstileToken(token),
          'expired-callback': () => setTurnstileToken(''),
          'error-callback': () => setTurnstileToken(''),
        });
        return;
      }
      attempts += 1;
      if (attempts < 40) window.setTimeout(renderTurnstile, 250);
    }

    renderTurnstile();
    return () => { cancelled = true; };
  }, [turnstileSiteKey]);

  function validate() {
    const e = {};
    if (!form.name.trim()) e.name = t.enquiry.errors.required;
    if (!form.email.trim()) e.email = t.enquiry.errors.required;
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = t.enquiry.errors.email;
    if (!form.phone.trim()) e.phone = t.enquiry.errors.required;
    if (!form.address.trim()) e.address = t.enquiry.errors.required;
    if (!form.zip.trim()) e.zip = t.enquiry.errors.required;
    if (form.vat.trim() && !/^\d{9}$/.test(form.vat.trim())) e.vat = t.enquiry.errors.vat;
    if (!form.city.trim()) e.city = t.enquiry.errors.required;
    if (!form.message.trim()) e.message = t.enquiry.errors.required;
    if (!form.age) e.age = t.enquiry.errors.age;
    if (!form.consent) e.consent = t.enquiry.errors.consent;
    return e;
  }

  function resetTurnstile() {
    setTurnstileToken('');
    if (window.turnstile && turnstileWidgetRef.current !== null) {
      window.turnstile.reset(turnstileWidgetRef.current);
    }
  }

  async function submit(ev) {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) {
      // Scroll to the first error
      const firstKey = Object.keys(e)[0];
      const node = document.querySelector(`[data-field="${firstKey}"]`);
      if (node) {
        const top = node.getBoundingClientRect().top + window.scrollY - 90;
        window.scrollTo({ top, behavior: 'smooth' });
      }
      return;
    }
    setStatus('sending');
    try {
      const response = await fetch('/api/enquiry', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          lang,
          turnstileToken,
        }),
      });
      const data = await response.json().catch(() => null);
      if (response.ok && data && data.ok === true) {
        setStatus('success');
        return;
      }
      resetTurnstile();
      setStatus('error');
    } catch (error) {
      resetTurnstile();
      setStatus('error');
    }
  }

  return (
    <section className="enquiry" id="enquiry" ref={ref}>
      <div className="enquiry-inner">
        <div className="enquiry-side" data-reveal>
          <div className="eyebrow" style={{ marginBottom: 16 }}>{t.enquiry.eyebrow}</div>
          <h2 className="section-title">
            {t.enquiry.title[0]}<br /><em>{t.enquiry.title[1]}</em>
          </h2>
          <p className="section-body" style={{ marginBottom: 22 }}>{t.enquiry.body}</p>
          <div className="rope-divider" style={{ justifyContent: 'flex-start', marginLeft: 0, marginBottom: 22 }}>
            <span className="line"></span>
            <span className="knot"></span>
            <span className="line" style={{ width: 24 }}></span>
          </div>
          <p style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontStyle: 'italic',
            color: 'var(--ink-soft)',
            fontSize: 15,
            maxWidth: 340,
            lineHeight: 1.6,
            margin: '0 0 18px',
          }}>{t.enquiry.sidenote}</p>
          <p className="business-note">{t.enquiry.businessNote}</p>
        </div>

        <form className="enquiry-form" onSubmit={submit} noValidate data-reveal>
          {status === 'success' ? (
            <div className="form-status">
              <span className="success-title">{t.enquiry.success.split('.')[0]}.</span>
              <span>{t.enquiry.success.split('.').slice(1).join('.').trim()}</span>
            </div>
          ) : (
            <React.Fragment>
              <input
                type="text"
                name="website"
                value={form.website}
                onChange={e => update('website', e.target.value)}
                tabIndex="-1"
                autoComplete="off"
                aria-hidden="true"
                style={{ position: 'absolute', left: '-10000px', opacity: 0 }}
              />
              <Field id="name" label={t.enquiry.f_name} value={form.name} onChange={v => update('name', v)} error={errors.name} required autoComplete="name" />
              <Field id="email" type="email" label={t.enquiry.f_email} value={form.email} onChange={v => update('email', v)} error={errors.email} required autoComplete="email" inputMode="email" />
              <Field id="phone" type="tel" label={t.enquiry.f_phone} value={form.phone} onChange={v => update('phone', v)} error={errors.phone} required autoComplete="tel" inputMode="tel" />
              <Field id="address" label={t.enquiry.f_address} value={form.address} onChange={v => update('address', v)} error={errors.address} required autoComplete="street-address" full />
              <Field id="zip" label={t.enquiry.f_zip} value={form.zip} onChange={v => update('zip', v)} error={errors.zip} required autoComplete="postal-code" />
              <Field id="vat" label={`${t.enquiry.f_vat} ${t.enquiry.f_vat_opt}`} value={form.vat} onChange={v => update('vat', v)} error={errors.vat} inputMode="numeric" />
              <Field id="qty" label={`${t.enquiry.f_qty} ${t.enquiry.f_qty_opt}`} value={form.qty} onChange={v => update('qty', v)} inputMode="numeric" />
              <Field id="city" label={t.enquiry.f_city} value={form.city} onChange={v => update('city', v)} error={errors.city} required autoComplete="address-level2" />

              <div className={`field full ${errors.message ? 'error' : ''}`} data-field="message">
                <label htmlFor="f-message">{t.enquiry.f_message} <abbr title="required" style={{textDecoration:'none', color:'var(--gold-bright)'}}>*</abbr></label>
                <textarea
                  id="f-message"
                  value={form.message}
                  onChange={e => update('message', e.target.value)}
                  placeholder={t.enquiry.f_message_ph}
                  rows={4}
                />
                {errors.message && <div className="field-error">{errors.message}</div>}
              </div>

              <div className="checks">
                <label className={`check ${errors.age ? 'error' : ''}`} data-field="age">
                  <input type="checkbox" checked={form.age} onChange={e => update('age', e.target.checked)} />
                  <span className="box" aria-hidden="true"></span>
                  <span>
                    {t.enquiry.check1}
                    {errors.age ? <span className="err-suffix">· {errors.age}</span> : null}
                  </span>
                </label>
                <label className={`check ${errors.consent ? 'error' : ''}`} data-field="consent">
                  <input type="checkbox" checked={form.consent} onChange={e => update('consent', e.target.checked)} />
                  <span className="box" aria-hidden="true"></span>
                  <span>
                    {t.enquiry.check2}
                    {errors.consent ? <span className="err-suffix">· {errors.consent}</span> : null}
                  </span>
                </label>
              </div>

              {turnstileSiteKey ? (
                <div className="field full" aria-label="Bot protection">
                  <div ref={turnstileRef}></div>
                </div>
              ) : null}

              {status === 'error' && (
                <div className="form-status error" role="alert">{t.enquiry.error}</div>
              )}

              <div className="submit-row">
                <button type="submit" className="btn btn-primary btn-arrow btn-block" disabled={status === 'sending'}>
                  {status === 'sending' ? t.enquiry.sending : t.enquiry.submit}
                </button>
                <p className="fine-note">{t.enquiry.fine}</p>
              </div>
            </React.Fragment>
          )}
        </form>
      </div>
    </section>
  );
}

function Field({ id, label, value, onChange, error, required, type = 'text', full, autoComplete, inputMode }) {
  return (
    <div className={`field ${full ? 'full' : ''} ${error ? 'error' : ''}`} data-field={id}>
      <label htmlFor={`f-${id}`}>
        {label}
        {required && <abbr title="required" style={{textDecoration:'none', color:'var(--gold-bright)', marginLeft: 4}}>*</abbr>}
      </label>
      <input
        id={`f-${id}`}
        type={type}
        value={value}
        onChange={e => onChange(e.target.value)}
        autoComplete={autoComplete || 'off'}
        inputMode={inputMode}
      />
      {error && <div className="field-error">{error}</div>}
    </div>
  );
}

function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div>
          <div className="footer-brand">FRANCIS</div>
          <div className="footer-meta">
            <div className="descr">{t.footer.descriptor}</div>
            <div>{t.footer.spec}</div>
            <div>{t.footer.origin}</div>
            <div className="resp">{t.footer.resp}</div>
          </div>
        </div>
        <div className="footer-cols">
          <div className="footer-col">
            <h4>{t.footer.col1}</h4>
            <a href="#enquiry">{t.footer.links.contact}</a>
            <a href="https://www.instagram.com/francisgin.pt/" target="_blank" rel="noopener">{t.footer.links.instagram}</a>
          </div>
          <div className="footer-col">
            <h4>{t.footer.col2}</h4>
            <a href="#privacy">{t.footer.links.privacy}</a>
            <a href="#terms">{t.footer.links.terms}</a>
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <span>{t.footer.copyright}</span>
        <span className="responsibility">{t.footer.enjoy}</span>
      </div>
    </footer>
  );
}

function LegalPage({ t, page }) {
  const content = t.legal[page];

  return (
    <main className="legal-page">
      <div className="legal-shell">
        <a className="legal-back" href="#top">{t.legal.back}</a>
        <div className="eyebrow">{t.legal.updated}</div>
        <h1>{content.title}</h1>
        <p className="legal-intro">{content.intro}</p>

        <section className="legal-company" aria-labelledby="legal-company-title">
          <h2 id="legal-company-title">{t.legal.companyTitle}</h2>
          {t.legal.company.map((line) => <p key={line}>{line}</p>)}
        </section>

        <div className="legal-content">
          {content.sections.map((section) => (
            <section key={section.h}>
              <h2>{section.h}</h2>
              {section.p.map((paragraph) => <p key={paragraph}>{paragraph}</p>)}
            </section>
          ))}
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { Enquiry, Field, Footer, LegalPage });
