/* global React */
const { useState } = React;
const AR = (typeof window !== "undefined" && window.WATHIQ_LANG === "ar");

/* ============================================================
   CONTACT — book-a-demo split (intro + form) + FAQ
   ============================================================ */

function ContactHero() {
  // The headline now lives inside the split layout below.
  return null;
}

function ContactForm() {
  // status: idle | submitting | success | error
  const [status, setStatus] = useState("idle");
  const [errorMsg, setErrorMsg] = useState("");

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === "submitting") return;
    const form = e.currentTarget;
    const fd = new FormData(form);
    const payload = {
      firstName: fd.get("firstName"),
      lastName: fd.get("lastName"),
      email: fd.get("email"),
      phone: fd.get("phone"),
      companyName: fd.get("companyName"),
      jobTitle: fd.get("jobTitle"),
      teamSize: fd.get("teamSize"),
      orgType: fd.get("orgType"),
      heardAbout: fd.get("heardAbout"),
      lang: AR ? "ar" : "en",
    };
    setStatus("submitting");
    setErrorMsg("");
    try {
      const r = await fetch("/api/request-demo", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!r.ok) throw new Error("request failed");
      setStatus("success");
      // Analytics: the demo-request conversion. Only non-PII fields (never name/email/phone).
      if (window.waTrack) window.waTrack("demo_request_submitted", { org_type: payload.orgType, team_size: payload.teamSize });
    } catch (err) {
      setStatus("error");
      setErrorMsg(
        AR
          ? "تعذّر إرسال الطلب. يُرجى المحاولة مرة أخرى أو مراسلتنا على info@wathiq.ai."
          : "We couldn't send your request. Please try again or email us at info@wathiq.ai."
      );
    }
  };

  return (
    <section className="contact-section">
      <div className="container contact-split">
        <aside className="contact-intro reveal">
          <div className="eyebrow">{AR ? "احجز عرضًا توضيحيًا" : "Book a demo"}</div>
          <h1 className="contact-title">{AR ? "اكتشف ما يقدّمه وثّق لمكتبك." : "See what Wathiq can do for your firm."}</h1>
          <p className="contact-lead">
            {AR
              ? "أخبِرنا عن فريقك، ونُريك كيف ينسجم وثّق مع أسلوب عملك القانوني. عبِّئ النموذج ونعود إليك خلال وقت قصير."
              : "Tell us a little about your team and we'll show you how Wathiq fits the way you already practice. Fill out the form and we'll get back to you shortly."}
          </p>
        </aside>

        {status === "success" ? (
          <div className="form-card contact-success reveal">
            <span className="contact-success-icon" aria-hidden="true">
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none">
                <path d="M5 12.5l4.2 4.2L19 7" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
            <h2 className="contact-success-title">{AR ? "شكرًا لك — وصلنا طلبك." : "Thank you — your request is in."}</h2>
            <p className="contact-success-text">
              {AR
                ? "سيتواصل معك أحد أعضاء فريقنا خلال يوم عمل واحد لتحديد موعد العرض. وأرسلنا تأكيدًا إلى بريدك الإلكتروني — تحقّق من مجلد الرسائل غير المرغوبة احتياطًا."
                : "A member of our team will reach out within one business day to schedule your demo. We've also sent a confirmation to your inbox — check your spam folder just in case."}
            </p>
          </div>
        ) : (
          <form className="form-card contact-form reveal" onSubmit={onSubmit} noValidate>
            {/* Bot-honeypot REMOVED 2026-07-05: any hidden field is unavoidably
                autofilled by password managers / browser autofill, which then made
                the server drop genuine (autofilling) users as "bots" — silently,
                while still showing them "Thank you". Autofill must never block a
                real lead. Bot protection now relies on the required fields + email
                validation; add Cloudflare Turnstile (invisible, autofill-safe) if
                spam ever appears — do NOT reintroduce a honeypot field. */}
            <div className="form-grid">
              <div className="form-field">
                <label className="form-label">{AR ? "الاسم الأول" : "First name"}<span className="req">*</span></label>
                <input className="form-input" type="text" name="firstName" required />
              </div>
              <div className="form-field">
                <label className="form-label">{AR ? "اسم العائلة" : "Last name"}<span className="req">*</span></label>
                <input className="form-input" type="text" name="lastName" required />
              </div>
              <div className="form-field">
                <label className="form-label">{AR ? "البريد الإلكتروني المهني" : "Work email"}<span className="req">*</span></label>
                <input className="form-input" type="email" name="email" required />
              </div>
              <div className="form-field">
                <label className="form-label">{AR ? "رقم الهاتف" : "Phone number"}<span className="req">*</span></label>
                <input className="form-input" type="tel" name="phone" required />
              </div>
              <div className="form-field col-span-2">
                <label className="form-label">{AR ? "اسم المنشأة" : "Company name"}<span className="req">*</span></label>
                <input className="form-input" type="text" name="companyName" required />
              </div>
              <div className="form-field">
                <label className="form-label">{AR ? "المسمى الوظيفي" : "Job title"}<span className="req">*</span></label>
                <input className="form-input" type="text" name="jobTitle" required />
              </div>
              <div className="form-field">
                <label className="form-label">{AR ? "حجم الفريق القانوني" : "Legal team size"}<span className="req">*</span></label>
                <select className="form-select" name="teamSize" required defaultValue="">
                  <option value="" disabled>{AR ? "اختر…" : "Select…"}</option>
                  <option>1–5</option>
                  <option>6–20</option>
                  <option>21–50</option>
                  <option>50+</option>
                </select>
              </div>
              <div className="form-field">
                <label className="form-label">{AR ? "نوع المنشأة" : "Organisation type"}<span className="req">*</span></label>
                <select className="form-select" name="orgType" required defaultValue="">
                  <option value="" disabled>{AR ? "اختر…" : "Select…"}</option>
                  <option>{AR ? "مكتب محاماة" : "Law firm"}</option>
                  <option>{AR ? "شركة" : "Corporate"}</option>
                  <option>{AR ? "جهة حكومية" : "Government"}</option>
                  <option>{AR ? "قطاع عام" : "Public sector"}</option>
                  <option>{AR ? "هيئة محامين" : "Bar association"}</option>
                </select>
              </div>
              <div className="form-field">
                <label className="form-label">{AR ? "كيف تعرّفت علينا؟" : "How did you hear about us?"}<span className="req">*</span></label>
                <select className="form-select" name="heardAbout" required defaultValue="">
                  <option value="" disabled>{AR ? "اختر…" : "Select…"}</option>
                  <option>{AR ? "محرك بحث" : "Search engine"}</option>
                  <option>LinkedIn</option>
                  <option>{AR ? "ترشيح من زميل" : "Referral or word of mouth"}</option>
                  <option>{AR ? "فعالية أو مؤتمر" : "Event or conference"}</option>
                  <option>{AR ? "أخرى" : "Other"}</option>
                </select>
              </div>
            </div>
            {status === "error" && <div className="form-error" role="alert">{errorMsg}</div>}
            <button type="submit" className="form-submit" disabled={status === "submitting"}>
              {status === "submitting"
                ? (AR ? "جارٍ الإرسال…" : "Sending…")
                : (AR ? "اطلب عرضًا توضيحيًا" : "Request a demo")}
              {status !== "submitting" && <span className="arrow">{AR ? "←" : "→"}</span>}
            </button>
          </form>
        )}
      </div>
    </section>
  );
}

const FAQS = [
  {
    q: AR ? "ما هو وثّق؟" : "What is Wathiq?",
    a: AR
      ? "وثّق مساحة عمل قانونية مبنية على الذكاء الاصطناعي، صُمّمت للفرق القانونية في السعودية. يجمع مراجعة العقود وصياغة المستندات وإدارة القضايا في منصة واحدة بضوابط حوكمة محكمة — يُتقن العربية والإنجليزية معًا."
      : "Wathiq is an AI-powered legal workspace built for Saudi legal teams. It combines contract review, document drafting, and matter management in one governed platform — with full Arabic and English support.",
  },
  {
    q: AR ? "ما مجالات الأنظمة السعودية التي يغطّيها وثّق؟" : "Which areas of Saudi law does Wathiq cover?",
    a: AR
      ? "يغطّي وثّق الأنظمة واللوائح السعودية ويستند إليها مباشرةً — في المجالات التجارية والشركات والعمل والمنازعات وغيرها. يبحث في نصوص الأنظمة كاملةً ويستشهد بموادها، مع تحديث القاعدة المعرفية أولًا بأول."
      : "Wathiq is grounded directly in Saudi laws and regulations — across commercial, corporate, employment, disputes, and more. It searches the full statutory text, cites the relevant articles, and keeps its knowledge base continuously updated.",
  },
  {
    q: AR ? "هل يستشهد وثّق بمصادره، وما مدى موثوقية إجاباته؟" : "Does Wathiq cite its sources, and how reliable are its answers?",
    a: AR
      ? "نعم. تُبنى إجابات وثّق على نصوص الأنظمة السعودية مع استشهادات صريحة بالمواد، فيمكنك الرجوع إلى المصدر والتحقق منه. ووثّق أداة مساندة لاتخاذ القرار تدعم المختص القانوني ولا تُغني عن مراجعته."
      : "Yes. Wathiq's answers are grounded in the text of Saudi statutes with explicit article-level citations, so you can trace and verify every source. Wathiq is a decision-support tool that assists legal professionals — it does not replace a lawyer's review.",
  },
  {
    q: AR ? "بماذا يختلف وثّق عن ChatGPT وأدوات الذكاء الاصطناعي العامة؟" : "How is Wathiq different from ChatGPT or other general AI tools?",
    a: AR
      ? "على خلاف النماذج العامة، بُني وثّق خصيصًا للقانون السعودي: إجاباته مؤصَّلة في القاعدة النظامية السعودية الفعلية مع استشهادات، وهو عربيٌّ أولًا، وبياناته مستضافة داخل المملكة وفق نظام حماية البيانات الشخصية، ومُدمَج في سير العمل القانوني بما في ذلك Microsoft Word."
      : "Unlike general-purpose models, Wathiq is built specifically for Saudi law: its answers are grounded in the actual Saudi legal corpus with citations, it is Arabic-first, its data is hosted inside the Kingdom under the PDPL, and it is embedded in legal workflows — including Microsoft Word.",
  },
  {
    q: AR ? "هل يستطيع وثّق مراجعة العقود وصياغتها؟" : "Can Wathiq review and draft contracts?",
    a: AR
      ? "نعم. يراجع وثّق العقود ويقترح التعديلات التتبّعية (Redline) ويصيغ المستندات استنادًا إلى الأنظمة السعودية — داخل المنصة أو مباشرةً في Microsoft Word."
      : "Yes. Wathiq reviews contracts, suggests tracked-change redlines, and drafts documents grounded in Saudi law — inside the platform or directly in Microsoft Word.",
  },
  {
    q: AR ? "هل يحلّ وثّق محلّ المحامي؟" : "Does Wathiq replace lawyers?",
    a: AR
      ? "لا. يُسرّع وثّق العمل القانوني ويرفع جودته، لكنه أداة مساندة يبقى فيها المحامي صاحب القرار والمراجعة النهائية. الغاية أن يتفرّغ الفريق للعمل الأعلى قيمةً، لا أن يحلّ محلّه."
      : "No. Wathiq accelerates and strengthens legal work, but it is a support tool — the lawyer stays in control and makes the final review. The goal is to free your team for higher-value work, not to replace it.",
  },
  {
    q: AR ? "هل يعمل وثّق مع Microsoft Word؟" : "Does Wathiq work with Microsoft Word?",
    a: AR
      ? "نعم. يعمل مساعد الصياغة في لوحة جانبية داخل Word، فتُعيد الصياغة وتُنقّحها وتتحقّق من الاستشهادات داخل المستند نفسه الذي بين يديك — بلا نسخ ولصق."
      : "Yes. Our drafting assistant runs as a sidecar in Word so you can rewrite, refine, and cite-check inside the document you're already working on — no copy-paste.",
  },
  {
    q: AR ? "هل يدعم وثّق اللغة العربية؟" : "Does Wathiq support Arabic?",
    a: AR
      ? "العربية لغة أصيلة في المنظومة لا إضافة لاحقة؛ فالواجهة والمرجعية القانونية وفهرس البحث ونماذج الصياغة بُنيت بالعربية أولًا، مع تحليل بلغتين للمستندات المختلطة."
      : "Arabic is a first-class language in the system, not an afterthought. The interface, the legal corpus, the search index, and the drafting models are all built Arabic-first, with bilingual analysis for mixed-language documents.",
  },
  {
    q: AR ? "كيف يتعامل وثّق مع أمن البيانات والسرّية؟" : "How does Wathiq handle data security and confidentiality?",
    a: AR
      ? "تبقى جميع البيانات داخل المملكة العربية السعودية، مشفّرة أثناء النقل وفي التخزين. بُني وثّق على نظام حماية البيانات الشخصية، ويأتي منذ اليوم الأول بصلاحيات وصول حسب الدور، وضوابط احتفاظ، وسجلّ تدقيق كامل."
      : "All data is hosted within the Kingdom of Saudi Arabia, encrypted in transit and at rest. Wathiq is designed to comply with the Personal Data Protection Law (PDPL) and supports role-based access, retention controls, and audit logging out of the box.",
  },
  {
    q: AR ? "لمن صُمِّم وثّق؟" : "Who is Wathiq built for?",
    a: AR
      ? "لمكاتب المحاماة والإدارات القانونية الداخلية العاملة في المملكة — من المكاتب التجارية المتخصصة إلى المكاتب متكاملة الخدمات والإدارات القانونية في كبرى المنشآت السعودية."
      : "Law firms and in-house legal teams operating in the Kingdom — from boutique commercial practices to full-service firms and corporate legal departments at large Saudi enterprises.",
  },
  {
    q: AR ? "كم يستغرق البدء مع وثّق؟" : "How long does it take to get started?",
    a: AR
      ? "تباشر معظم المكاتب أولى قضاياها على وثّق خلال أسبوع. نتولّى تأهيل فريقك خطوة بخطوة، مع أدلّة عمل جاهزة وتكاملات وتدريب بالعربية والإنجليزية."
      : "Most firms are running their first matter inside Wathiq within a week. We offer a guided onboarding with template playbooks, integrations, and Arabic + English training for your team.",
  },
  {
    q: AR ? "كيف أطلب عرضًا توضيحيًا أو أحصل على وصول؟" : "How do I request a demo or get access?",
    a: AR
      ? "عبّئ نموذج طلب العرض في صفحة التواصل، أو راسلنا على info@wathiq.ai، وسنتواصل معك لترتيب عرضٍ توضيحي مخصّص لمكتبك وبدء التأهيل."
      : "Fill out the demo-request form on the Contact page, or email us at info@wathiq.ai, and we'll arrange a tailored walkthrough for your firm and start onboarding.",
  },
];

function FaqList() {
  const [open, setOpen] = useState(0);
  return (
    <section className="section is-warm">
      <div className="container">
        <div className="section-head reveal">
          <div className="eyebrow">{AR ? "الأسئلة الشائعة" : "Frequently asked questions"}</div>
          <h2 className="h-1" style={{ maxWidth: "22ch", marginTop: 18, marginBottom: 14 }}>
            {AR ? "كل ما تريد معرفته عن وثّق." : "All you need to know about Wathiq."}
          </h2>
          <p>{AR ? "لم تجد ما تبحث عنه؟ " : "Still can't find what you're looking for? "}<a href="mailto:info@wathiq.ai" style={{ color: "var(--accent)", borderBottom: "1px solid currentColor" }}>{AR ? "راسلنا" : "Email us"}</a>.</p>
        </div>
        <div className="faq-list reveal-sm">
          {FAQS.map((it, i) => (
            <div className={`faq-item ${open === i ? "is-open" : ""}`} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{it.q}</span>
                <span className="faq-q-icon">
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                    <path d="M8 2v12M2 8h12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                  </svg>
                </span>
              </button>
              <div className="faq-a" style={{ maxHeight: open === i ? "600px" : "0px" }}>
                <div className="faq-a-inner" style={{ opacity: open === i ? 1 : 0, transform: open === i ? "translateY(0)" : "translateY(-6px)" }}>{it.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ContactHero, ContactForm, FaqList });
