/* ════════════════════════════════════════════════════════════════════
   BookingCard — "Book a conversation" flow for Decidr's AI Roadmap.
   lead → qualify → book → done.  Exposes window.BookingCard.

   On successful submission this POSTs to the HubSpot Forms API
   (portal 443167984, form ff46396e-…) and pushes a
   `hero_form_submit_success` event to window.dataLayer for GTM
   pixel/tag triggers.
   ════════════════════════════════════════════════════════════════════ */

const HUBSPOT_PORTAL_ID = "443167984";
const HUBSPOT_FORM_GUID = "ff46396e-4255-4c88-a913-fdeb223c429c";
const HUBSPOT_REGION    = "ap1";
const HUBSPOT_ENDPOINT  =
  `https://api-${HUBSPOT_REGION}.hsforms.com/submissions/v3/integration/submit/` +
  `${HUBSPOT_PORTAL_ID}/${HUBSPOT_FORM_GUID}`;
// HubSpot objectTypeIds: "0-1" = Contact, "0-2" = Company.
const OBJ_CONTACT = "0-1";
const OBJ_COMPANY = "0-2";

const HEADCOUNT_OPTIONS = ["1-14", "15-49", "50-99", "100-200", "201-500", "500+"];
const REVENUE_OPTIONS = ["Under $2M", "$2M-$10M", "$10M-$20M", "$20M-$50M", "$50M-$100M", "$100M+"];
const ROLE_OPTIONS = ["Executive", "Owner", "Partner", "Director", "VP", "Senior", "Manager", "Employee", "Entry"];
const AI_STAGE_OPTIONS = [
  "We haven't started yet",
  "We've tried a few tools but nothing has changed how we operate",
  "We're actively using AI but it feels fragmented",
  "AI is working for us, we want to scale it across the business",
];
const GOAL_OPTIONS = [
  "Reduce dependence on key people",
  "Get a clear AI strategy we can actually execute",
  "Make our existing AI investments start compounding",
  "Stay ahead of competitors adopting AI faster",
  "Other",
];
const DIAL_CODES = [
  { cc: "AU", code: "+61", country: "Australia" },
  { cc: "NZ", code: "+64", country: "New Zealand" },
  { cc: "US", code: "+1",  country: "United States" },
  { cc: "GB", code: "+44", country: "United Kingdom" },
  { cc: "SG", code: "+65", country: "Singapore" },
];

// Headcount option mismatch: form uses 1-14 / 15-49 / etc., HubSpot's
// `employee_dropdown` uses en-dashes and different buckets. Mapping picks
// the nearest HubSpot bucket. NOTE: HubSpot's middle bucket labels and
// internal values differ (e.g. label "101 – 200" -> value "100 – 200");
// we use the internal value here, not the label.
const HEADCOUNT_TO_HUBSPOT = {
  "1-14":    "6 – 50",
  "15-49":   "6 – 50",
  "50-99":   "51 – 100",
  "100-200": "100 – 200",
  "201-500": "200 – 500",
  "500+":    "1,000+",
};

function countryNameForDial(code) {
  const c = DIAL_CODES.find((x) => x.code === code);
  return c ? c.country : "";
}

function toE164(dialCode, phone) {
  const digits = String(phone || "").replace(/\D/g, "").replace(/^0+/, "");
  if (!digits) return "";
  return `${dialCode}${digits}`;
}

async function submitToHubspot(data) {
  const fields = [
    { objectTypeId: OBJ_CONTACT, name: "firstname", value: data.firstName.trim() },
    { objectTypeId: OBJ_CONTACT, name: "lastname",  value: data.lastName.trim() },
    { objectTypeId: OBJ_CONTACT, name: "email",     value: data.email.trim() },
    { objectTypeId: OBJ_CONTACT, name: "company",   value: data.company.trim() },
    { objectTypeId: OBJ_CONTACT, name: "hs_seniority",          value: data.role.toLowerCase() },
    { objectTypeId: OBJ_CONTACT, name: "revenue_dropdown",      value: data.revenue },
    { objectTypeId: OBJ_CONTACT, name: "where_you_are_with_ai", value: data.aiStage },
    { objectTypeId: OBJ_CONTACT, name: "your_goals",            value: data.goal },
    { objectTypeId: OBJ_CONTACT, name: "marketing_consent",     value: data.consent ? "true" : "false" },
    { objectTypeId: OBJ_COMPANY, name: "employee_dropdown",     value: HEADCOUNT_TO_HUBSPOT[data.headcount] || data.headcount },
  ];
  const phone = toE164(data.dialCode, data.phone);
  if (phone) fields.push({ objectTypeId: OBJ_CONTACT, name: "phone", value: phone });
  const country = countryNameForDial(data.dialCode);
  if (country) fields.push({ objectTypeId: OBJ_CONTACT, name: "country", value: country });

  const payload = {
    fields,
    context: {
      pageUri: typeof window !== "undefined" ? window.location.href : "",
      pageName: typeof document !== "undefined" ? document.title : "",
    },
  };

  const res = await fetch(HUBSPOT_ENDPOINT, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    let detail = "";
    try {
      const j = await res.json();
      detail = j.message || (j.errors && j.errors[0] && j.errors[0].message) || "";
    } catch {}
    throw new Error(detail || `HubSpot submission failed (${res.status})`);
  }
  return res.json().catch(() => ({}));
}

function fireSuccessEvent(data) {
  if (typeof window === "undefined") return;
  const payload = {
    event: "hero_form_submit_success",
    form: "hero_intake",
    form_id: HUBSPOT_FORM_GUID,
    portal_id: HUBSPOT_PORTAL_ID,
    country: countryNameForDial(data.dialCode) || undefined,
  };
  try { window.dataLayer = window.dataLayer || []; window.dataLayer.push(payload); } catch (e) {}
  try { window.dispatchEvent(new CustomEvent("heroform:submit:success", { detail: payload })); } catch (e) {}
}

const TIME_SLOTS = ["9:00 AM", "10:30 AM", "12:00 PM", "1:30 PM", "3:00 PM", "4:30 PM"];
const DOW = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

function BookingCard() {
  const [phase, setPhase] = React.useState("lead");
  const [attempted, setAttempted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitErr, setSubmitErr] = React.useState(null);
  const [data, setData] = React.useState({
    phone: "", dialCode: "+61", firstName: "", lastName: "", email: "", company: "", role: "",
    headcount: "", revenue: "", aiStage: "", goal: "", consent: true,
  });

  const setEvt = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));
  const setCheck = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.checked }));

  const leadValid = data.firstName.trim() && data.lastName.trim();
  const qualifyValid = /\S+@\S+\.\S+/.test(data.email)
    && data.company.trim() && data.role.trim() && data.headcount && data.revenue && data.aiStage && data.goal;

  const onContinue = async () => {
    if (phase === "lead") {
      setAttempted(true);
      if (!leadValid) return;
      setAttempted(false); setPhase("qualify");
    } else if (phase === "qualify") {
      setAttempted(true);
      if (!qualifyValid) return;
      setSubmitErr(null);
      setSubmitting(true);
      try {
        await submitToHubspot(data);
        fireSuccessEvent(data);
        setAttempted(false);
        setPhase("done");
      } catch (err) {
        setSubmitErr(err.message || "Something went wrong. Please try again.");
      } finally {
        setSubmitting(false);
      }
    }
  };

  const bookingDone = phase === "done";

  return (
    <div className="bk-card" data-screen-label={bookingDone ? "Application received" : "Book a conversation"}>
      {bookingDone ? (
        <DoneScreen data={data} />
      ) : (
        <FormScreen
          phase={phase}
          data={data}
          setEvt={setEvt}
          setCheck={setCheck}
          attempted={attempted}
          submitting={submitting}
          submitErr={submitErr}
          onContinue={onContinue} />
      )}
    </div>);
}

function FormScreen({ phase, data, setEvt, setCheck, attempted, submitting, submitErr, onContinue }) {
  const expanded = phase === "qualify";
  const err = (cond) => attempted && cond;

  return (
    <React.Fragment>
      <div className="bk-body">
        <h2 className="bk-title">Book a discovery call</h2>
        <p className="bk-sub">A 15-minute call. No deck. We'll show you where AI pays back first in your business.</p>

        <div className="bk-fields">
          <div className="bk-field">
            <span className="bk-label">Phone number<span className="bk-req">*</span></span>
            <div className="bk-phone-row">
              <select className="bk-control bk-dial" name="tel-country-code" value={data.dialCode} onChange={setEvt("dialCode")} autoComplete="tel-country-code" aria-label="Country code">
                {DIAL_CODES.map((c) => <option key={c.code} value={c.code}>{c.cc} {c.code}</option>)}
              </select>
              <input className="bk-control" type="tel" name="phone" value={data.phone} onChange={setEvt("phone")} placeholder="400 000 000" autoComplete="tel-national" />
            </div>
          </div>

          <div className="bk-row-2">
            <div className="bk-field">
              <input className="bk-control" type="text" value={data.firstName} onChange={setEvt("firstName")} placeholder="First name *" autoComplete="given-name" />
              {err(!data.firstName.trim()) && <span className="bk-error">Required</span>}
            </div>
            <div className="bk-field">
              <input className="bk-control" type="text" value={data.lastName} onChange={setEvt("lastName")} placeholder="Last name *" autoComplete="family-name" />
              {err(!data.lastName.trim()) && <span className="bk-error">Required</span>}
            </div>
          </div>

          {expanded && (
            <div className="bk-reveal bk-fields" style={{ marginTop: 0 }}>
              <Field label="Email address" required error={err(!/\S+@\S+\.\S+/.test(data.email)) && "Enter a valid work email."}>
                <input className="bk-control" type="email" value={data.email} onChange={setEvt("email")} placeholder="Email *" autoComplete="email" />
              </Field>

              <div className="bk-row-2">
                <Field label="Company name" required error={err(!data.company.trim()) && "Required"}>
                  <input className="bk-control" type="text" value={data.company} onChange={setEvt("company")} placeholder="Acme Co." autoComplete="organization" />
                </Field>
                <SelectField label="Your role" required value={data.role} onChange={setEvt("role")} options={ROLE_OPTIONS} error={err(!data.role) && "Required"} />
              </div>

              <SelectField label="How many people work in your business?" required value={data.headcount} onChange={setEvt("headcount")} options={HEADCOUNT_OPTIONS} error={err(!data.headcount) && "Required"} />

              <SelectField label="Annual revenue" required value={data.revenue} onChange={setEvt("revenue")} options={REVENUE_OPTIONS} error={err(!data.revenue) && "Required"} />

              <SelectField label="Where you are with AI" required value={data.aiStage} onChange={setEvt("aiStage")} options={AI_STAGE_OPTIONS} error={err(!data.aiStage) && "Required"} />

              <SelectField label="Your goals" required value={data.goal} onChange={setEvt("goal")} options={GOAL_OPTIONS} error={err(!data.goal) && "Required"} />
            </div>
          )}
        </div>

        {expanded && (
        <label className="bk-consent-check bk-reveal">
          <input type="checkbox" checked={data.consent} onChange={setCheck("consent")} />
          <span className={"bk-check-box" + (data.consent ? " is-checked" : "")} style={data.consent ? { background: "var(--ink)", borderColor: "var(--ink)" } : undefined}><i className="ph-bold ph-check" style={{ opacity: data.consent ? 1 : 0 }}></i></span>
          <span className="bk-consent-text">Get updates, insights and event invites from Decidr. <a href="https://www.decidr.ai/privacy-policy?_gl=1*lyrkaz*_gcl_aw*R0NMLjE3Nzk3NTg4MTMuQ2p3S0NBanc1c19RQmhBZEVpd0FERF9nQmxIWS1sSnlWby1qX1Zoa3RUSHNDVnZuTFN5eTJHdjBreUktTkFGdm1kdzNfN21rV0tGV3NCb0NiMllRQXZEX0J3RQ..*_gcl_au*ODU0MTg3MzYyLjE3NzkwNjcxNTMuMTYwODE2NTI5OC4xNzc5NzcxNzI2LjE3Nzk3NzE3MzY.*_ga*NDkzMjA2NzguMTc3OTA2NzE1NA..*_ga_46XLTFPK7T*czE3ODA1NTE1NjQkbzU1JGcwJHQxNzgwNTUxNTY0JGo2MCRsMCRoMTY1NTA3NDAyNg.." target="_blank" rel="noopener">Read our Privacy Policy</a>.</span>
        </label>
        )}

        {submitErr && (
          <div className="bk-submit-err" role="alert" style={{
            marginTop: 14, padding: "10px 12px", borderRadius: 10,
            background: "rgba(220,38,38,.08)", color: "var(--error, #b91c1c)",
            border: "1px solid rgba(220,38,38,.2)", fontSize: 13, lineHeight: 1.4
          }}>
            {submitErr}
          </div>
        )}

        <button className="bk-cta" type="button" onClick={onContinue} disabled={submitting} style={submitting ? { opacity: 0.7, cursor: "wait" } : undefined}>
          {submitting ? "Submitting…" : expanded ? "Submit application" : "Continue"}
          {!submitting && <i className="ph ph-arrow-right"></i>}
        </button>
      </div>

      <div className="bk-cal-wrap">
        <Calendar disabled day={null} setDay={() => {}} />
        <div className="bk-cal-lock">
          <div className="bk-cal-lock-msg">
            <i className="ph-fill ph-lock-simple"></i>
            Submit your application and our team will help you find a time.
          </div>
        </div>
      </div>
    </React.Fragment>);
}

function Calendar({ day, setDay, disabled }) {
  // June 1, 2026 is a Monday. Sunday-first grid → 1 blank lead cell. Today = June 3.
  const LEAD = 1, DAYS = 30, TODAY = 3;
  const cells = [];
  for (let i = 0; i < LEAD; i++) cells.push(null);
  for (let d = 1; d <= DAYS; d++) cells.push(d);
  const dow = (d) => (LEAD + d - 1) % 7;
  const isAvailable = (d) => !disabled && d >= TODAY && dow(d) !== 0 && dow(d) !== 6;

  return (
    <div>
      <div className="bk-cal-head">
        <span className="bk-cal-month">June 2026</span>
        <div className="bk-cal-nav">
          <button className="bk-cal-navbtn" type="button" disabled><i className="ph ph-caret-left"></i></button>
          <button className="bk-cal-navbtn" type="button" disabled={disabled}><i className="ph ph-caret-right"></i></button>
        </div>
      </div>
      <div className="bk-cal-grid">
        {DOW.map((d) => <div key={d} className="bk-cal-dow">{d}</div>)}
        {cells.map((d, i) => {
          if (d === null) return <div key={`e${i}`} className="bk-cal-cell is-empty"></div>;
          const avail = isAvailable(d);
          const selected = day === d;
          const cls = `bk-cal-cell${selected ? " is-selected" : avail ? " is-available" : " is-disabled"}`;
          return <button key={d} type="button" className={cls} disabled={!avail} onClick={() => avail && setDay(d)}>{d}</button>;
        })}
      </div>
    </div>);
}

function DoneScreen({ data }) {
  return (
    <div className="bk-done bk-reveal">
      <div className="bk-done-mark"><i className="ph-fill ph-check-circle"></i></div>
      <h2 className="bk-done-h">Application received, {data.firstName}.</h2>
      <p className="bk-done-p">
        Thanks for sharing the details. One of our consultants will be in touch shortly. In the meantime, you're welcome to book a time directly below.
      </p>
      <a className="bk-done-book" href="https://meetings-ap1.hubspot.com/co-boyle" target="_blank" rel="noopener">
        <i className="ph-fill ph-calendar-check"></i> Book a time now
      </a>
    </div>);
}

function Field({ label, required, error, children }) {
  return (
    <label className="bk-field">
      <span className="bk-label">{label}{required && <span className="bk-req">*</span>}</span>
      {children}
      {error && <span className="bk-error">{error}</span>}
    </label>);
}

function SelectField({ label, required, value, onChange, options, error }) {
  return (
    <Field label={label} required={required} error={error}>
      <select className="bk-control" value={value} onChange={onChange} required>
        <option value="" disabled hidden>Select</option>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </Field>);
}

window.BookingCard = BookingCard;
