const QUESTIONS = [
  {
    key: "owner",
    q: "Do you own a construction company?",
    options: ["Yes", "No"],
  },
  {
    key: "services",
    q: "What services do you specialise in?",
    options: ["New builds", "Extensions / Renovations", "Roofing", "Driveways, paving & patios", "General building", "Other"],
  },
  {
    key: "turnover",
    q: "What's your approximate annual turnover?",
    options: ["Under £150k", "£150k – £500k", "£500k – £1m", "£1m – £2m", "£2m – £5m", "£5m+"],
  },
  {
    key: "enquiries",
    q: "How many enquiries do you get a month right now?",
    options: ["0 – 5", "5 – 15", "15 – 30", "30+"],
  },
];
const TOTAL_STEPS = QUESTIONS.length + 1; // + contact details

function sendLead(payload) {
  const url = window.NORIX_FUNNEL.LEADS_URL;
  if (!url) return;
  try {
    fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      keepalive: true,
    }).catch(() => {});
  } catch (e) {
    /* never block the booking on logging */
  }
}

function CalendlyEmbed({ answers, contact, onBooked }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const base = window.NORIX_FUNNEL.CALENDLY_URL;
    const url = `${base}?hide_gdpr_banner=1&background_color=0f1422&text_color=fbfaf7&primary_color=1fa9bb`;
    const prefill = {
      name: contact.name,
      email: contact.email,
      customAnswers: {
        a1: contact.phone,
        a2: answers.services,
        a3: answers.turnover,
        a4: answers.enquiries,
      },
    };
    let tries = 0;
    const mount = () => {
      if (window.Calendly && ref.current) {
        ref.current.innerHTML = "";
        window.Calendly.initInlineWidget({ url, parentElement: ref.current, prefill });
      } else if (tries++ < 40) {
        setTimeout(mount, 150);
      } else if (ref.current) {
        ref.current.innerHTML = `<a class="fx-btn fx-btn--lg" href="${base}" target="_blank" rel="noopener">Open the calendar</a>`;
      }
    };
    mount();
    const onMsg = (e) => {
      if (e.data && e.data.event === "calendly.event_scheduled") onBooked();
    };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, []);
  return <div ref={ref} className="fx-cal"></div>;
}

function QualifyModal() {
  const [open, setOpen] = React.useState(false);
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [contact, setContact] = React.useState({ name: "", email: "", phone: "" });
  const [screen, setScreen] = React.useState("questions"); // questions | notfit | calendar | booked
  const [trap, setTrap] = React.useState(""); // honeypot: a field only bots fill in
  const [closing, setClosing] = React.useState(false); // exit animation playing, still mounted
  const [dir, setDir] = React.useState("fwd"); // which way the next step slides in
  const closeRef = React.useRef(null);
  const openerRef = React.useRef(null); // the Book button that opened us, to hand focus back on close

  React.useEffect(() => {
    const onClick = (e) => {
      const t = e.target.closest("[data-book]");
      if (!t) return;
      e.preventDefault();
      openerRef.current = t;
      setClosing(false);
      setDir("fwd");
      setOpen(true);
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  React.useEffect(() => {
    document.body.classList.toggle("fx-locked", open);
    if (!open) return;
    closeRef.current && closeRef.current.focus();
    const onKey = (e) => e.key === "Escape" && close();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  // Closing plays the exit animation first; finishClose unmounts once it ends.
  function close() {
    setClosing(true);
  }

  function finishClose() {
    setOpen(false);
    setClosing(false);
    // Return keyboard / screen-reader users to where they were, not the top of the page
    if (openerRef.current) openerRef.current.focus({ preventScroll: true });
    // Start fresh next time if they were turned away or already booked.
    if (screen === "notfit" || screen === "booked") {
      setStep(0); setAnswers({}); setScreen("questions");
    }
  }

  // Fallback in case animationend never fires (tab hidden mid-close, animations disabled).
  React.useEffect(() => {
    if (!closing) return;
    const t = setTimeout(finishClose, 400);
    return () => clearTimeout(t);
  }, [closing]);

  function choose(key, value) {
    const next = { ...answers, [key]: value };
    setAnswers(next);
    setDir("fwd");
    if (key === "owner" && value === "No") {
      setScreen("notfit");
      return;
    }
    setStep(step + 1);
  }

  function back() {
    setDir("back");
    if (screen === "notfit") { setScreen("questions"); return; }
    if (screen === "calendar") { setScreen("questions"); return; }
    setStep(Math.max(0, step - 1));
  }

  function submitContact(e) {
    e.preventDefault();
    sendLead({
      event: "submitted",
      ...answers,
      ...contact,
      company_website: trap,
      page: window.location.href,
    });
    setDir("fwd");
    setScreen("calendar");
  }

  if (!open) return null;

  const progress = screen === "questions" ? step : TOTAL_STEPS;
  const wide = screen === "calendar";
  const q = `fx-q${dir === "back" ? " fx-q--back" : ""}`;

  return (
    <div className={`fx-modal${closing ? " is-closing" : ""}`} role="dialog" aria-modal="true" aria-labelledby="fx-modal-title" onMouseDown={(e) => e.target === e.currentTarget && close()}>
      <div
        className={`fx-modal__panel${wide ? " fx-modal__panel--wide" : ""}`}
        onAnimationEnd={(e) => closing && e.target === e.currentTarget && finishClose()}
      >
        <div className="fx-modal__head">
          <div id="fx-modal-title" className="fx-modal__title">Let's see if we're a fit</div>
          <button type="button" ref={closeRef} className="fx-modal__close" aria-label="Close" onClick={close}>
            <svg viewBox="0 0 24 24" width="22" height="22"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
          </button>
        </div>

        {screen !== "notfit" && (
          <div className="fx-progress" aria-hidden="true">
            {Array.from({ length: TOTAL_STEPS }).map((_, i) => (
              <span key={i} className={i < progress ? "is-done" : ""}></span>
            ))}
          </div>
        )}

        <div className="fx-modal__body">
          {screen === "questions" && step < QUESTIONS.length && (
            <div key={step} className={q}>
              <h2 className="fx-q__title">{QUESTIONS[step].q}</h2>
              <div className="fx-q__options">
                {QUESTIONS[step].options.map((o) => (
                  <button
                    type="button"
                    key={o}
                    className={`fx-opt${answers[QUESTIONS[step].key] === o ? " is-selected" : ""}`}
                    onClick={() => choose(QUESTIONS[step].key, o)}
                  >
                    {o}
                  </button>
                ))}
              </div>
            </div>
          )}

          {screen === "questions" && step === QUESTIONS.length && (
            <form className={q} onSubmit={submitContact}>
              <h2 className="fx-q__title">Where should we send the invite?</h2>
              <label className="fx-field">
                <span>Full name</span>
                <input required autoComplete="name" value={contact.name} onChange={(e) => setContact({ ...contact, name: e.target.value })} />
              </label>
              <label className="fx-field">
                <span>Email</span>
                <input required type="email" autoComplete="email" value={contact.email} onChange={(e) => setContact({ ...contact, email: e.target.value })} />
              </label>
              <label className="fx-field">
                <span>Mobile number</span>
                <input required type="tel" autoComplete="tel" inputMode="tel" pattern="\+?[0-9 ]{10,16}" title="Please enter a valid UK phone number" placeholder="07..." value={contact.phone} onChange={(e) => setContact({ ...contact, phone: e.target.value })} />
              </label>
              <input className="fx-trap" type="text" name="company_website" tabIndex={-1} autoComplete="off" aria-hidden="true" value={trap} onChange={(e) => setTrap(e.target.value)} />
              <button type="submit" className="fx-btn fx-btn--lg fx-btn--block">Show me available times &rarr;</button>
              <p className="fx-micro fx-micro--left">Your details are only used to arrange your call.</p>
            </form>
          )}

          {screen === "calendar" && (
            <div className={q}>
              <h2 className="fx-q__title fx-q__title--sm">Pick a time that suits you, {contact.name.split(" ")[0]}</h2>
              <CalendlyEmbed answers={answers} contact={contact} onBooked={() => { sendLead({ event: "booked", email: contact.email }); setScreen("booked"); }} />
            </div>
          )}

          {screen === "booked" && (
            <div className={`${q} fx-done`}>
              <div className="fx-done__tick" aria-hidden="true">
                <svg viewBox="0 0 24 24" width="30" height="30"><path pathLength="1" d="M5 12.5l4.5 4.5L19 7.5" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </div>
              <h2 className="fx-q__title">You're booked in.</h2>
              <p className="fx-lead">Check your email for the invite. Speak soon.</p>
              <button type="button" className="fx-btn fx-btn--lg" onClick={close}>Done</button>
            </div>
          )}

          {screen === "notfit" && (
            <div className={`${q} fx-done`}>
              <h2 className="fx-q__title">Thanks for your interest</h2>
              <p className="fx-lead">
                Right now we only work with owners of construction companies, so we're not the right fit
                for this call. If that changes, we'd love to hear from you.
              </p>
              <a className="fx-btn fx-btn--lg fx-btn--ghost" href="mailto:ahmet@norixai.co.uk">Email us instead</a>
            </div>
          )}

          {((screen === "questions" && step > 0) || screen === "notfit" || screen === "calendar") && (
            <button type="button" className="fx-back" onClick={back}>&larr; Back</button>
          )}
        </div>
      </div>
    </div>
  );
}

window.QualifyModal = QualifyModal;
