/* ============================================================
   components-contact.jsx — lead-capture form + contact page layout
   Fields: name · email · company · engagement interest · brief
   Captures locally (localStorage) + success state; wire to a real
   backend (Resend / Formspark) later via CONTACT_ACTION.
   ============================================================ */
const CONTACT_ACTION = ""; /* real endpoint goes here later */

const ENGAGEMENT_OPTIONS = [
  "Single Creative — AED 14,999 (≈ $4,100)",
  "Anchor Retainer — from AED 35K/mo (≈ $9,500/mo)",
  "Build-and-License — from AED 80K (≈ $21,800)",
  "A Topmate call first",
  "Not sure yet — help me pick",
];

function LeadForm({ fireToast }) {
  const [f, setF] = React.useState({ name:"", email:"", company:"", engagement:"", brief:"" });
  const [errs, setErrs] = React.useState({});
  const [done, setDone] = React.useState(false);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  const validate = () => {
    const e = {};
    if (!f.name.trim()) e.name = "Need a name — and the decision-maker's, ideally.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email.trim())) e.email = "A real email so the reply lands.";
    if (!f.brief.trim() || f.brief.trim().length < 80) e.brief = "Two real lines — what you're trying to ship, by when, and what's gotten in the way.";
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    if (CONTACT_ACTION) {
      try { fetch(CONTACT_ACTION, { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify(f) }); } catch(_) {}
    }
    try {
      const list = JSON.parse(localStorage.getItem("ths_leads") || "[]");
      list.push({ ...f, at: new Date().toISOString() });
      localStorage.setItem("ths_leads", JSON.stringify(list));
    } catch (_) {}
    setDone(true);
    if (fireToast) fireToast(<span>Brief received — <b>I read every one</b> ↗</span>);
  };

  if (done) {
    return (
      <div className="form-ok">
        <div className="eyebrow">Brief received</div>
        <h2>Got it, {f.name.split(" ")[0] || "operator"}. <em>The clock starts now.</em></h2>
        <p>I read every brief myself — no intake form, no junior triage. Expect a reply at <b style={{color:"var(--bone)"}}>{f.email}</b> within one working day. If it's urgent, the WhatsApp line is faster.</p>
        <div className="book-cta" style={{justifyContent:"flex-start"}}>
          <a className="btn btn-saffron" href={TOPMATE} target="_blank" rel="noopener">Skip the wait — book Topmate <Arrow/></a>
        </div>
      </div>
    );
  }

  const field = (key, label, node, required) => (
    <div className={"field" + (errs[key] ? " error" : "")}>
      <label htmlFor={key}>{label}{required && <span className="req"> *</span>}</label>
      {node}
      {errs[key] && <span className="err">{errs[key]}</span>}
    </div>
  );

  return (
    <form className="lead-form" onSubmit={submit} noValidate>
      <div className="form-row">
        {field("name", "Your name", <input id="name" value={f.name} onChange={set("name")} placeholder="First & last" autoComplete="name" />, true)}
        {field("email", "Email", <input id="email" type="email" value={f.email} onChange={set("email")} placeholder="you@company.com" autoComplete="email" />, true)}
      </div>
      {field("company", "Company / brand", <input id="company" value={f.company} onChange={set("company")} placeholder="What are we building for" autoComplete="organization" />)}
      {field("engagement", "What you're after",
        <select id="engagement" value={f.engagement} onChange={set("engagement")}>
          <option value="">Pick the seat (or let me)</option>
          {ENGAGEMENT_OPTIONS.map((o, i) => <option key={i} value={o}>{o}</option>)}
        </select>
      )}
      {field("brief", "The brief", <textarea id="brief" value={f.brief} onChange={set("brief")} placeholder="What's the play. What's the deadline. What's gotten in the way so far. Two lines is plenty." />, true)}
      <div className="form-foot">
        <button className="btn btn-saffron" type="submit">Send the brief <Arrow/></button>
        <span className="small">One operator reads this. No autoresponder, no sales sequence.</span>
      </div>
    </form>
  );
}

function ContactPage({ onBook, onWhats, onMail, fireToast }) {
  return (
    <main className="contact">
      <div className="page-top"></div>
      <section className="contact-hero">
        <div className="wrap">
          <div className="eyebrow">05 · Get in touch</div>
          <h1>Book the call <em>before you commission the deck.</em></h1>
          <p className="lede">Send a brief below and I'll reply within a working day. Or go straight to Topmate — takes ten minutes to book, no proposal needed. The receipts are already on the table.</p>
        </div>
      </section>
      <div className="wrap">
        <div className="contact-grid">
          <LeadForm fireToast={fireToast} />
          <aside className="contact-side">
            <h3>Faster routes</h3>
            <div className="contact-direct">
              <div className="cd-link" onClick={onBook}>
                <div><div className="cd-k">Book on Topmate</div><div className="cd-v">Slots in under ten minutes · first founder call free</div></div>
                <Arrow/>
              </div>
              <div className="cd-link" onClick={onWhats}>
                <div><div className="cd-k">WhatsApp</div><div className="cd-v">+971 56 745 3636 · fastest for urgent</div></div>
                <Arrow/>
              </div>
              <div className="cd-link" onClick={onMail}>
                <div><div className="cd-k">Email</div><div className="cd-v">hi@thathyperactivesardar.com</div></div>
                <Arrow/>
              </div>
              <a className="cd-link" href={LINKEDIN} target="_blank" rel="noopener">
                <div><div className="cd-k">LinkedIn</div><div className="cd-v">Operator Mode, in public</div></div>
                <Arrow/>
              </a>
            </div>
            <p className="resp">I read every brief myself. No intake form, no junior triage — the operator you hire is the one who replies.</p>
          </aside>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { LeadForm, ContactPage, CONTACT_ACTION, ENGAGEMENT_OPTIONS });
