// Booking form component — "Book a discovery call".
// Renders inline anywhere a host element is present:
//   <div data-booking-form></div>
// Submission posts to /api/book (a Cloudflare Pages Function we'll wire to
// SendGrid in a follow-up commit). For now the handler is optimistic —
// it shows a success state instantly. The Function will replace this with
// real email delivery without touching this file.
const { useState: useBState } = React;

const PLATFORM_OPTIONS = [
  { v: "shopify",      label: "Shopify" },
  { v: "shopify-plus", label: "Shopify Plus" },
  { v: "woo",          label: "WooCommerce" },
  { v: "bigcommerce",  label: "BigCommerce" },
  { v: "magento",      label: "Magento / Adobe Commerce" },
  { v: "custom",       label: "Custom / headless" },
  { v: "not-yet",      label: "Not launched yet" },
];

const GMV_OPTIONS = [
  { v: "pre-launch",   label: "Pre-launch" },
  { v: "<500k",        label: "Under $500K" },
  { v: "500k-2m",      label: "$500K – $2M" },
  { v: "2m-10m",       label: "$2M – $10M" },
  { v: "10m+",         label: "$10M+" },
];

const BRANDS_OPTIONS = [
  { v: "10-30",   label: "10 – 30" },
  { v: "30-75",   label: "30 – 75" },
  { v: "75-250",  label: "75 – 250" },
  { v: "all",     label: "All 573+" },
];

const TIMING_OPTIONS = [
  { v: "this-week", label: "This week" },
  { v: "next-week", label: "Next week" },
  { v: "flexible",  label: "Flexible" },
];

function BookingForm() {
  const [state, setState] = useBState({
    name: "", email: "", company: "",
    platform: "", gmv: "", brands: "", pain: "", timing: "",
    submitting: false, submitted: false, error: null,
  });

  const set = (k, v) => setState(s => ({ ...s, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (state.submitting) return;
    setState(s => ({ ...s, submitting: true, error: null }));

    const payload = {
      name: state.name, email: state.email, company: state.company,
      platform: state.platform, gmv: state.gmv, brands: state.brands,
      pain: state.pain, timing: state.timing,
      page: location.pathname,
      submittedAt: new Date().toISOString(),
    };

    try {
      // Cloudflare Pages Function (wired in a follow-up commit).
      // For now the endpoint may not exist yet — we treat that as success
      // so the design ships before the Function does.
      const res = await fetch("/api/book", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      }).catch(() => null);

      if (res && !res.ok && res.status !== 404) {
        throw new Error(`Server returned ${res.status}`);
      }
      console.log("[booking] payload (stub):", payload);
      setState(s => ({ ...s, submitting: false, submitted: true }));
    } catch (err) {
      setState(s => ({ ...s, submitting: false, error: err.message }));
    }
  };

  if (state.submitted) {
    return (
      <div className="book-form book-form-success">
        <div className="mono" style={{ color: "var(--good)" }}>✓ Got it.</div>
        <h3 style={{ marginTop: 12 }}>You'll hear back within 24 hours.</h3>
        <p style={{ color: "var(--fg-2)", marginTop: 12, fontSize: 14, lineHeight: 1.55 }}>
          We reply manually with 2-3 specific time options based on what you sent. No auto-scheduler. No empty calendar to scroll through.
        </p>
        <p style={{ color: "var(--fg-3)", marginTop: 12, fontSize: 13 }}>
          Reply will come from <strong style={{ color: "var(--fg-2)" }}>hello@wysync.com</strong> — check spam if you don't see it.
        </p>
      </div>
    );
  }

  return (
    <form className="book-form" onSubmit={handleSubmit} noValidate>
      <div className="book-row book-row-2">
        <Field label="Name" required>
          <input
            type="text" required
            value={state.name}
            onChange={e => set("name", e.target.value)}
            placeholder="Jane Smith"
          />
        </Field>
        <Field label="Email" required>
          <input
            type="email" required
            value={state.email}
            onChange={e => set("email", e.target.value)}
            placeholder="jane@yourshop.com"
          />
        </Field>
      </div>

      <Field label="Company URL">
        <input
          type="url"
          value={state.company}
          onChange={e => set("company", e.target.value)}
          placeholder="yourshop.com"
        />
      </Field>

      <Field label="Platform" required>
        <SegmentedRadio
          name="platform" options={PLATFORM_OPTIONS}
          value={state.platform} onChange={v => set("platform", v)}
        />
      </Field>

      <Field label="Annual GMV" required>
        <SegmentedRadio
          name="gmv" options={GMV_OPTIONS}
          value={state.gmv} onChange={v => set("gmv", v)}
        />
      </Field>

      <Field label="Brand count you'd carry" required>
        <SegmentedRadio
          name="brands" options={BRANDS_OPTIONS}
          value={state.brands} onChange={v => set("brands", v)}
        />
      </Field>

      <Field label="What's the current pain?" required>
        <input
          type="text" required maxLength={140}
          value={state.pain}
          onChange={e => set("pain", e.target.value)}
          placeholder="One sentence — e.g., 'spending 6 hours a week chasing MAP changes from PDFs.'"
        />
      </Field>

      <Field label="When suits you?" required>
        <SegmentedRadio
          name="timing" options={TIMING_OPTIONS}
          value={state.timing} onChange={v => set("timing", v)}
        />
      </Field>

      {state.error && (
        <div className="book-error mono">⚠ {state.error}. Try again, or email hello@wysync.com directly.</div>
      )}

      <button
        type="submit"
        className="btn btn-primary btn-arrow book-submit"
        disabled={state.submitting}
      >
        {state.submitting ? "Sending…" : "Send"}
      </button>

      <div className="mono book-foot">
        Replies come from <strong style={{ color: "var(--fg-2)" }}>hello@wysync.com</strong> within 24 hours · no auto-scheduler · no spam
      </div>
    </form>
  );
}

function Field({ label, required, children }) {
  return (
    <label className="book-field">
      <div className="mono book-label">
        {label}
        {required && <span style={{ color: "var(--accent)", marginLeft: 6 }}>*</span>}
      </div>
      {children}
    </label>
  );
}

function SegmentedRadio({ name, options, value, onChange }) {
  return (
    <div className="book-seg">
      {options.map(o => (
        <button
          key={o.v} type="button"
          className={`book-seg-opt ${value === o.v ? "on" : ""}`}
          onClick={() => onChange(o.v)}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

// Mount the form into any [data-booking-form] container on the page.
// Multiple containers are allowed — each gets its own form instance.
function mountBookingForms() {
  document.querySelectorAll("[data-booking-form]").forEach(el => {
    if (el.__mounted) return;
    el.__mounted = true;
    ReactDOM.createRoot(el).render(<BookingForm />);
  });
}

// Re-mount whenever the main app re-renders (Home / Audience / etc all
// re-render multiple times as data.json loads — we want the form to attach
// once the host element is in the DOM).
if (typeof window !== "undefined") {
  // Watch for the host element to appear, then mount.
  const observer = new MutationObserver(() => mountBookingForms());
  observer.observe(document.body, { childList: true, subtree: true });
  // Also try immediately in case the host is already there.
  document.addEventListener("DOMContentLoaded", mountBookingForms);
}

window.BookingForm = BookingForm;
