// Form questions — restructured to 4 pages:
//   1. Situation (single select, auto-advance)
//   2. Approximate balance (dropdown)
//   3. Contact info + optional additional info (lenders, payment, cadence)
//   4. Book a call (Cal.com style calendar)

function OptionCard({ value, current, onSelect, title, hint }) {
  const selected = current === value;
  return (
    <button
      type="button"
      className="opt"
      data-selected={selected ? "1" : "0"}
      onClick={() => onSelect(value)}
    >
      <span className="opt-radio" aria-hidden="true" />
      <span className="opt-body">
        <span className="opt-title">{title}</span>
        {hint && <span className="opt-hint">{hint}</span>}
      </span>
      <svg className="opt-arrow" width="18" height="18" viewBox="0 0 24 24" fill="none"
           stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M5 12h14M13 5l7 7-7 7" />
      </svg>
    </button>
  );
}

function Segmented({ options, value, onChange, ariaLabel }) {
  return (
    <div className="seg" role="radiogroup" aria-label={ariaLabel}>
      {options.map((o) => {
        const v = typeof o === "object" ? o.value : o;
        const l = typeof o === "object" ? o.label : o;
        return (
          <button
            key={v}
            type="button"
            role="radio"
            aria-checked={value === v}
            data-on={value === v ? "1" : "0"}
            onClick={() => onChange(v)}
          >
            {l}
          </button>
        );
      })}
    </div>
  );
}

// Multi-select pills — like Segmented but accepts an array of values.
function MultiPills({ options, values = [], onChange, ariaLabel }) {
  const toggle = (v) => {
    const set = new Set(values);
    if (set.has(v)) set.delete(v); else set.add(v);
    onChange([...set]);
  };
  return (
    <div className="pills" role="group" aria-label={ariaLabel}>
      {options.map((o) => {
        const v = typeof o === "object" ? o.value : o;
        const l = typeof o === "object" ? o.label : o;
        const on = values.includes(v);
        return (
          <button
            key={v}
            type="button"
            role="checkbox"
            aria-checked={on}
            data-on={on ? "1" : "0"}
            className="pill"
            onClick={() => toggle(v)}
          >
            <span className="pill-check" aria-hidden="true">
              {on && (
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 13l4 4L19 7" />
                </svg>
              )}
            </span>
            {l}
          </button>
        );
      })}
    </div>
  );
}

function CurrencyInput({ value, onChange, placeholder = "0", autoFocus, onEnter }) {
  const [local, setLocal] = React.useState(value ? Number(value).toLocaleString("en-US") : "");
  React.useEffect(() => {
    setLocal(value ? Number(value).toLocaleString("en-US") : "");
  }, [value]);
  const handle = (e) => {
    const raw = e.target.value.replace(/[^0-9]/g, "");
    if (raw === "") { setLocal(""); onChange(null); return; }
    const n = Number(raw);
    setLocal(n.toLocaleString("en-US"));
    onChange(n);
  };
  return (
    <div className="currency-wrap">
      <input
        className="input currency"
        type="text"
        inputMode="numeric"
        value={local}
        placeholder={placeholder}
        onChange={handle}
        autoFocus={autoFocus}
        onKeyDown={(e) => { if (e.key === "Enter" && onEnter) onEnter(); }}
      />
    </div>
  );
}

function TextInput({ value, onChange, placeholder, autoFocus, type = "text", onEnter, inputMode }) {
  return (
    <input
      className="input"
      type={type}
      inputMode={inputMode}
      value={value || ""}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      autoFocus={autoFocus}
      onKeyDown={(e) => { if (e.key === "Enter" && onEnter) onEnter(); }}
    />
  );
}

function formatPhone(s) {
  const d = String(s).replace(/[^0-9]/g, "").slice(0, 10);
  if (d.length <= 3) return d;
  if (d.length <= 6) return `(${d.slice(0,3)}) ${d.slice(3)}`;
  return `(${d.slice(0,3)}) ${d.slice(3,6)}-${d.slice(6)}`;
}

const US_STATES = ["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"];

const BALANCE_RANGES = [
  { value: "lt_25k",     label: "Under $25,000" },
  { value: "25_50k",     label: "$25,000 – $50,000" },
  { value: "50_100k",    label: "$50,000 – $100,000" },
  { value: "100_250k",   label: "$100,000 – $250,000" },
  { value: "250_500k",   label: "$250,000 – $500,000" },
  { value: "500k_1m",    label: "$500,000 – $1,000,000" },
  { value: "gt_1m",      label: "Over $1,000,000" },
];

const PAYMENT_RANGES = [
  { value: "lt_500",    label: "Under $500" },
  { value: "500_1k",    label: "$500 – $1,000" },
  { value: "1k_2.5k",   label: "$1,000 – $2,500" },
  { value: "2.5k_5k",   label: "$2,500 – $5,000" },
  { value: "5k_10k",    label: "$5,000 – $10,000" },
  { value: "gt_10k",    label: "Over $10,000" },
];

// ── Question wrapper ─────────────────────────────────────────────────────
function Q({ eyebrow, title, sub, children, hint }) {
  return (
    <>
      {eyebrow && <div className="q-eyebrow">{eyebrow}</div>}
      <h2 className="question">{title}</h2>
      {sub && <p className="sub">{sub}</p>}
      <div className="q-body">{children}</div>
      {hint && <p className="q-hint">{hint}</p>}
    </>
  );
}

// ── Q1 · Situation ───────────────────────────────────────────────────────
function QSituation({ data, set, onNext }) {
  const choose = (v) => {
    set("situation", v);
    if (window.__autoAdvance) setTimeout(onNext, 360);
  };
  return (
    <Q eyebrow="01 · Your situation"
       title="Where are you with your MCA payments right now?"
       sub="Pick the option closest to your situation — we'll tailor your consultation accordingly.">
      <div className="options">
        <OptionCard value="paying" current={data.situation} onSelect={choose}
          title="Still paying — but it's tight"
          hint="Daily/weekly draws are eating into payroll and operations." />
        <OptionCard value="behind" current={data.situation} onSelect={choose}
          title="Behind on payments"
          hint="Missed pulls, NSFs, or actively defaulting on one or more advances." />
        <OptionCard value="sued" current={data.situation} onSelect={choose}
          title="Been sued or COJ filed"
          hint="Confession of judgment, frozen accounts, or active litigation." />
        <OptionCard value="stacked" current={data.situation} onSelect={choose}
          title="Considering another advance"
          hint="Looking at stacking — want a second opinion before signing." />
      </div>
    </Q>
  );
}

// ── Q2 · Balance dropdown ────────────────────────────────────────────────
function QBalance({ data, set, onNext }) {
  return (
    <Q eyebrow="02 · The debt"
       title="What's your approximate total balance?"
       sub="All MCAs combined. We'll go through the exact figures on your call.">
      <div className="select-wrap">
        <select
          className="input select"
          value={data.balance || ""}
          autoFocus
          onChange={(e) => {
            set("balance", e.target.value);
            if (window.__autoAdvance && e.target.value) setTimeout(onNext, 280);
          }}
        >
          <option value="">Select a range…</option>
          {BALANCE_RANGES.map((r) => (
            <option key={r.value} value={r.value}>{r.label}</option>
          ))}
        </select>
        <svg className="select-caret" width="14" height="14" viewBox="0 0 24 24" fill="none"
             stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M6 9l6 6 6-6" />
        </svg>
      </div>
    </Q>
  );
}

// ── Q3 · Contact + optional additional info ──────────────────────────────
function QContact({ data, set }) {
  return (
    <Q eyebrow="03 · About you"
       title="Where should your advisor reach you?"
       sub="A real human will review your case before your call. No autodialers, no sales scripts.">
      <div className="form-grid">
        <div className="form-row two">
          <div>
            <label className="mini-label">First name <em>*</em></label>
            <TextInput value={data.firstName} onChange={(v) => set("firstName", v)} placeholder="Marcus" autoFocus />
          </div>
          <div>
            <label className="mini-label">Last name <em>*</em></label>
            <TextInput value={data.lastName} onChange={(v) => set("lastName", v)} placeholder="Renteria" />
          </div>
        </div>

        <div className="form-row">
          <label className="mini-label">Business name <em>*</em></label>
          <TextInput value={data.businessName} onChange={(v) => set("businessName", v)} placeholder="Renteria Logistics LLC" />
        </div>

        <div className="form-row two">
          <div>
            <label className="mini-label">Email <em>*</em></label>
            <TextInput type="email" inputMode="email" value={data.email} onChange={(v) => set("email", v)} placeholder="you@business.com" />
          </div>
          <div>
            <label className="mini-label">Phone <em>*</em></label>
            <TextInput type="tel" inputMode="tel"
                       value={data.phone}
                       onChange={(v) => set("phone", formatPhone(v))}
                       placeholder="(555) 123-4567" />
          </div>
        </div>

        <div className="form-row two narrow-second">
          <div>
            <label className="mini-label">State <em>*</em></label>
            <div className="select-wrap small">
              <select className="input select"
                      value={data.state || ""}
                      onChange={(e) => set("state", e.target.value)}>
                <option value="">Select…</option>
                {US_STATES.map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
              <svg className="select-caret" width="12" height="12" viewBox="0 0 24 24" fill="none"
                   stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M6 9l6 6 6-6" />
              </svg>
            </div>
          </div>
          <div />
        </div>
      </div>

      {/* Additional Information — all optional, surfaces below the required block */}
      <div className="additional-info">
        <div className="ai-header">
          <span className="ai-eyebrow">Additional information</span>
          <span className="ai-optional">All optional · helps us prep for the call</span>
        </div>

        <div className="form-grid">
          <div className="form-row">
            <label className="mini-label">Lender names</label>
            <TextInput value={data.lenders} onChange={(v) => set("lenders", v)}
                       placeholder="e.g. Kapitus, Rapid Finance, OnDeck" />
            <span className="hint">Helps us match you with an advisor who's negotiated with these funders before.</span>
          </div>

          <div className="form-row two narrow-second">
            <div>
              <label className="mini-label">Combined payment</label>
              <div className="select-wrap">
                <select className="input select"
                        value={data.payment || ""}
                        onChange={(e) => set("payment", e.target.value)}>
                  <option value="">Select a range…</option>
                  {PAYMENT_RANGES.map((r) => (
                    <option key={r.value} value={r.value}>{r.label}</option>
                  ))}
                </select>
                <svg className="select-caret" width="12" height="12" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M6 9l6 6 6-6" />
                </svg>
              </div>
            </div>
            <div>
              <label className="mini-label">How often?</label>
              <MultiPills
                ariaLabel="Payment frequency"
                options={[
                  { value: "daily", label: "Daily" },
                  { value: "weekly", label: "Weekly" },
                  { value: "monthly", label: "Monthly" },
                ]}
                values={data.frequency || []}
                onChange={(v) => set("frequency", v)}
              />
              <span className="hint">Tap all that apply — stacked advances often mix cadences.</span>
            </div>
          </div>
        </div>
      </div>
    </Q>
  );
}

// ── Q4 · Book a call (Cal.com style) ─────────────────────────────────────
function QSchedule({ data, set, onNext }) {
  const TZ_MAP = {
    ET: "America/New_York",
    CT: "America/Chicago",
    MT: "America/Denver",
    PT: "America/Los_Angeles",
    AK: "America/Anchorage",
    HI: "Pacific/Honolulu",
  };
  const iana = TZ_MAP[data.timezone || "ET"];

  // Build next 14 weekdays.
  const days = React.useMemo(() => {
    const out = [];
    const d = new Date();
    while (out.length < 14) {
      d.setDate(d.getDate() + 1);
      const dow = d.getDay();
      if (dow !== 0 && dow !== 6) out.push(new Date(d));
    }
    return out;
  }, []);
  const [selectedDay, setSelectedDay] = React.useState(0);
  const day = days[selectedDay];

  // Live slots loaded from Cal.com /api/cal/slots — keyed by YYYY-MM-DD in tz.
  const [slotsByDay, setSlotsByDay] = React.useState({});
  const [slotsLoading, setSlotsLoading] = React.useState(false);
  const [slotsError, setSlotsError] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  // YYYY-MM-DD key in the selected timezone for a given JS Date.
  const dayKey = React.useCallback((d) => {
    const parts = new Intl.DateTimeFormat("en-CA", {
      timeZone: iana, year: "numeric", month: "2-digit", day: "2-digit",
    }).formatToParts(d).reduce((acc, p) => { acc[p.type] = p.value; return acc; }, {});
    return `${parts.year}-${parts.month}-${parts.day}`;
  }, [iana]);

  // Fetch slots whenever tz changes — 10-day window.
  React.useEffect(() => {
    let aborted = false;
    const run = async () => {
      setSlotsLoading(true);
      setSlotsError(null);
      try {
        const today = new Date();
        const start = new Date(today); start.setDate(start.getDate() + 1);
        const end = new Date(today); end.setDate(end.getDate() + 21);
        const u = new URL("/api/cal/slots", window.location.origin);
        u.searchParams.set("startTime", start.toISOString());
        u.searchParams.set("endTime", end.toISOString());
        u.searchParams.set("timeZone", iana);
        const r = await fetch(u.toString(), { cache: "no-store" });
        const j = await r.json();
        if (aborted) return;
        if (!r.ok) { setSlotsError(j?.error || `error ${r.status}`); setSlotsByDay({}); return; }
        // j.slots is keyed by YYYY-MM-DD (in the requested tz)
        setSlotsByDay(j.slots || {});
      } catch (e) {
        if (!aborted) { setSlotsError(e?.message || "failed"); setSlotsByDay({}); }
      } finally {
        if (!aborted) setSlotsLoading(false);
      }
    };
    run();
    return () => { aborted = true; };
  }, [iana]);

  const fmtSlotLabel = (iso) => new Date(iso).toLocaleTimeString("en-US", {
    timeZone: iana, hour: "numeric", minute: "2-digit", hour12: true,
  }).toLowerCase().replace(" ", " ");
  const fmtDate = (d) => d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric", timeZone: iana });
  const fmtDateLong = (d) => d.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", timeZone: iana });

  const currentDayKey = dayKey(day);
  const slotsForDay = (slotsByDay[currentDayKey] || []).map((s) => ({ iso: s.time, label: fmtSlotLabel(s.time) }));

  const pickSlot = async (iso) => {
    if (submitting) return;
    set("slotIso", iso);
    set("slot", `${fmtDate(day)} @ ${fmtSlotLabel(iso)}`);
    setSubmitError(null);
    setSubmitting(true);
    try {
      // Compose notes from the captured form data
      const balanceLabel = (BALANCE_RANGES.find((r) => r.value === data.balance) || {}).label || data.balance || "—";
      const paymentLabel = (PAYMENT_RANGES.find((r) => r.value === data.payment) || {}).label || data.payment || "—";
      const situationLabel = ({
        paying: "Still paying — it's tight",
        behind: "Behind on payments",
        sued: "Been sued / COJ filed",
        stacked: "Considering another advance",
      })[data.situation] || data.situation || "—";
      const freq = Array.isArray(data.frequency) && data.frequency.length ? data.frequency.join(", ") : "—";
      const notes = [
        `Situation: ${situationLabel}`,
        `Balance: ${balanceLabel}`,
        `Business: ${data.businessName || "—"}`,
        `State: ${data.state || "—"}`,
        `Lender names: ${data.lenders || "—"}`,
        `Combined payment: ${paymentLabel}`,
        `Cadence: ${freq}`,
      ].join("\n");

      const utm = {};
      try {
        const sp = new URLSearchParams(window.location.search);
        ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach((k) => {
          const v = sp.get(k);
          if (v) utm[k] = v;
        });
      } catch {}

      const r = await fetch("/api/cal/book", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          start: iso,
          timeZone: iana,
          name: `${data.firstName || ""} ${data.lastName || ""}`.trim(),
          email: data.email,
          phone: data.phone,
          meetingType: (data.meetingType === "video" || data.meetingType === "zoom") ? "video" : "phone",
          notes,
          utm,
        }),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok || !j.ok) {
        setSubmitError(j?.error || `booking failed (${r.status})`);
        setSubmitting(false);
        set("slot", "");
        set("slotIso", "");
        return;
      }
      set("bookingId", j.uid || j.id || "");
      setTimeout(onNext, 220);
    } catch (e) {
      setSubmitError(e?.message || "booking failed");
      setSubmitting(false);
      set("slot", "");
      set("slotIso", "");
    }
  };

  return (
    <Q eyebrow="04 · Book your strategy call"
       title={data.firstName
         ? `${data.firstName}, pick a time and a senior advisor will review your case before the call.`
         : `Pick a time and a senior advisor will review your case before the call.`}
       sub="30-minute call · Pricing reviewed on the call · No obligation · Recorded only if you want a copy">

      <div className="cal-card">
        <aside className="cal-side">
          <div className="cal-advisor-pending">
            <div className="cal-pending-icon" aria-hidden="true">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="8" r="4"/><path d="M4 21v-1a8 8 0 0 1 16 0v1"/>
              </svg>
            </div>
            <div>
              <div className="cal-advisor-name">Senior advisor</div>
              <div className="cal-advisor-role">Matched after your booking</div>
            </div>
          </div>
          <div className="cal-meta-row">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>
            <span>30 min</span>
          </div>

          <div className="cal-field">
            <label className="cal-field-label">Format</label>
            <Segmented
              ariaLabel="Meeting format"
              options={[
                { value: "phone", label: "Phone" },
                { value: "video", label: "Cal Video" },
              ]}
              value={data.meetingType || "phone"}
              onChange={(v) => set("meetingType", v)}
            />
          </div>

          <div className="cal-field">
            <label className="cal-field-label">Time zone</label>
            <div className="select-wrap small">
              <select
                className="input select"
                value={data.timezone || "ET"}
                onChange={(e) => set("timezone", e.target.value)}
              >
                <option value="ET">Eastern (ET)</option>
                <option value="CT">Central (CT)</option>
                <option value="MT">Mountain (MT)</option>
                <option value="PT">Pacific (PT)</option>
                <option value="AK">Alaska (AKT)</option>
                <option value="HI">Hawaii (HST)</option>
              </select>
              <svg className="select-caret" width="12" height="12" viewBox="0 0 24 24" fill="none"
                   stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M6 9l6 6 6-6" />
              </svg>
            </div>
          </div>
          <div className="cal-prep">
            <div className="cal-prep-title">Before your call</div>
            <ul>
              <li>Have copies of your MCA contracts ready (PDFs are fine)</li>
              <li>Last 3 months of business bank statements</li>
              <li>Any COJ or legal notices you've received</li>
            </ul>
          </div>
        </aside>

        <div className="cal-main">
          <div className="cal-section-label">Select a day</div>
          <div className="cal-days">
            {days.slice(0, 10).map((d, i) => (
              <button key={i}
                      className={`cal-day ${i === selectedDay ? "on" : ""}`}
                      onClick={() => setSelectedDay(i)}>
                <div className="cal-day-dow">{d.toLocaleDateString("en-US", { weekday: "short" })}</div>
                <div className="cal-day-num">{d.getDate()}</div>
                <div className="cal-day-mo">{d.toLocaleDateString("en-US", { month: "short" })}</div>
              </button>
            ))}
          </div>

          <div className="cal-section-label">
            Available times — <span>{fmtDateLong(day)}</span>
          </div>
          <div className="cal-slots">
            {slotsLoading && (
              <div style={{gridColumn:"1 / -1", padding:"24px 0", color:"var(--ink-3)", fontSize:13}}>Loading times…</div>
            )}
            {!slotsLoading && slotsError && (
              <div style={{gridColumn:"1 / -1", padding:"24px 0", color:"#9b2c2c", fontSize:13}}>Couldn't load times — {slotsError}</div>
            )}
            {!slotsLoading && !slotsError && slotsForDay.length === 0 && (
              <div style={{gridColumn:"1 / -1", padding:"24px 0", color:"var(--ink-3)", fontSize:13}}>No times available on this day — pick another.</div>
            )}
            {slotsForDay.map((s) => (
              <button
                key={s.iso}
                className={`cal-slot ${data.slotIso === s.iso ? "on" : ""}`}
                disabled={submitting}
                onClick={() => pickSlot(s.iso)}
              >{s.label}</button>
            ))}
          </div>

          {submitError && (
            <div style={{marginTop:12, padding:"10px 12px", border:"1px solid #f5c6c6", background:"#fff5f5", color:"#9b2c2c", borderRadius:8, fontSize:13}}>
              {submitError}
            </div>
          )}
          {submitting && !submitError && (
            <div style={{marginTop:12, padding:"10px 12px", border:"1px solid var(--rule)", background:"#fff", color:"var(--ink-2)", borderRadius:8, fontSize:13}}>
              Booking your call…
            </div>
          )}

          <div className="cal-footnote">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
            <span>Scheduling powered by <b>Cal.com</b> · Calendar invite emailed instantly</span>
          </div>
        </div>
      </div>
    </Q>
  );
}

// Resource tabs surfaced on the thank-you page — interactive Payment
// Calculator + Free eBook offer.
function ResourceTabs({ data }) {
  const [tab, setTab] = React.useState("calc");

  return (
    <div className="resource-tabs">
      <div className="rt-tablist" role="tablist">
        <button role="tab" aria-selected={tab === "calc"} data-on={tab === "calc" ? "1" : "0"}
                className="rt-tab" onClick={() => setTab("calc")}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
               strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <rect x="4" y="3" width="16" height="18" rx="2"/>
            <path d="M8 7h8M8 11h8M8 15h4"/>
          </svg>
          Payment calculator
        </button>
        <button role="tab" aria-selected={tab === "ebook"} data-on={tab === "ebook" ? "1" : "0"}
                className="rt-tab" onClick={() => setTab("ebook")}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
               strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20V3H6.5A2.5 2.5 0 0 0 4 5.5v14z"/>
            <path d="M4 19.5A2.5 2.5 0 0 0 6.5 22H20"/>
          </svg>
          Free eBook: Settle your own MCA debt
          <span className="rt-tab-badge">Free</span>
        </button>
      </div>

      {tab === "calc" && (
        <div className="rt-panel" role="tabpanel">
          <div className="rt-redirect">
            <div className="rt-redirect-icon" aria-hidden="true">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <rect x="4" y="3" width="16" height="18" rx="2"/>
                <path d="M8 7h8M8 11h8M8 15h4"/>
              </svg>
            </div>
            <div className="rt-redirect-body">
              <div className="rt-redirect-eyebrow">Take 90 seconds</div>
              <h3 className="rt-redirect-title">Get a tailored payment-reduction estimate.</h3>
              <p className="rt-redirect-sub">
                Our calculator walks through your specific contract terms and produces a written estimate of where your monthly outflow could land after restructuring. Takes a few extra details about your debt structure.
              </p>
              <ul className="rt-redirect-list">
                <li><span className="diamond" />Per-lender breakdown, not just totals</li>
                <li><span className="diamond" />Realistic reduction range based on your state and lenders</li>
                <li><span className="diamond" />Emailed as a PDF so you can compare to other offers</li>
              </ul>
              <a className="primary rt-redirect-cta"
                 href="https://apply.businessdebtadjusters.net/calculator"
                 onClick={(e) => { e.preventDefault(); alert("In production this redirects to the calculator capture form."); }}>
                Open the calculator
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M12 5l7 7-7 7" />
                </svg>
              </a>
              <div className="rt-redirect-foot">Opens in a new step · About 90 seconds</div>
            </div>
          </div>
        </div>
      )}

      {tab === "ebook" && (
        <div className="rt-panel" role="tabpanel">
          <div className="rt-ebook">
            <div className="rt-ebook-cover" aria-hidden="true">
              <div className="rt-ebook-cover-eyebrow">Free guide · 42 pages</div>
              <div className="rt-ebook-cover-title">Settle Your Own<br />MCA Debt</div>
              <div className="rt-ebook-cover-sub">A practical playbook for small-business owners</div>
              <div className="rt-ebook-cover-mark">BDA</div>
            </div>
            <div className="rt-ebook-meta">
              <div className="rt-ebook-eyebrow">Free download</div>
              <h3 className="rt-ebook-title">Negotiate with your funders — without a lawyer.</h3>
              <p className="rt-ebook-sub">
                The exact playbook we walk advisors through: how to read your MCA contract,
                what leverage points work, and the email scripts to open a settlement conversation.
              </p>
              <ul className="rt-ebook-list">
                <li><span className="diamond" />Contract anatomy: COJ clauses, reconciliation triggers, default mechanics</li>
                <li><span className="diamond" />Three opening-letter templates that have produced 40%+ reductions</li>
                <li><span className="diamond" />When to settle vs. consolidate vs. litigate — a decision flowchart</li>
              </ul>
              <form className="rt-ebook-form" onSubmit={(e) => { e.preventDefault(); alert("In production this would email the PDF."); }}>
                <input type="email" className="input"
                       defaultValue={data.email || ""}
                       placeholder="you@business.com"
                       aria-label="Email for eBook" />
                <button className="primary" type="submit">
                  Send me the eBook
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                       strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M5 12h14M12 5l7 7-7 7" />
                  </svg>
                </button>
              </form>
              <div className="rt-ebook-trust">PDF delivered instantly · No marketing list</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Confirmation / Thank You (after Cal.com slot picked) ────────────────
function StepConfirm({ data }) {
  const first = data.firstName || "there";
  const balanceLabel = (BALANCE_RANGES.find((r) => r.value === data.balance) || {}).label || "—";
  const slotParts = (data.slot || "").split(" @ ");
  const slotDate = slotParts[0] || "Soon";
  const slotTime = slotParts[1] || "TBD";
  const tzLabel = ({
    ET: "Eastern Time", CT: "Central Time", MT: "Mountain Time",
    PT: "Pacific Time", AK: "Alaska Time", HI: "Hawaii Time",
  })[data.timezone || "ET"];
  const fmt = (data.meetingType === "video" || data.meetingType === "zoom") ? "Cal Video call" : "Phone call";

  return (
    <div className="thanks">
      <div className="thanks-hero">
        <div className="thanks-ribbon">
          <span className="thanks-tick" aria-hidden="true">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 13l4 4L19 7" />
            </svg>
          </span>
          Your call is booked
        </div>
        <h1 className="thanks-title">Thank you, {first}.</h1>
        <p className="thanks-sub">
          We've blocked your time and sent a calendar invite to <b>{data.email || "your inbox"}</b>.
          A senior advisor will be matched to your case and will reach out before the call.
        </p>
      </div>

      <div className="thanks-callcard">
        <div className="thanks-callcard-head">
          <div className="thanks-callcard-eyebrow">Your strategy call</div>
          <div className="thanks-callcard-date">{slotDate}</div>
          <div className="thanks-callcard-time">{slotTime} <span>· 30 min · {tzLabel} · {fmt}</span></div>
        </div>
        <div className="thanks-callcard-meta">
          <div className="thanks-advisor-pending">
            <div className="cal-pending-icon" aria-hidden="true">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="8" r="4"/><path d="M4 21v-1a8 8 0 0 1 16 0v1"/>
              </svg>
            </div>
            <div>
              <div className="thanks-advisor-name">Senior advisor</div>
              <div className="thanks-advisor-role">Matched after your booking</div>
            </div>
          </div>
          <div className="thanks-actions">
            <a className="primary" href="#"
               onClick={(e) => { e.preventDefault(); alert("In production this would generate a .ics file."); }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/>
              </svg>
              Add to calendar
            </a>
            <a className="ghost" href="#"
               onClick={(e) => { e.preventDefault(); alert("Reschedule flow in production."); }}>
              Reschedule
            </a>
          </div>
        </div>
      </div>

      <div className="thanks-videos">
        <div className="thanks-video-main">
          <div className="thanks-pane-label">Next steps · Watch this first</div>
          <div className="video-frame main" data-noncommentable="">
            <div className="video-poster" aria-hidden="true">
              <div className="video-poster-bg" />
              <button className="video-play" aria-label="Play next steps video">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                  <path d="M8 5v14l11-7z" />
                </svg>
              </button>
              <div className="video-meta">
                <div className="video-meta-title">What happens after you book</div>
                <div className="video-meta-sub">2:14 · A walkthrough of the contract review process</div>
              </div>
            </div>
            {/* === NEXT STEPS VIDEO PLACEHOLDER =================================
               Replace this div's contents with the production embed, e.g.:
                 <iframe src="https://player.vimeo.com/video/XXXXXX" allowfullscreen />
               or a <video> tag pointing at your CDN.
               ============================================================== */}
          </div>
        </div>

        <div className="thanks-video-side">
          <div className="thanks-pane-label">Stories from owners we've helped</div>
          <UgcRail />
        </div>
      </div>

      <ResourceTabs data={data} />

      <div className="thanks-grid">
        <div className="thanks-pane">
          <div className="thanks-pane-label">Before your call</div>
          <ul className="thanks-list">
            <li><span className="diamond" />Have copies of your MCA contracts ready (PDFs are fine)</li>
            <li><span className="diamond" />Last 3 months of business bank statements</li>
            <li><span className="diamond" />Any COJ or legal notices you've received</li>
          </ul>
          <p className="thanks-note">Send anything early to <a href="mailto:advisors@example.com">advisors@example.com</a>. Your advisor will review materials before the call.</p>
        </div>
        <div className="thanks-pane">
          <div className="thanks-pane-label">Case summary</div>
          <dl className="thanks-summary">
            <div><dt>Situation</dt><dd>{({paying:"Still paying — it's tight",behind:"Behind on payments",sued:"Been sued / COJ filed",stacked:"Considering another advance"})[data.situation] || "—"}</dd></div>
            <div><dt>Balance range</dt><dd>{balanceLabel}</dd></div>
            <div><dt>Business</dt><dd>{data.businessName || "—"}</dd></div>
            <div><dt>State</dt><dd>{data.state || "—"}</dd></div>
          </dl>
        </div>
      </div>

      <div className="thanks-links">
        <div className="thanks-pane-label">Explore while you wait</div>

        <div className="thanks-feature-grid">
          <a className="thanks-feature" href="https://businessdebtadjusters.com/team" target="_blank" rel="noopener">
            <div className="thanks-feature-media team-media" aria-hidden="true">
              <div className="team-avatars">
                <span className="team-avatar a1">DP</span>
                <span className="team-avatar a2">JK</span>
                <span className="team-avatar a3">SR</span>
                <span className="team-avatar a4">MV</span>
              </div>
              <div className="thanks-feature-tag">14 advisors</div>
            </div>
            <div className="thanks-feature-body">
              <div className="thanks-feature-eyebrow">The advisors</div>
              <div className="thanks-feature-title">Meet the team</div>
              <div className="thanks-feature-sub">
                Senior restructuring advisors with 9+ years of MCA negotiation experience.
                One of them is reviewing your case right now.
              </div>
              <div className="thanks-feature-cta">
                Meet the team
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M12 5l7 7-7 7" />
                </svg>
              </div>
            </div>
          </a>

          <a className="thanks-feature" href="https://businessdebtadjusters.com/about" target="_blank" rel="noopener">
            <div className="thanks-feature-media about-media" aria-hidden="true">
              <div className="about-stat">
                <div className="about-stat-big">$500M<span>+</span></div>
                <div className="about-stat-sub">in MCA balances reviewed</div>
              </div>
              <div className="about-stat secondary">
                <div className="about-stat-big">11<span>yrs</span></div>
                <div className="about-stat-sub">in business</div>
              </div>
            </div>
            <div className="thanks-feature-body">
              <div className="thanks-feature-eyebrow">The firm</div>
              <div className="thanks-feature-title">About us</div>
              <div className="thanks-feature-sub">
                Founded in 2014. Privately held. Independent of any funder or lender —
                our incentives are aligned with yours.
              </div>
              <div className="thanks-feature-cta">
                Read our story
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M12 5l7 7-7 7" />
                </svg>
              </div>
            </div>
          </a>
        </div>

        <div className="thanks-utility-row">
          <a className="thanks-utility" href="https://businessdebtadjusters.com" target="_blank" rel="noopener">
            <span className="thanks-utility-icon" aria-hidden="true">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/>
              </svg>
            </span>
            <span>businessdebtadjusters.com</span>
            <span className="thanks-utility-chev">↗</span>
          </a>
          <a className="thanks-utility wa" href="https://wa.me/18778170404" target="_blank" rel="noopener">
            <span className="thanks-utility-icon wa-icon" aria-hidden="true">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9s-.5-.1-.7.1-.8.9-1 1.1-.4.2-.6.1c-.3-.1-1.2-.4-2.4-1.4-.9-.8-1.5-1.7-1.6-2s0-.4.1-.5l.4-.4c.1-.1.2-.3.2-.4s.1-.3 0-.5c0 0-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1.1 1-1.1 2.5s1.1 3 1.3 3.2c.1.2 2.2 3.4 5.3 4.7 1.9.7 2.6.8 3.5.7.5-.1 1.7-.7 2-1.3.2-.7.2-1.2.2-1.3-.1-.2-.3-.2-.6-.4zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.3c1.4.8 3 1.3 4.8 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18c-1.7 0-3.2-.5-4.5-1.3l-.3-.2-3.2.8.9-3.1-.2-.3C3.8 15 3.3 13.5 3.3 12 3.3 7.2 7.2 3.3 12 3.3S20.7 7.2 20.7 12 16.8 20 12 20z"/>
              </svg>
            </span>
            <span>WhatsApp an advisor now</span>
            <span className="thanks-utility-chev">↗</span>
          </a>
        </div>

        <div className="thanks-social">
          <div className="thanks-pane-label">See what people say</div>
          <SocialLinks variant="thanks" />
        </div>
      </div>

      <div className="thanks-footer">
        <div className="thanks-footer-cell">
          <div className="l">Need to reach us before the call?</div>
          <div className="v"><a href="tel:18778170404">(877) 817-0404</a> · M–F 9–6 ET</div>
        </div>
        <div className="thanks-footer-cell">
          <div className="l">Reference number</div>
          <div className="v mono">BDA-{Math.floor(Math.random()*900000)+100000}</div>
        </div>
      </div>
    </div>
  );
}

// ── Question registry — flat list, 4 pages ───────────────────────────────
const QUESTIONS = [
  { id: "situation", section: "Situation", component: "QSituation", validate: (d) => !!d.situation, optional: false },
  { id: "balance",   section: "Balance",   component: "QBalance",   validate: (d) => !!d.balance,   optional: false },
  { id: "contact",   section: "Contact",   component: "QContact",
    validate: (d) => !!d.firstName && !!d.lastName && !!d.businessName && !!d.state
                  && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.email || "")
                  && String(d.phone || "").replace(/[^0-9]/g, "").length === 10,
    optional: false },
  { id: "schedule",  section: "Book",      component: "QSchedule",  validate: (d) => !!d.slot, optional: false },
];

// Featured-story rail on the thank-you page. One big featured video, plus a
// scrollable grid of smaller thumbnails for the rest of the library.
function UgcRail() {
  const [activeIdx, setActiveIdx] = React.useState(0);
  const videoRef = React.useRef(null);
  const [muted, setMuted] = React.useState(true);
  const lib = window.UGC_LIBRARY;
  const active = lib[activeIdx];

  // Restart playback whenever the selected clip changes.
  React.useEffect(() => {
    const v = videoRef.current;
    if (v) { v.load(); v.play().catch(() => {}); }
  }, [activeIdx]);

  const toggleMute = () => {
    const v = videoRef.current;
    if (!v) return;
    v.muted = !v.muted;
    setMuted(v.muted);
  };

  return (
    <div className="ugc-rail" data-noncommentable="">
      <div className="ugc-rail-feature">
        <video
          ref={videoRef}
          className="ugc-rail-feature-video"
          autoPlay loop muted playsInline preload="metadata"
          src={active.src}
          key={active.src}
        ></video>
        <div className="ugc-rail-feature-overlay">
          <div className="ugc-watermark" aria-hidden="true">
            <img src="assets/bda-logo-on-navy.png?v=3" alt="" />
          </div>
          <div className="ugc-lower-third">
            <div className="ugc-lt-accent" aria-hidden="true" />
            <div className="ugc-lt-body">
              <div className="ugc-namecard-name">{active.name}</div>
              <div className="ugc-namecard-role">Verified client</div>
            </div>
            <button type="button" className="ugc-mute" onClick={toggleMute}
                    aria-label={muted ? "Unmute" : "Mute"}>
              {muted ? (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M11 5 6 9H2v6h4l5 4z"/>
                  <line x1="22" y1="9" x2="16" y2="15"/>
                  <line x1="16" y1="9" x2="22" y2="15"/>
                </svg>
              ) : (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M11 5 6 9H2v6h4l5 4z"/>
                  <path d="M15.5 8.5a5 5 0 0 1 0 7"/>
                  <path d="M18.5 5.5a9 9 0 0 1 0 13"/>
                </svg>
              )}
            </button>
          </div>
        </div>
      </div>

      <div className="ugc-rail-thumbs">
        {lib.map((v, i) => (
          <button
            key={v.src}
            type="button"
            className={`ugc-rail-thumb ${i === activeIdx ? "on" : ""}`}
            aria-label={`Play ${v.name}`}
            onMouseEnter={(e) => {
              const tv = e.currentTarget.querySelector("video");
              if (tv) tv.play().catch(() => {});
            }}
            onMouseLeave={(e) => {
              const tv = e.currentTarget.querySelector("video");
              if (tv) { tv.pause(); tv.currentTime = 0; }
            }}
            onClick={() => setActiveIdx(i)}
          >
            <video
              className="ugc-rail-thumb-video"
              src={v.src}
              muted
              playsInline
              loop
              preload="none"
            ></video>
            <span className="ugc-rail-thumb-name">{v.name}</span>
            <span className="ugc-rail-thumb-play">
              <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M8 5v14l11-7z" />
              </svg>
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, {
  QSituation, QBalance, QContact, QSchedule,
  StepConfirm, QUESTIONS,
  OptionCard, Segmented, MultiPills, CurrencyInput, TextInput, formatPhone,
  BALANCE_RANGES, PAYMENT_RANGES, UgcRail,
});
