/* ============================================================
   TOP WHEELS Funnel — step content renderers
   Each renderer returns the inner content for a step; the shell
   (app.jsx) wraps it with progress + footer nav.
   ============================================================ */
const {
  Icon, BrandLogo, ChoiceGroup, Field, TextInput, SelectInput, PhoneField, PrimaryBtn,
} = window;

/* ---------- option data ---------- */
const OPT = {
  subTo: [
    { value: "yes", label: "Yes — I'm in", icon: "check", sub: "Active SubTo student" },
    { value: "no", label: "Not yet", icon: "user", sub: "Outside the community" },
    { value: "deciding", label: "Still deciding", icon: "search", sub: "Looking into it" },
  ],
  needsHelp: [
    { value: "yes", label: "Yes — I have a deal", icon: "handshake", sub: "Need it coordinated" },
    { value: "no", label: "No, just browsing", icon: "search", sub: "Not right now" },
    { value: "question", label: "Just have a question", icon: "mail", sub: "Quick ask" },
  ],
  role: [
    { value: "buyer", label: "Buyer", icon: "key", sub: "Taking over payments" },
    { value: "seller", label: "Seller", icon: "dollar", sub: "Getting out from under" },
  ],
  hasBuyer: [
    { value: "yes", label: "Yes — buyer's lined up", icon: "handshake", sub: "Real deal to coordinate" },
    { value: "no", label: "Not yet", icon: "search", sub: "Still need a buyer" },
  ],
  terms: [
    { value: "yes", label: "Yes — terms are set", icon: "check", sub: "Both sides agreed" },
    { value: "no", label: "Not yet", icon: "x", sub: "Still in talks" },
  ],
  dealType: [
    { value: "subto", label: "Subject-To", icon: "files", sub: "Take over existing loan" },
    { value: "sellerfinance", label: "Seller Finance", icon: "scale", sub: "Seller carries the note" },
    { value: "hybrid", label: "Hybrid", icon: "zap", sub: "A mix of both" },
  ],
  loanCurrent: [
    { value: "yes", label: "Yes — current", icon: "shield", sub: "Payments up to date" },
    { value: "no", label: "Behind / unsure", icon: "alert-triangle", sub: "We'll sort it out" },
  ],
  heard: [
    "Facebook group", "Referral", "Google", "AI (ChatGPT, Claude, Gemini, etc.)",
    "SellFi", "SubTo community", "Other",
  ],
};

/* ============================================================
   1 · WELCOME
   ============================================================ */
function WelcomeStep() {
  return (
    <div className="welcome stagger">
      <div className="badge-row">
        <span className="pill"><Icon name="shield" /> Coordinated end-to-end</span>
        <span className="pill"><Icon name="calendar" /> ~3 minutes</span>
      </div>
      <h1>Own More.<br /><span className="cy">Bank Less.</span></h1>
      <p className="lead">
        Tell us about your creative-finance vehicle deal. We'll qualify the fit,
        protect both sides, and book a transparency call to coordinate the rest.
      </p>
      <div className="meta-row">
        <span className="meta-item"><Icon name="check" /> No bank. No dealer. No guesswork.</span>
        <span className="meta-item"><Icon name="files" /> Contracts, title &amp; tracking handled.</span>
      </div>
    </div>
  );
}

/* ============================================================
   2 · QUICK QUALIFY
   ============================================================ */
function QErr({ msg }) {
  if (!msg) return null;
  return <span className="ferror"><Icon name="alert-triangle" />{msg}</span>;
}

function QualifyStep({ data, set, errors = {} }) {
  return (
    <div className="qgroup stagger">
      <div className="qblock">
        <div className="qlabel">Are you a SubTo student? <span className="opt">required</span></div>
        <ChoiceGroup name="SubTo student" options={OPT.subTo} value={data.subToStudent}
          onChange={(v) => set("subToStudent", v)} triplet />
        <QErr msg={errors.subToStudent} />
      </div>
      <div className="qblock">
        <div className="qlabel">Do you have a creative-finance deal to coordinate?</div>
        <ChoiceGroup name="Needs help" options={OPT.needsHelp} value={data.needsHelp}
          onChange={(v) => set("needsHelp", v)} columns={3} />
        <QErr msg={errors.needsHelp} />
      </div>
      <div className="qblock">
        <div className="qlabel">Are you the buyer or the seller?</div>
        <ChoiceGroup name="Role" options={OPT.role} value={data.role}
          onChange={(v) => set("role", v)} columns={2} />
        <QErr msg={errors.role} />
      </div>
      {data.role === "seller" && (
        <div className="qblock">
          <div className="qlabel">Do you already have a buyer?</div>
          <ChoiceGroup name="Has buyer" options={OPT.hasBuyer} value={data.hasBuyer}
            onChange={(v) => set("hasBuyer", v)} columns={2} />
          <QErr msg={errors.hasBuyer} />
        </div>
      )}
    </div>
  );
}

/* ============================================================
   3 · YOUR INFO  (captured early — lead is recoverable)
   ============================================================ */
function InfoStep({ data, set, errors }) {
  return (
    <div className="qgroup stagger">
      <div className="fields cols-2">
        <Field label="First name" error={errors.firstName}>
          <TextInput value={data.firstName} onChange={(v) => set("firstName", v)}
            placeholder="Jordan" autoComplete="given-name" error={errors.firstName} />
        </Field>
        <Field label="Last name" error={errors.lastName}>
          <TextInput value={data.lastName} onChange={(v) => set("lastName", v)}
            placeholder="Rivera" autoComplete="family-name" error={errors.lastName} />
        </Field>
        <Field label="Email" span="full" error={errors.email}>
          <TextInput value={data.email} onChange={(v) => set("email", v)} type="email"
            inputMode="email" placeholder="you@email.com" autoComplete="email" error={errors.email} />
        </Field>
        <Field label="Phone" span="full" error={errors.phone}>
          <PhoneField value={data.phone} ccValue={data.phoneCc} error={errors.phone}
            onChange={(v) => set("phone", v)} onCc={(v) => set("phoneCc", v)} />
          <p className="consent">
            By continuing, you agree to be contacted by TOP Wheels about your deal by call,
            text, and email. Message rates may apply. We never sell your info.
          </p>
        </Field>
        <Field label="How did you hear about us?" span="full" error={errors.heardAbout}>
          <SelectInput value={data.heardAbout} onChange={(v) => set("heardAbout", v)}
            options={OPT.heard} placeholder="Select one…" error={errors.heardAbout} />
        </Field>
      </div>
    </div>
  );
}

/* ============================================================
   4 · DEAL DETAILS
   ============================================================ */
function DealStep({ data, set, errors = {} }) {
  return (
    <div className="qgroup stagger">
      <div className="qblock">
        <div className="qlabel">Have both parties agreed to terms?</div>
        <ChoiceGroup name="Terms agreed" options={OPT.terms} value={data.termsAgreed}
          onChange={(v) => set("termsAgreed", v)} columns={2} />
        <QErr msg={errors.termsAgreed} />
      </div>
      <div className="qblock">
        <div className="qlabel">What kind of deal is this?</div>
        <ChoiceGroup name="Deal type" options={OPT.dealType} value={data.dealType}
          onChange={(v) => set("dealType", v)} columns={3} />
        <QErr msg={errors.dealType} />
      </div>
      <div className="qblock">
        <div className="qlabel">Is the seller's loan current?</div>
        <ChoiceGroup name="Loan current" options={OPT.loanCurrent} value={data.loanCurrent}
          onChange={(v) => set("loanCurrent", v)} columns={2} />
        <QErr msg={errors.loanCurrent} />
      </div>
    </div>
  );
}

/* ============================================================
   5 · THE VEHICLE
   ============================================================ */
function VehicleStep({ data, set, errors }) {
  return (
    <div className="qgroup stagger">
      <div className="fields cols-3">
        <Field label="Year" error={errors.year}>
          <TextInput value={data.year} onChange={(v) => set("year", v)} mono
            inputMode="numeric" placeholder="2022" maxLength={4}
            transform={(v) => v.replace(/\D/g, "")} error={errors.year} />
        </Field>
        <Field label="Make" error={errors.make}>
          <TextInput value={data.make} onChange={(v) => set("make", v)}
            placeholder="Ford" error={errors.make} />
        </Field>
        <Field label="Model" error={errors.model}>
          <TextInput value={data.model} onChange={(v) => set("model", v)}
            placeholder="F-150" error={errors.model} />
        </Field>
        <Field label="Trim" optional span="full">
          <TextInput value={data.trim} onChange={(v) => set("trim", v)}
            placeholder="Lariat 4x4" />
        </Field>
        <Field label="VIN" optional span="full" error={errors.vin}>
          <TextInput value={data.vin} onChange={(v) => set("vin", v)} mono
            placeholder="17-character VIN" maxLength={17}
            transform={(v) => v.toUpperCase().replace(/[^A-HJ-NPR-Z0-9]/g, "")} error={errors.vin} />
          <VinMeter vin={data.vin} />
        </Field>
      </div>
    </div>
  );
}

function VinMeter({ vin }) {
  const len = (vin || "").length;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: "8px", marginTop: "2px" }}>
      <div style={{ flex: 1, height: "2px", background: "var(--dark-border)", borderRadius: "999px", overflow: "hidden" }}>
        <div style={{ height: "100%", width: `${(len / 17) * 100}%`,
          background: len === 17 ? "var(--green)" : "var(--cyan)", transition: "width .2s ease" }} />
      </div>
      <span className="mono" style={{ fontSize: "0.7rem", color: len === 17 ? "var(--green)" : "var(--text-muted)" }}>
        {len}/17
      </span>
    </div>
  );
}

/* ============================================================
   6 · LOCATION
   ============================================================ */
function LocationStep({ data, set, errors }) {
  return (
    <div className="qgroup stagger">
      <div className="fields cols-2">
        <Field label="Where's the vehicle now?" span="full" error={errors.vehicleLocation}>
          <TextInput value={data.vehicleLocation} onChange={(v) => set("vehicleLocation", v)}
            placeholder="City, State" error={errors.vehicleLocation} />
        </Field>
        <Field label="Where will you primarily drive it?" span="full" error={errors.drivingLocation}>
          <TextInput value={data.drivingLocation} onChange={(v) => set("drivingLocation", v)}
            placeholder="City, State" error={errors.drivingLocation} />
        </Field>
      </div>
    </div>
  );
}

/* ============================================================
   THE OTHER SIDE  (counterparty contact — both join the call)
   ============================================================ */
function OtherPartyStep({ data, set, errors }) {
  const other = data.role === "seller" ? "buyer" : "seller";
  const Other = other.charAt(0).toUpperCase() + other.slice(1);
  return (
    <div className="qgroup stagger">
      <div className="fields cols-2">
        <Field label={`${Other}'s first name`} error={errors.otherFirstName}>
          <TextInput value={data.otherFirstName} onChange={(v) => set("otherFirstName", v)}
            placeholder="First name" error={errors.otherFirstName} />
        </Field>
        <Field label={`${Other}'s last name`} error={errors.otherLastName}>
          <TextInput value={data.otherLastName} onChange={(v) => set("otherLastName", v)}
            placeholder="Last name" error={errors.otherLastName} />
        </Field>
        <Field label={`${Other}'s email`} span="full" error={errors.otherEmail}>
          <TextInput value={data.otherEmail} onChange={(v) => set("otherEmail", v)} type="email"
            inputMode="email" placeholder="name@email.com" error={errors.otherEmail} />
        </Field>
      </div>
      <p className="qhint">We'll use this to add the {other} to your transparency call.</p>
    </div>
  );
}

/* ============================================================
   7 · BOOK CALL  (success + summary + GHL calendar slot)
   ============================================================ */
function BookStep({ data }) {
  const vehicle = [data.year, data.make, data.model].filter(Boolean).join(" ");
  const other = data.role === "seller" ? "buyer" : "seller";
  const otherName = [data.otherFirstName, data.otherLastName].filter(Boolean).join(" ");
  return (
    <div className="terminal stagger" style={{ maxWidth: "720px" }}>
      <div className="glyph success"><Icon name="check" /></div>
      <h2>You're In{ data.firstName ? `, ${data.firstName}` : "" }.<br /><span className="cy">Let's Lock The Call.</span></h2>
      <p className="lead">
        Your deal's in the queue. Grab a time below for your transparency call — we'll walk
        the structure, the protections, and every next step, with both sides on the line.
      </p>
      <div className="summary">
        {vehicle && <span className="chip"><Icon name="car" /><b>{vehicle}</b></span>}
        {data.role && <span className="chip">You <b>{data.role}</b></span>}
        {data.dealType && <span className="chip">Deal <b>{data.dealType}</b></span>}
        {otherName && <span className="chip"><Icon name="users" /><b>{otherName}</b> · {other}</span>}
        {data.vehicleLocation && <span className="chip"><Icon name="map-pin" /><b>{data.vehicleLocation}</b></span>}
      </div>

      <div className="next-card" style={{ marginTop: "var(--space-6)" }}>
        <span className="nc-label">What happens on the call</span>
        <ul className="nc-list">
          <li><Icon name="scale" /> We walk the deal structure and confirm the terms both sides agreed to.</li>
          <li><Icon name="shield" /> We cover the protections — contracts, insurance, title, and tracking.</li>
          <li><Icon name="arrow-right" /> You leave with clear next steps. Most calls run about 20 minutes.</li>
        </ul>
      </div>

      {/* GHL calendar embed slot — replace with your GoHighLevel iframe */}
      <div className="cal-slot" id="calendar-embed" data-provider="gohighlevel">
        <Icon name="calendar" />
        <span className="cs-title">Transparency Call · Calendar</span>
        <span className="cs-note">
          GoHighLevel calendar mounts here. Drop your GHL embed into <code>#calendar-embed</code>.
        </span>
      </div>
    </div>
  );
}

/* ============================================================
   BRANCH · QUESTION CAPTURE  ("just have a question")
   ============================================================ */
function QuestionStep({ data, set, errors }) {
  return (
    <div className="qgroup stagger">
      <div className="fields cols-2">
        <Field label="Your question" span="full" error={errors.question}>
          <textarea
            className={`control ${errors.question ? "invalid" : ""}`}
            rows={4} style={{ resize: "vertical", minHeight: "110px" }}
            placeholder="What can we clear up for you?"
            value={data.question || ""}
            onChange={(e) => set("question", e.target.value)}
          />
        </Field>
        <Field label="First name" error={errors.firstName}>
          <TextInput value={data.firstName} onChange={(v) => set("firstName", v)} placeholder="Jordan" error={errors.firstName} />
        </Field>
        <Field label="Email" error={errors.email}>
          <TextInput value={data.email} onChange={(v) => set("email", v)} type="email"
            inputMode="email" placeholder="you@email.com" error={errors.email} />
        </Field>
        <Field label="Phone" optional span="full">
          <PhoneField value={data.phone} ccValue={data.phoneCc}
            onChange={(v) => set("phone", v)} onCc={(v) => set("phoneCc", v)} />
        </Field>
      </div>
    </div>
  );
}

/* ============================================================
   TERMINAL screens (branch dead-ends — graceful, never harsh)
   ============================================================ */
function Terminal({ glyph, icon, title, titleCy, lead, children }) {
  return (
    <div className="terminal stagger">
      <div className={`glyph ${glyph}`}><Icon name={icon} /></div>
      <h2>{title} {titleCy && <span className="cy">{titleCy}</span>}</h2>
      <p className="lead">{lead}</p>
      {children}
    </div>
  );
}

function SellerScreen() {
  return (
    <div className="terminal stagger">
      <div className="glyph info"><Icon name="dollar" /></div>
      <h2>Sellers — Here's Your<br /><span className="cy">Faster Lane.</span></h2>
      <p className="lead">
        TOP Wheels coordinates deals once a buyer's in the picture. No buyer yet? List
        your vehicle on SellFi — you'll get matched with vetted buyers ready to take over
        payments, and we'll coordinate the deal from there.
      </p>
      <div className="next-card">
        <span className="nc-label">How it works</span>
        <ul className="nc-list">
          <li><Icon name="files" /> List your vehicle on SellFi in a few minutes.</li>
          <li><Icon name="users" /> Get matched with vetted buyers taking over payments.</li>
          <li><Icon name="shield" /> Once a buyer's locked, we coordinate the full transaction.</li>
        </ul>
      </div>
      <a className="btn btn-primary btn-lg" href="https://sellfi.io" target="_blank" rel="noopener"
        style={{ marginTop: "var(--space-6)", textDecoration: "none" }}>
        List on SellFi <Icon name="arrow-right" />
      </a>
    </div>
  );
}

function NotReadyScreen() {
  return (
    <Terminal glyph="warn" icon="alert-triangle" title="Not Quite" titleCy="Ready Yet."
      lead="Coordination moves fastest once both sides have agreed to terms. Lock the structure with your counterpart, then come back — your spot's waiting.">
      <div className="next-card">
        <span className="nc-label">Before you return</span>
        <ul className="nc-list">
          <li><Icon name="handshake" /> Align on price, payment, and who covers what.</li>
          <li><Icon name="files" /> Confirm the loan details and that payments are current.</li>
          <li><Icon name="check" /> Once terms are set, restart this form — it takes ~3 minutes.</li>
        </ul>
      </div>
    </Terminal>
  );
}

function NotFitScreen() {
  return (
    <Terminal glyph="soft" icon="check" title="No Problem." titleCy="We're Here."
      lead="Just looking for now — all good. When you've got a creative-finance vehicle deal to coordinate, this is where it starts.">
      <div className="next-card">
        <span className="nc-label">While you're exploring</span>
        <ul className="nc-list">
          <li><Icon name="search" /> Browse vehicles with buyer-ready terms on <a href="https://sellfi.io" target="_blank" rel="noopener">SellFi</a>.</li>
          <li><Icon name="users" /> <a href="https://facebook.com/groups/topmethod" target="_blank" rel="noopener">Learn the T.O.P. Method inside the SubTo community.</a></li>
        </ul>
      </div>
    </Terminal>
  );
}

function ThankYouScreen({ data }) {
  return (
    <Terminal glyph="success" icon="check" title="Question Sent." titleCy="We've Got It."
      lead={`Thanks${data.firstName ? `, ${data.firstName}` : ""}. We'll get back to you by email shortly — usually within one business day.`}>
      <div className="next-card">
        <span className="nc-label">What happens next</span>
        <ul className="nc-list">
          <li><Icon name="mail" /> A coordinator reviews your question personally.</li>
          <li><Icon name="phone" /> If it's faster to talk, we'll offer a quick call.</li>
        </ul>
      </div>
    </Terminal>
  );
}

Object.assign(window, {
  OPT, WelcomeStep, QualifyStep, InfoStep, DealStep, VehicleStep, LocationStep, OtherPartyStep, BookStep,
  QuestionStep, SellerScreen, NotReadyScreen, NotFitScreen, ThankYouScreen,
});
