/* ============================================================
   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 = (
    <React.Fragment>
      <span className="top">TOP</span>
      <span className="wheels">Wheels</span>
      <span className="io">.io</span>
    </React.Fragment>
  );
  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>
  );
}

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