/* ============================================================
   TOP WHEELS Funnel — shared atoms / form controls
   Exposes components on window for the other babel scripts.
   ============================================================ */
const { useState, useRef, useEffect, useCallback } = React;

const ICON_HREF = (typeof window !== "undefined" && window.__ICON_HREF != null) ? window.__ICON_HREF : "assets/icons.svg";
function Icon({ name, className = "", style }) {
  return (
    <svg className={`icon ${className}`} aria-hidden="true" style={style}>
      <use href={`${ICON_HREF}#${name}`} />
    </svg>
  );
}

function BrandLogo({ className = "", href = "/" }) {
  const inner = <img src="/brand/topwheels-logo.svg" alt="TOP Wheels" />;
  if (href) {
    return (
      <a className={`brand-logo ${className}`} href={href} aria-label="TOP Wheels — go to homepage">
        {inner}
      </a>
    );
  }
  return <span className={`brand-logo ${className}`}>{inner}</span>;
}

/* ---------- Choice cards (single-select radio group) ---------- */
function ChoiceGroup({ options, value, onChange, columns, compact, triplet, name }) {
  const colClass = triplet
    ? "triplet"
    : columns === 2 ? "cols-2" : columns === 3 ? "cols-3" : "";
  return (
    <div className={`choices ${colClass}`} role="radiogroup" aria-label={name}>
      {options.map((opt) => {
        const sel = value === opt.value;
        return (
          <button
            type="button"
            key={opt.value}
            role="radio"
            aria-checked={sel}
            className={`choice ${compact ? "compact" : ""} ${sel ? "sel" : ""}`}
            onClick={() => onChange(opt.value)}
          >
            {!compact && opt.icon && (
              <span className="ic"><Icon name={opt.icon} /></span>
            )}
            <span className="ctext">
              <span className="ctitle">{opt.label}</span>
              {opt.sub && <span className="csub">{opt.sub}</span>}
            </span>
            {!compact && (
              <span className="tick"><Icon name="check" /></span>
            )}
          </button>
        );
      })}
    </div>
  );
}

/* ---------- Field wrapper ---------- */
function Field({ label, optional, error, children, span }) {
  return (
    <div className={`field ${span === 2 ? "col-span-2" : span === "full" ? "col-span-full" : ""}`}>
      {label && (
        <label className="flabel">
          {label}
          {optional && <span className="optional">· optional</span>}
        </label>
      )}
      {children}
      {error && (
        <span className="ferror"><Icon name="alert-triangle" />{error}</span>
      )}
    </div>
  );
}

/* ---------- Text input ---------- */
function TextInput({ value, onChange, placeholder, error, mono, type = "text",
                     inputMode, maxLength, autoComplete, transform, onBlur, prefix }) {
  const handle = (e) => {
    let v = e.target.value;
    if (transform) v = transform(v);
    if (maxLength) v = v.slice(0, maxLength);
    onChange(v);
  };
  const input = (
    <input
      className={`control ${mono ? "mono" : ""} ${error ? "invalid" : ""}`}
      type={type}
      value={value || ""}
      onChange={handle}
      onBlur={onBlur}
      placeholder={placeholder}
      inputMode={inputMode}
      autoComplete={autoComplete}
      maxLength={maxLength}
    />
  );
  if (prefix) {
    return (
      <div className="affix">
        <span className="pfx">{prefix}</span>
        {input}
      </div>
    );
  }
  return input;
}

/* ---------- Select ---------- */
function SelectInput({ value, onChange, options, placeholder, error }) {
  return (
    <select
      className={`control ${!value ? "placeholder" : ""} ${error ? "invalid" : ""}`}
      value={value || ""}
      onChange={(e) => onChange(e.target.value)}
    >
      <option value="" disabled hidden>{placeholder || "Select…"}</option>
      {options.map((o) => (
        <option key={o.value || o} value={o.value || o}>{o.label || o}</option>
      ))}
    </select>
  );
}

/* ---------- Phone (country code + auto-format), US default ---------- */
const COUNTRIES = [
  { code: "+1",  iso: "US", label: "🇺🇸 +1" },
  { code: "+1",  iso: "CA", label: "🇨🇦 +1" },
  { code: "+44", iso: "GB", label: "🇬🇧 +44" },
  { code: "+52", iso: "MX", label: "🇲🇽 +52" },
  { code: "+61", iso: "AU", label: "🇦🇺 +61" },
  { code: "+91", iso: "IN", label: "🇮🇳 +91" },
  { code: "+63", iso: "PH", label: "🇵🇭 +63" },
  { code: "+49", iso: "DE", label: "🇩🇪 +49" },
  { code: "+33", iso: "FR", label: "🇫🇷 +33" },
  { code: "+34", iso: "ES", label: "🇪🇸 +34" },
  { code: "+55", iso: "BR", label: "🇧🇷 +55" },
  { code: "+971", iso: "AE", label: "🇦🇪 +971" },
  { code: "+",   iso: "XX", label: "🌐 Other" },
];

function formatPhone(digits, cc) {
  const d = digits.replace(/\D/g, "");
  if (cc === "+1") {
    const p = d.slice(0, 10);
    if (p.length <= 3) return p;
    if (p.length <= 6) return `(${p.slice(0,3)}) ${p.slice(3)}`;
    return `(${p.slice(0,3)}) ${p.slice(3,6)}-${p.slice(6)}`;
  }
  // light international grouping
  return d.replace(/(\d{3})(?=\d)/g, "$1 ").trim();
}

function PhoneField({ value, ccValue, onChange, onCc, error }) {
  return (
    <div className="phone">
      <select className="cc" value={ccValue} onChange={(e) => onCc(e.target.value)} aria-label="Country code">
        {COUNTRIES.map((c, i) => (
          <option key={c.iso + i} value={c.code}>{c.label}</option>
        ))}
      </select>
      <input
        className={`control mono ${error ? "invalid" : ""}`}
        type="tel"
        inputMode="tel"
        autoComplete="tel"
        placeholder={ccValue === "+1" ? "(555) 123-4567" : "phone number"}
        value={value || ""}
        onChange={(e) => onChange(formatPhone(e.target.value, ccValue))}
      />
    </div>
  );
}

/* ---------- Progress (mono STEP n/total + thin bar) ---------- */
function Progress({ index, total, name, saved }) {
  const pct = Math.max(0, Math.min(100, (index / (total - 1)) * 100));
  return (
    <div className="progress-wrap">
      <div className="progress-meta">
        <span className="progress-label">
          STEP {String(index + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
        </span>
        {saved
          ? <span className="progress-saved"><Icon name="check" /> Progress saved</span>
          : <span className="progress-name">{name}</span>}
      </div>
      <div className="progress-track">
        <div className="progress-fill" style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}

/* ---------- Buttons ---------- */
function PrimaryBtn({ children, onClick, disabled, variant = "primary", size, icon }) {
  return (
    <button
      type="button"
      className={`btn btn-${variant} ${size === "lg" ? "btn-lg" : ""}`}
      onClick={onClick}
      disabled={disabled}
    >
      {children}
      {icon && <Icon name={icon} />}
    </button>
  );
}

/* ---------- TOP Wheels Terms & Pricing (intake review + accept) ---------- */
const TC_FEES = [
  ["Motorcycles / Small Off-Road", "$1,050"],
  ["Cars / Pickups / SUVs", "$1,250"],
  ["RVs / Boats / Trailers", "$1,350"],
  ["Commercial Trucks / Exotics", "$1,500"],
  ["Yachts / Houseboats / Aircraft", "$2,000"],
];
const TC_SCOPE = [
  ["Coordination Call", "A dedicated call to answer questions, provide clarity, and coordinate the transaction to completion."],
  ["Document Provision", "We provide the necessary documents, including state-specific documents, with additions based on the mutual agreement of both parties. All documents are reviewed and agreed upon by both parties."],
  ["Notarization", "We ensure documents are notarized through our partner notary service, enabling direct interaction with a certified notary."],
  ["Escrow Handling", "TOP Wheels manages the escrow transaction based on the prior agreement of both parties."],
  ["Vehicle Insurance Verification", "We help verify the buyer carries appropriate insurance, including considerations for adding the seller to the policy."],
  ["Potential Vehicle Issues", "We address concerns around insurance claims, police interactions, impound challenges, total loss, and related scenarios."],
  ["DMV / FAA Process Guidelines", "We provide documentation and guidance on state-specific DMV / FAA processes."],
];

function AgreementModal({ open, onClose, onAccept }) {
  const bodyRef = useRef(null);
  const [atBottom, setAtBottom] = useState(false);
  useEffect(() => {
    if (!open) { setAtBottom(false); return; }
    const el = bodyRef.current;
    if (el) {
      el.scrollTop = 0;
      requestAnimationFrame(() => {
        if (el.scrollHeight - el.clientHeight < 24) setAtBottom(true);
      });
    }
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [open]);
  if (!open) return null;
  const onScroll = (e) => {
    const el = e.target;
    if (el.scrollTop + el.clientHeight >= el.scrollHeight - 24) setAtBottom(true);
  };
  return (
    <div className="tos-overlay" onClick={onClose}>
      <div className="tos-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="TOP Wheels Terms & Pricing">
        <div className="tos-head">
          <div>
            <div className="tos-eyebrow">Before You Book</div>
            <h3>Terms &amp; Pricing</h3>
          </div>
          <button className="tos-x" onClick={onClose} aria-label="Close">
            <Icon name="x" />
          </button>
        </div>
        <div className="tos-readbar"><Icon name="arrow-down" /> Quick read — scroll to the bottom to accept.</div>
        <div className="tos-body" ref={bodyRef} onScroll={onScroll}>
          <p className="tos-lead">A quick overview of what TOP Wheels does and what it costs — so you know exactly what you're booking. TOP Wheels provides the specific services described below and <strong>does not act as an attorney, consultant, broker, or intermediary</strong> in any transaction.</p>

          <div className="tos-free"><Icon name="check" /> Your transparency call is <strong>100% free</strong> — nothing to pay to book it, and no obligation. Any coordination fee is only discussed and agreed on the call, if you choose to move forward.</div>

          <h4>What We Coordinate</h4>
          <ol className="tos-scope">
            {TC_SCOPE.map(([t, d], i) => (
              <li key={i}><strong>{t}.</strong> {d}</li>
            ))}
          </ol>

          <h4>Service Fee by Vehicle Class</h4>
          <table className="tos-fees">
            <tbody>
              {TC_FEES.map(([c, f], i) => (
                <tr key={i}><td>{c}</td><td>{f}</td></tr>
              ))}
            </tbody>
          </table>
          <p className="tos-note">The service-fee arrangement — whether borne by the buyer or split between parties — is discussed and documented during the coordination call based on mutual understanding.</p>

          <h4>Acknowledgment</h4>
          <p>By accepting, you acknowledge you've reviewed how TOP Wheels works and its pricing. TOP Wheels functions in a specified capacity without taking on legal, brokerage, or intermediary roles. Engaging our services is not a substitute for legal or professional advice — you're encouraged to seek independent legal counsel if you have questions about the transaction. Full terms are provided in your service agreement when your deal moves forward.</p>
          <p className="tos-fine">Accepting here simply lets us book your free transparency call — no payment and no obligation until you choose to move forward.</p>
        </div>
        <div className="tos-foot">
          {!atBottom && <span className="tos-scrollhint"><Icon name="arrow-down" /> Scroll to the bottom to accept</span>}
          <PrimaryBtn variant="primary" icon="check" disabled={!atBottom} onClick={onAccept}>
            I Accept
          </PrimaryBtn>
        </div>
      </div>
    </div>
  );
}

function AcceptConsent({ accepted, error, onOpen }) {
  return (
    <div className={`tos-consent ${error ? "invalid" : ""}`}>
      <button type="button" className={`tos-check ${accepted ? "on" : ""}`} onClick={onOpen}
        aria-pressed={accepted} aria-label="Review and accept the service agreement">
        {accepted && <Icon name="check" />}
      </button>
      <div className="tos-consent-text">
        {accepted ? (
          <span>You've reviewed TOP Wheels' <button type="button" className="tos-link" onClick={onOpen}>Terms &amp; Pricing</button>.</span>
        ) : (
          <span>I've reviewed and accept TOP Wheels' <button type="button" className="tos-link" onClick={onOpen}>Terms &amp; Pricing</button>.</span>
        )}
        {error && <span className="tos-err">{error}</span>}
      </div>
    </div>
  );
}

Object.assign(window, {
  Icon, BrandLogo, ChoiceGroup, Field, TextInput, SelectInput,
  PhoneField, Progress, PrimaryBtn, COUNTRIES, formatPhone,
  AgreementModal, AcceptConsent,
});
