// Lead webhook endpoint (Google Apps Script Web App URL).
// Example:
// https://script.google.com/macros/s/AKfycb.../exec
const SHEETS_WEBHOOK_URL = "https://script.google.com/macros/s/AKfycbx4pIOfO-b7hbbdTgKy8X3AAWovYYI0INgNKXK91ttAScItxTjln0kZOFJuvhhTVc72rw/exec";
const BUSINESS_EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i;
const BLOCKED_EMAIL_DOMAINS = new Set([
  "gmail.com",
  "googlemail.com",
  "yahoo.com",
  "yahoo.co.in",
  "outlook.com",
  "hotmail.com",
  "live.com",
  "msn.com",
  "icloud.com",
  "me.com",
  "mac.com",
  "aol.com",
  "proton.me",
  "protonmail.com",
  "pm.me",
  "mail.com",
  "gmx.com",
  "yandex.com",
  "zoho.com",
]);

const PMS_OPTIONS = ["Dentrix","Modento","Open Dental","Athenahealth","eClinicalWorks","Jane App","DrChrono","ModMed","Other / not sure"];
const REF = "SAM-" + Math.floor(Math.random() * 900000 + 100000);

async function postToSheets(payload) {
  const formBody = new URLSearchParams();
  Object.entries(payload).forEach(([k, v]) => {
    formBody.append(k, v == null ? "" : String(v));
  });

  // URL-encoded body maps directly to Apps Script e.parameter.
  await fetch(SHEETS_WEBHOOK_URL, {
    method: "POST",
    mode: "no-cors",
    body: formBody,
  });
}

function ConfirmStep({ data }) {
  const [pms, setPms] = React.useState("");
  const [pmsSent, setPmsSent] = React.useState(false);
  const [pmsSubmitting, setPmsSubmitting] = React.useState(false);

  const sendPms = async () => {
    if (!pms || pmsSubmitting) return;
    if (!SHEETS_WEBHOOK_URL.startsWith("https://script.google.com/")) {
      setPmsSent(true);
      return;
    }

    setPmsSubmitting(true);
    try {
      const payload = {
        reference: REF,
        fullName: data.name || "",
        workEmail: data.email || "",
        specialty: data.specialty || "",
        role: data.role || "",
        pms,
        submittedAt: new Date().toISOString(),
        pageUrl: window.location.href,
        userAgent: navigator.userAgent,
      };
      await postToSheets(payload);
    } catch (e) {
      // PMS is optional; ignore network errors.
    } finally {
      setPmsSubmitting(false);
      setPmsSent(true);
    }
  };

  return (
    <div className="lf__done">
      <div className="lf__done-mark" />
      <h3 className="display h-md" style={{margin:0}}>You're booked.</h3>
      <p style={{margin:0, fontSize:15, lineHeight:1.6, color:"rgba(247,241,228,0.7)"}}>
        Expect a text from Jordan within the hour confirming your 20-minute slot. We'll build the demo around your specialty.
      </p>

      {/* ── Post-commit PMS question ── */}
      {!pmsSent ? (
        <div className="lf__pms-ask">
          <div className="lf__pms-label">One quick thing to help us prep —</div>
          <div className="lf__pms-q">Which scheduling system does your practice use?</div>
          <div className="lf__pms-row">
            <select className="lf__pms-select" value={pms} onChange={e => setPms(e.target.value)}>
              <option value="">Select your PMS…</option>
              {PMS_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
            </select>
            <button className="lf__pms-btn" onClick={sendPms} disabled={!pms || pmsSubmitting}>
              {pmsSubmitting ? "Sending..." : "Send →"}
            </button>
          </div>
          <div className="lf__pms-skip" onClick={() => setPmsSent(true)}>Skip — Jordan will ask on the call</div>
        </div>
      ) : (
        <div className="lf__pms-thanks">
          ✓ Got it{pms ? ` — ${pms}` : ""}. We'll have the right integration demo ready.
        </div>
      )}

      <div className="lf__done-row">
        <span className="eyebrow">Reference</span>
        <span style={{fontFamily:"var(--font-mono)", fontSize:13}}>{REF}</span>
      </div>
    </div>
  );
}

function LeadForm() {
  const [data, setData] = React.useState({ name:"", email:"", specialty:"", role:"" });
  const [submitted, setSubmitted] = React.useState(false);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState("");
  const [emailError, setEmailError] = React.useState("");
  const onChange = (id, v) => {
    if (id === "email") setEmailError("");
    setData(d => ({...d, [id]: v}));
  };

  const getEmailValidationError = (email) => {
    const normalizedEmail = email.trim().toLowerCase();
    if (!normalizedEmail) return "Work email is required.";
    if (!BUSINESS_EMAIL_REGEX.test(normalizedEmail)) return "Enter a valid work email address.";
    const domain = normalizedEmail.split("@")[1] || "";
    if (BLOCKED_EMAIL_DOMAINS.has(domain)) return "Please use your clinic or company email (not a personal inbox).";
    return "";
  };

  const canSubmit = data.name.trim() && data.email.trim() && data.specialty && data.role;

  const submit = async (e) => {
    e.preventDefault();
    if (!canSubmit || isSubmitting) return;
    const currentEmailError = getEmailValidationError(data.email);
    if (currentEmailError) { setEmailError(currentEmailError); return; }
    if (!SHEETS_WEBHOOK_URL.startsWith("https://script.google.com/")) {
      setSubmitError("Add your Google Apps Script Web App URL in components/leadForm.jsx.");
      return;
    }
    setSubmitError("");
    setIsSubmitting(true);
    try {
      await postToSheets({
        reference: REF,
        fullName: data.name.trim(),
        workEmail: data.email.trim(),
        specialty: data.specialty,
        role: data.role,
        submittedAt: new Date().toISOString(),
        pageUrl: window.location.href,
        userAgent: navigator.userAgent,
      });
      setSubmitted(true);
    } catch (err) {
      setSubmitError("Could not submit right now. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <section className="lf section" id="book">
      <div className="container">
        <div className="lf__layout">

          {/* ── Left: intro ─────────────────────────────────────── */}
          <div className="lf__intro">
            <span className="eyebrow">Book a 20-minute demo</span>
            <h2 className="display h-lg">See your<br/><span className="serif">first call answered.</span></h2>
            <p className="lede">We'll spin up Samika with your specialty intake script and place a live call into your line — before you commit to anything.</p>

            {/* ── Trust chips ── */}
            <div className="lf__chips">
              <div className="lf__chip">
                <svg width="13" height="16" viewBox="0 0 13 16" fill="none" aria-hidden="true">
                  <path d="M6.5 0L0 2.8v4.8C0 11.6 2.8 15.2 6.5 16 10.2 15.2 13 11.6 13 7.6V2.8L6.5 0z" fill="#7CC7A1" fillOpacity=".2"/>
                  <path d="M6.5 1.4L1.3 3.6v4C1.3 11 3.6 14.3 6.5 14.7c2.9-.4 5.2-3.7 5.2-7.1v-4L6.5 1.4z" stroke="#7CC7A1" strokeWidth="0.9" fill="none"/>
                  <path d="M4.3 8.1l1.8 1.8 3.1-3.1" stroke="#7CC7A1" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
                HIPAA compliant
              </div>
              <div className="lf__chip">
                <span className="lf__chip-dot" />
                40+ clinics this quarter
              </div>
              <div className="lf__chip">
                <span className="lf__chip-line" />
                Live in 7–14 days
              </div>
            </div>

            {/* ── Combined rep + quote ── */}
            <div className="lf__social">
              <div className="lf__quote-mark">"</div>
              <p className="lf__quote-text">Samika paid for itself in the first week. I wish we'd done this two years ago.</p>
              <div className="lf__rep">
                <img
                  className="lf__rep-photo"
                  src="https://images.unsplash.com/photo-1560250097-0b93528c311a?w=96&h=96&fit=crop&crop=faces&auto=format"
                  alt="Jordan Calloway, Samika"
                  onError={e => { e.target.style.display="none"; e.target.nextSibling.style.display="flex"; }}
                />
                <div className="lf__rep-fallback">JC</div>
                <div className="lf__rep-text">
                  <div className="lf__rep-name">
                    Dr. Marcus Webb
                    <span className="lf__rep-specialty">Lakeview Family Medicine</span>
                  </div>
                  <div className="lf__rep-note">
                    Jordan runs every first call.
                    <span className="lf__rep-avail">● Available today</span>
                  </div>
                </div>
              </div>
            </div>

            {/* ── Urgency line ── */}
            <div className="lf__urgency">
              <span className="lf__urgency-dot" />
              <span>Pilot slots limited by onboarding capacity — <strong>12 remaining</strong> this quarter</span>
            </div>
          </div>

          {/* ── Right: form card ────────────────────────────────── */}
          <div className="lf__card">
            {!submitted ? (
              <form onSubmit={submit} noValidate>
                <div className="lf__card-head">
                  <div className="lf__card-title">Get your demo slot</div>
                  <div className="lf__card-sub">4 fields · 45 seconds</div>
                </div>

                <div className="lf__grid">
                  <div className="lf__field">
                    <label className="field-label">Full name *</label>
                    <input type="text" value={data.name} onChange={e => onChange("name", e.target.value)} placeholder="Dr. Jane Smith" required />
                  </div>
                  <div className="lf__field">
                    <label className="field-label">Work email *</label>
                    <input
                      type="email"
                      value={data.email}
                      onChange={e => onChange("email", e.target.value)}
                      onBlur={() => setEmailError(getEmailValidationError(data.email))}
                      placeholder="jane@yourclinic.com"
                      required
                    />
                    {emailError && <div className="lf__field-error">{emailError}</div>}
                  </div>
                  <div className="lf__field">
                    <label className="field-label">Specialty *</label>
                    <select value={data.specialty} onChange={e => onChange("specialty", e.target.value)} required>
                      <option value="">Select…</option>
                      {["Dental","Dermatology","Aesthetics","Primary care","Orthopedics","Other"].map(o =>
                        <option key={o} value={o}>{o}</option>)}
                    </select>
                  </div>
                  <div className="lf__field">
                    <label className="field-label">Your role *</label>
                    <select value={data.role} onChange={e => onChange("role", e.target.value)} required>
                      <option value="">Select…</option>
                      {["Practice owner","Physician","Office manager","Operations lead","Other"].map(o =>
                        <option key={o} value={o}>{o}</option>)}
                    </select>
                  </div>
                </div>

                <button type="submit" className="btn btn--primary lf__submit" disabled={!canSubmit || isSubmitting}>
                  {isSubmitting ? "Submitting..." : <>Book my demo <span className="arrow">→</span></>}
                </button>

                <div className="lf__legal">
                  No spam, no cold calls. We never sell your information.
                </div>
                {submitError && <div className="lf__error">{submitError}</div>}
              </form>
            ) : (
              <ConfirmStep data={data} />
            )}
          </div>

        </div>
      </div>

      <style>{`
        /* ── Section shell ── */
        .lf { background: var(--ink-900); color: var(--cream-100); }
        .lf .eyebrow { color: rgba(247,241,228,0.45); }
        .lf__layout {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 80px;
          align-items: center;
        }

        /* ── Left: intro ── */
        .lf__intro h2 { color: var(--cream-100); margin: 16px 0 20px; }
        .lf__intro .lede { color: rgba(247,241,228,0.65); max-width: 400px; }

        /* Trust chips */
        .lf__chips {
          display: flex; flex-wrap: wrap; gap: 10px;
          margin-top: 28px;
        }
        .lf__chip {
          display: inline-flex; align-items: center; gap: 7px;
          padding: 7px 13px; border-radius: 100px;
          border: 1px solid rgba(247,241,228,0.12);
          background: rgba(247,241,228,0.04);
          font-size: 12.5px; color: rgba(247,241,228,0.7);
          letter-spacing: 0.01em;
        }
        .lf__chip-dot {
          width: 6px; height: 6px; border-radius: 50%;
          background: #7CC7A1; flex-shrink: 0;
        }
        .lf__chip-line {
          width: 14px; height: 1px;
          background: rgba(247,241,228,0.35); flex-shrink: 0;
        }

        /* Combined rep + quote */
        .lf__social {
          margin-top: 36px;
          padding: 24px;
          background: rgba(247,241,228,0.04);
          border: 1px solid rgba(247,241,228,0.1);
          border-radius: 14px;
        }
        .lf__quote-mark {
          font-family: var(--font-display); font-style: italic;
          font-size: 2.4em; line-height: 0.6; color: rgba(124,199,161,0.5);
          margin-bottom: 10px; display: block;
        }
        .lf__quote-text {
          font-size: 15px; line-height: 1.6;
          color: rgba(247,241,228,0.85);
          font-style: italic;
          margin: 0 0 18px;
        }
        .lf__rep {
          display: flex; gap: 12px; align-items: center;
          padding-top: 16px;
          border-top: 1px solid rgba(247,241,228,0.1);
        }
        .lf__rep-photo {
          width: 40px; height: 40px; border-radius: 50%;
          object-fit: cover; flex-shrink: 0;
          border: 1.5px solid rgba(247,241,228,0.15);
        }
        .lf__rep-fallback {
          display: none; width: 40px; height: 40px; border-radius: 50%;
          background: rgba(247,241,228,0.1); color: var(--cream-100);
          align-items: center; justify-content: center;
          font-family: var(--font-mono); font-size: 12px; flex-shrink: 0;
        }
        .lf__rep-text { display: flex; flex-direction: column; gap: 3px; }
        .lf__rep-name {
          font-size: 13px; font-weight: 500;
          color: var(--cream-100);
          display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
        }
        .lf__rep-specialty {
          font-weight: 400; font-size: 12px;
          color: rgba(247,241,228,0.45);
        }
        .lf__rep-note {
          font-size: 12px; color: rgba(247,241,228,0.5);
          display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
        }
        .lf__rep-avail {
          font-family: var(--font-mono); font-size: 10px;
          letter-spacing: 0.08em; text-transform: uppercase;
          color: #7CC7A1;
        }

        /* Urgency line */
        .lf__urgency {
          display: flex; align-items: center; gap: 10px;
          margin-top: 20px;
          font-size: 12.5px; color: rgba(247,241,228,0.5);
        }
        .lf__urgency strong { color: rgba(247,241,228,0.85); font-weight: 500; }
        .lf__urgency-dot {
          width: 6px; height: 6px; border-radius: 50%;
          background: #7CC7A1; flex-shrink: 0;
          box-shadow: 0 0 0 3px rgba(124,199,161,0.18);
          animation: pulse-dot 2.4s ease-in-out infinite;
        }
        @keyframes pulse-dot {
          0%,100% { box-shadow: 0 0 0 3px rgba(124,199,161,0.18); }
          50%      { box-shadow: 0 0 0 6px rgba(124,199,161,0.06); }
        }

        /* ── Right: form card ── */
        .lf__card {
          background: rgba(247,241,228,0.04);
          border: 1px solid rgba(247,241,228,0.11);
          border-radius: 18px;
          padding: 44px;
        }
        .lf__card form { display: flex; flex-direction: column; gap: 0; }
        .lf__card-head { margin-bottom: 32px; }
        .lf__card-title { font-size: 19px; font-weight: 500; color: var(--cream-100); }
        .lf__card-sub {
          font-family: var(--font-mono); font-size: 10px;
          letter-spacing: 0.14em; text-transform: uppercase;
          color: rgba(247,241,228,0.35); margin-top: 6px;
        }
        .lf__grid { display: grid; grid-template-columns: 1fr 1fr; gap: 22px 24px; }
        .lf .field-label { color: rgba(247,241,228,0.5); }
        .lf input, .lf select { color: var(--cream-100); border-bottom-color: rgba(247,241,228,0.15); }
        .lf input:focus, .lf select:focus { border-bottom-color: var(--cream-100); }
        .lf__field-error { margin-top: 8px; font-size: 12px; color: #ffb4b4; line-height: 1.35; }
        .lf select option { background: var(--ink-900); }
        .lf__submit {
          width: 100%; margin-top: 30px;
          justify-content: center; padding: 16px;
          font-size: 16px; border-radius: 10px;
        }
        .lf .btn--primary { background: var(--cream-100); color: var(--ink-900); }
        .lf .btn--primary:hover { background: white; }
        .lf .btn--primary:disabled { opacity: 0.3; cursor: not-allowed; }
        .lf__legal {
          font-family: var(--font-mono); font-size: 10.5px;
          letter-spacing: 0.07em; color: rgba(247,241,228,0.3);
          margin-top: 14px; line-height: 1.6; text-align: center;
        }
        .lf__error { margin-top: 12px; font-size: 12px; color: #ffb4b4; text-align: center; }

        /* ── Confirm state ── */
        .lf__done { display: flex; flex-direction: column; gap: 20px; padding: 8px 0; }
        .lf__done-mark {
          width: 12px; height: 12px; border-radius: 50%;
          background: #7CC7A1; box-shadow: 0 0 0 6px rgba(124,199,161,0.15);
        }
        .lf__done h3 { color: var(--cream-100); }
        .lf__done-row {
          display: flex; gap: 12px; align-items: baseline;
          padding-top: 18px; border-top: 1px solid rgba(247,241,228,0.1); margin-top: 4px;
        }

        /* Post-commit PMS */
        .lf__pms-ask {
          background: rgba(247,241,228,0.05);
          border: 1px solid rgba(247,241,228,0.1);
          border-radius: 10px; padding: 20px;
          display: flex; flex-direction: column; gap: 10px;
        }
        .lf__pms-label {
          font-family: var(--font-mono); font-size: 10px;
          letter-spacing: 0.14em; text-transform: uppercase;
          color: rgba(247,241,228,0.4);
        }
        .lf__pms-q { font-size: 14px; font-weight: 500; color: var(--cream-100); line-height: 1.4; }
        .lf__pms-row { display: flex; gap: 10px; align-items: center; margin-top: 4px; }
        .lf__pms-select {
          flex: 1; background: rgba(247,241,228,0.08);
          border: 1px solid rgba(247,241,228,0.15);
          border-radius: 8px; color: var(--cream-100);
          font-size: 13px; padding: 10px 12px;
          font-family: inherit; outline: none;
          -webkit-appearance: none; appearance: none;
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' fill='none'%3E%3Cpath d='M1 1l4 4 4-4' stroke='rgba(247,241,228,0.4)' stroke-width='1.5' stroke-linecap='round'/%3E%3C/svg%3E");
          background-repeat: no-repeat; background-position: right 12px center;
        }
        .lf__pms-select option { background: #1F1D1A; }
        .lf__pms-btn {
          background: var(--cream-100); color: var(--ink-900);
          border: 0; border-radius: 8px; padding: 10px 18px;
          font-size: 13px; font-weight: 500; cursor: pointer;
          font-family: inherit; white-space: nowrap; transition: opacity .15s;
        }
        .lf__pms-btn:disabled { opacity: 0.35; cursor: not-allowed; }
        .lf__pms-skip {
          font-size: 12px; color: rgba(247,241,228,0.35);
          cursor: pointer; text-decoration: underline; text-underline-offset: 3px;
        }
        .lf__pms-skip:hover { color: rgba(247,241,228,0.6); }
        .lf__pms-thanks {
          font-size: 14px; color: #7CC7A1;
          background: rgba(124,199,161,0.08);
          border: 1px solid rgba(124,199,161,0.2);
          border-radius: 8px; padding: 14px 16px;
        }

        /* ── Responsive ── */
        @media (max-width: 1000px) {
          .lf__layout { grid-template-columns: 1fr; gap: 48px; }
          .lf__intro .lede { max-width: none; }
        }
        @media (max-width: 600px) {
          .lf__grid { grid-template-columns: 1fr; }
          .lf__card { padding: 28px 22px; }
        }
      `}</style>
    </section>
  );
}
window.LeadForm = LeadForm;
