// application-form.jsx — Shared "Work with me" application form.
// Used by the home page enquiry section AND the dedicated service pages.
// Relies on the global <Arrow /> (defined in nav-hero.jsx or page-chrome.jsx).

const APPLY_INTEREST = [
  'The Content Retainer',
  'Content Production',
  'The Signature Day',
  'A little of everything',
  'Not sure yet — let’s talk',
];
const APPLY_INVESTMENT = [
  '1K – 2K AED',
  '2K – 3K AED',
  '3K – 4K AED',
  '4K – 5K AED',
  '5K+ AED',
  'Still figuring it out',
];
const APPLY_SOURCE = [
  'Instagram',
  'TikTok',
  'Word of mouth',
  'Google search',
  'A brand I’ve worked with',
  'Somewhere else',
];

const APPLY_BLANK = {
  name: '', brand: '', email: '', handle: '',
  interest: '', start: '', challenge: '', investment: '', source: '',
  botcheck: false,
};

// Web3Forms — free, 250 submissions/month.
// Get an access key at https://web3forms.com (enter Lamia’s email, verify, copy the key).
const WEB3FORMS_KEY = '5b8cd53f-3b4c-40e9-af8e-1398a800a35d';

function ApplicationForm({
  eyebrow = 'Apply now',
  heading = <>Work <em className="serif-italic">with me.</em></>,
  intro = 'Tell me where your brand is and where you want it to go. Share a few details below and I’ll come back within 48 hours — usually with a short questionnaire and a discovery call.',
}) {
  const [form, setForm] = React.useState(APPLY_BLANK);
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState(false);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    if (form.botcheck) return; // honeypot triggered — silent discard
    setError(false);
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        body: JSON.stringify({ ...form, access_key: WEB3FORMS_KEY }),
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      });
      const data = await res.json();
      if (data.success) {
        setSent(true);
        setTimeout(() => {
          const el = document.querySelector('.form-success');
          if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 60);
      } else {
        setError(true);
      }
    } catch (err) {
      setError(true);
    }
  };

  return (
    <div className="inquire">
      <div className="left">
        <div className="eyebrow appform-eyebrow">{eyebrow}</div>
        <h2 style={{ fontSize: 'clamp(34px,4vw,60px)' }}>{heading}</h2>
        <p>{intro}</p>
      </div>

      {!sent ? (
        <form className="form" onSubmit={submit}>
          {/* honeypot — hidden from real users, bots fill it */}
          <input
            type="checkbox"
            name="botcheck"
            checked={form.botcheck}
            onChange={(e) => setForm((f) => ({ ...f, botcheck: e.target.checked }))}
            style={{ display: 'none' }}
            tabIndex={-1}
            autoComplete="off"
          />

          <div className="form-row split">
            <div>
              <label>Full name</label>
              <input value={form.name} onChange={set('name')} placeholder="Your name" required />
            </div>
            <div>
              <label>Brand name</label>
              <input value={form.brand} onChange={set('brand')} placeholder="Your brand or company" />
            </div>
          </div>

          <div className="form-row split">
            <div>
              <label>Email</label>
              <input type="email" value={form.email} onChange={set('email')} placeholder="you@brand.com" required />
            </div>
            <div>
              <label>Main social handle</label>
              <input value={form.handle} onChange={set('handle')} placeholder="@ Instagram / TikTok" />
            </div>
          </div>

          <div className="form-row">
            <label>How would you like to work together?</label>
            <select value={form.interest} onChange={set('interest')} data-empty={form.interest === ''} required>
              <option value="" disabled>Select an option</option>
              {APPLY_INTEREST.map((o) => <option key={o} value={o}>{o}</option>)}
            </select>
          </div>

          <div className="form-row">
            <label>Tell me about your project</label>
            <textarea value={form.challenge} onChange={set('challenge')}
              placeholder="Brand, goals, vision, event details..." />
          </div>

          <div className="form-row split">
            <div>
              <label>Investment Range</label>
              <select value={form.investment} onChange={set('investment')} data-empty={form.investment === ''}>
                <option value="" disabled>Select a range</option>
                {APPLY_INVESTMENT.map((o) => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
            <div>
              <label>How did you hear about me?</label>
              <select value={form.source} onChange={set('source')} data-empty={form.source === ''}>
                <option value="" disabled>Select an option</option>
                {APPLY_SOURCE.map((o) => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
          </div>

          {error && (
            <div className="form-row" style={{ color: 'var(--accent)', fontSize: '0.85rem' }}>
              Something went wrong — please try again or email directly.
            </div>
          )}

          <div className="form-submit">
            <div className="fineprint">
              By sending you agree to be contacted about your enquiry. Nothing shared,
              nothing spammed.
            </div>
            <button type="submit" className="btn-primary" style={{ border: 0, cursor: 'pointer' }}>
              <span>Submit</span>
              <Arrow />
            </button>
          </div>
        </form>
      ) : (
        <div className="form-success">
          <div className="eyebrow" style={{ marginBottom: 18 }}>Sent — Thank you</div>
          <h3 style={{ marginBottom: 18 }}>
            Talk soon, <em className="serif-italic">{form.name || 'friend'}.</em>
          </h3>
          <p>
            Your application is in. I'll come back within 48 hours with next steps —
            usually a short questionnaire and a discovery call.
          </p>
          <div style={{ marginTop: 32 }}>
            <button className="btn-ghost"
              onClick={() => { setSent(false); setForm(APPLY_BLANK); }}
              style={{ border: '1px solid var(--ink-20)', background: 'transparent', cursor: 'pointer' }}>
              <span>Send another</span>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ApplicationForm });
