// cal-home.jsx — Home page with 4 hero strategies + supporting sections

const { useState: _uS, useEffect: _uE, useMemo: _uM, useRef: _uR } = React;

// ─────────────────────────────────────────────────────────────
// Hero variants
// ─────────────────────────────────────────────────────────────

function HeroTraditional() {
  const { go } = useRoute();
  return (
    <section className="hero hero-traditional">
      <div className="container">
        <div className="hero-grid">
          <div className="anim-fadeup">
            <div className="eyebrow">Ontario · Quebec</div>
            <h1 className="h-hero mt-4">Financing for<br/>every credit<br/>situation.</h1>
            <p className="lede-lg mt-6" style={{maxWidth: 480}}>
              Apply in 3 minutes. We work with our lender network to find a rate that fits
              your credit profile — then deliver the vehicle to your door.
            </p>
            <div className="mt-8" style={{display:"flex",gap:12,flexWrap:"wrap"}}>
              <button className="btn btn-primary btn-xl" onClick={() => go("/apply")}>
                Start application <Icon name="arrowRight" size={18} />
              </button>
              <button className="btn btn-secondary btn-xl" onClick={() => go("/financing")}>
                How it works
              </button>
            </div>
            <div className="mt-6 trust-strip">
              <div><Icon name="shield" size={16}/> Credit check only after we talk</div>
              <div><Icon name="lock" size={16}/> Bank-level encryption</div>
              <div><Icon name="clock" size={16}/> Reply in under 24 hrs</div>
            </div>
          </div>
          <div className="hero-art anim-fadeup anim-fadeup-d2">
            <HeroImage />
          </div>
        </div>
      </div>
      <style>{`
        .hero { padding: 56px 0 80px; position: relative; overflow: hidden; }
        @media (max-width: 880px) { .hero { padding: 32px 0 56px; } }
        .hero-grid {
          display: grid;
          grid-template-columns: 1.05fr 1fr;
          gap: 56px;
          align-items: center;
        }
        @media (max-width: 980px) { .hero-grid { grid-template-columns: 1fr; gap: 40px; } }
        .hero-art { position: relative; }
      `}</style>
    </section>
  );
}

// Hero floating-card carousel: cycles through TESTIMONIALS, pauses on hover/focus,
// honours prefers-reduced-motion (no auto-advance; dots still clickable).
function HeroProofCarousel() {
  const [idx, setIdx] = _uS(0);
  const [paused, setPaused] = _uS(false);
  const reduced = _uM(() => {
    if (typeof window === "undefined" || !window.matchMedia) return false;
    return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  }, []);

  _uE(() => {
    if (paused || reduced) return;
    const id = setInterval(() => setIdx((i) => (i + 1) % TESTIMONIALS.length), 6000);
    return () => clearInterval(id);
  }, [paused, reduced]);

  return (
    <div
      className="hero-proof anim-fadeup anim-fadeup-d3 hero-proof-carousel"
      role="region"
      aria-label="Customer testimonials"
      aria-roledescription="carousel"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)}
      onBlur={() => setPaused(false)}
    >
      <div className="hero-proof-stage" aria-live="polite">
        {TESTIMONIALS.map((t, i) => (
          <div
            key={t.name}
            className={"hero-proof-slide" + (i === idx ? " is-active" : "")}
            aria-hidden={i === idx ? "false" : "true"}
          >
            <div style={{display:"flex",gap:12,alignItems:"center"}}>
              <div style={{
                width: 44, height: 44, borderRadius: "50%",
                background: TINT_BG[t.tint % TINT_BG.length],
                color: "white", display: "grid", placeItems: "center", fontWeight: 600, fontSize: 14,
              }}>{t.initials}</div>
              <div style={{lineHeight: 1.2}}>
                <div style={{fontWeight: 600, fontSize: 14}}>{t.name.replace(/\.$/, "")}, {t.role.split(",")[0]}</div>
                <div style={{color: "oklch(0.7 0.16 75)", fontSize: 12, letterSpacing: 1}}>
                  {"★".repeat(t.stars)}
                </div>
              </div>
            </div>
            <p style={{margin: "10px 0 0", fontSize: 13.5, lineHeight: 1.5, color: "var(--text-muted)"}}>
              "{t.short}"
            </p>
          </div>
        ))}
      </div>
      <div className="hero-proof-dots" role="tablist" aria-label="Select testimonial">
        {TESTIMONIALS.map((t, i) => (
          <button
            key={t.name}
            type="button"
            className={"hero-proof-dot" + (i === idx ? " is-active" : "")}
            role="tab"
            aria-selected={i === idx}
            aria-label={`Show review ${i + 1} of ${TESTIMONIALS.length}: ${t.name}`}
            onClick={() => setIdx(i)}
          />
        ))}
      </div>
      <style>{`
        .hero-proof-carousel { padding-bottom: 14px; }
        .hero-proof-stage {
          position: relative;
          min-height: 116px;
        }
        .hero-proof-slide {
          position: absolute; inset: 0;
          opacity: 0; pointer-events: none;
          transition: opacity 400ms ease;
        }
        .hero-proof-slide.is-active { opacity: 1; pointer-events: auto; }
        .hero-proof-dots {
          display: flex; gap: 6px; justify-content: center;
          margin-top: 10px;
        }
        .hero-proof-dot {
          width: 6px; height: 6px; border-radius: 50%;
          border: none; padding: 0; cursor: pointer;
          background: oklch(0.85 0.012 65);
          transition: background 200ms ease, transform 200ms ease;
        }
        .hero-proof-dot.is-active {
          background: var(--primary);
          transform: scale(1.35);
        }
        .hero-proof-dot:hover:not(.is-active) { background: oklch(0.7 0.02 50); }
        .hero-proof-dot:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
        @media (prefers-reduced-motion: reduce) {
          .hero-proof-slide { transition: none; }
        }
      `}</style>
    </div>
  );
}

function HeroImage() {
  return (
    <div style={{ position: "relative" }}>
      <image-slot
        id="hero-photo"
        src={(typeof window !== 'undefined' && window.__resources && window.__resources.heroDriver) || "assets/hero-driver.jpg"}
        shape="rounded"
        radius="24"
        placeholder="Hero photo — recent customer with their new vehicle, or calm Canadian driveway. 4:5 portrait."
        style={{ width: "100%", aspectRatio: "4 / 5", height: "auto", display: "block" }}
      ></image-slot>

      {/* Floating proof carousel */}
      <HeroProofCarousel />


      {/* Floating stat card */}
      <div className="hero-stat anim-fadeup anim-fadeup-d2">
        <div className="tiny" style={{textTransform:"uppercase",letterSpacing:".08em",fontWeight:600}}>Lender network</div>
        <div className="tnum" style={{fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 4, lineHeight: 1}}>
          7,000<span style={{color:"var(--primary)"}}>+</span>
        </div>
        <div className="small mt-2" style={{lineHeight:1.3}}>vehicles we can source<br/>through our partners</div>
      </div>

      <style>{`
        .hero-proof, .hero-stat {
          position: absolute;
          background: var(--surface);
          border: 1px solid var(--border);
          border-radius: 16px;
          box-shadow: var(--shadow-lg);
          padding: 16px;
        }
        .hero-proof { bottom: 24px; left: -24px; width: 260px; }
        .hero-stat { top: 28px; right: -16px; width: 200px; }
        @media (max-width: 980px) {
          .hero-proof { left: 12px; bottom: 16px; }
          .hero-stat { right: 12px; top: 16px; }
        }
        @media (max-width: 520px) {
          .hero-proof, .hero-stat { display: none; }
        }
      `}</style>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Mini-application hero
// ─────────────────────────────────────────────────────────────
function HeroMiniApp() {
  const { go } = useRoute();
  const [data, setData] = _uS({ first: "", last: "", postal: "" });
  const submit = (e) => {
    e.preventDefault();
    try { localStorage.setItem("cal_apply_seed", JSON.stringify(data)); } catch (_) {}
    go("/apply");
  };
  return (
    <section className="hero hero-mini">
      <div className="container">
        <div className="hero-grid">
          <div className="anim-fadeup">
            <div className="eyebrow">Ontario · Quebec</div>
            <h1 className="h-hero mt-4">Financing for every credit situation.</h1>
            <p className="lede mt-6" style={{maxWidth: 520}}>
              Start your application here. It takes about 3 minutes — no credit check until we've spoken.
            </p>
            <div className="mt-6 trust-strip" style={{paddingTop:0}}>
              <div><Icon name="check-circle" size={16}/> No credit check just to apply</div>
              <div><Icon name="check-circle" size={16}/> Save your progress anytime</div>
            </div>
          </div>
          <div className="anim-fadeup anim-fadeup-d2">
            <form onSubmit={submit} className="card card-pad" style={{boxShadow: "var(--shadow-lg)"}}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
                <div className="h3">Start your application</div>
                <span className="tag"><span style={{
                  width:5,height:5,borderRadius:"50%",background:"var(--success)",display:"inline-block",
                }}/>3 minutes</span>
              </div>
              <p className="small" style={{margin: "0 0 18px"}}>
                Step 1 of 5 · Basic contact info
              </p>
              <div className="stack gap-4">
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}}>
                  <div className="field">
                    <label className="field-label">First name <span className="req">required</span></label>
                    <input className="input" value={data.first} onChange={(e)=>setData({...data, first:e.target.value})} placeholder="Maya" />
                  </div>
                  <div className="field">
                    <label className="field-label">Last name <span className="req">required</span></label>
                    <input className="input" value={data.last} onChange={(e)=>setData({...data, last:e.target.value})} placeholder="Tremblay" />
                  </div>
                </div>
                <div className="field">
                  <label className="field-label">Postal code <span className="req">required</span></label>
                  <input className="input" value={data.postal} onChange={(e)=>setData({...data, postal:e.target.value.toUpperCase()})} placeholder="K1Z 7S8" maxLength={7} />
                  <div className="field-hint">Ontario and Quebec residents only at this time.</div>
                </div>
                <button type="submit" className="btn btn-primary btn-lg btn-block mt-2">
                  Continue <Icon name="arrowRight" size={16}/>
                </button>
                <div className="tiny text-center" style={{marginTop:4}}>
                  <Icon name="lock" size={11} stroke={2} style={{verticalAlign:"-1px",marginRight:4}}/>
                  Encrypted. We never sell your information.
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
      <style>{`
        .hero { padding: 56px 0 80px; position: relative; overflow: hidden; }
        .hero-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 56px; align-items: center; }
        @media (max-width: 980px) { .hero-grid { grid-template-columns: 1fr; gap: 32px; } }
        @media (max-width: 880px) { .hero { padding: 32px 0 48px; } }
      `}</style>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Quiz hero — "Can I qualify?"
// ─────────────────────────────────────────────────────────────
function HeroQuiz() {
  const { go } = useRoute();
  const [step, setStep] = _uS(0);
  const [credit, setCredit] = _uS(null);
  const [income, setIncome] = _uS(null);
  const [purpose, setPurpose] = _uS(null);

  const total = 3;
  const advance = () => setStep((s) => Math.min(s + 1, total));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  const startApply = () => {
    try {
      localStorage.setItem("cal_apply_seed", JSON.stringify({ credit, income, purpose }));
    } catch(_) {}
    go("/apply");
  };

  return (
    <section className="hero hero-quiz">
      <div className="container">
        <div className="hero-grid">
          <div className="anim-fadeup" style={{maxWidth: 540}}>
            <div className="eyebrow">Ontario · Quebec</div>
            <h1 className="h-hero mt-4">Will we be able to&nbsp;help?</h1>
            <p className="lede-lg mt-6">
              Three quick questions. No name, no email, no credit check.
              Just a quick read on whether we can find you financing.
            </p>
            <ul style={{listStyle:"none",padding:0,margin: "28px 0 0"}}>
              <CheckBullet>We work with every credit profile, including past bankruptcies</CheckBullet>
              <CheckBullet>You're under no obligation — quitting the quiz at any time costs nothing</CheckBullet>
              <CheckBullet>If we can help, you'll be invited to start a real application</CheckBullet>
            </ul>
          </div>
          <div className="anim-fadeup anim-fadeup-d2">
            <div className="card card-pad-lg" style={{boxShadow: "var(--shadow-lg)"}}>
              {step < total && (
                <>
                  <div style={{display:"flex",alignItems:"center",gap:12,marginBottom:24}}>
                    <div className="stepper">
                      {[0,1,2].map(i => (
                        <div key={i} className={`step ${i <= step ? "active":""}`}>
                          <div className="step-bar"></div>
                        </div>
                      ))}
                    </div>
                    <div className="tiny tnum" style={{minWidth:36, textAlign:"right"}}>{step+1}/{total}</div>
                  </div>
                </>
              )}

              {step === 0 && (
                <div className="anim-fadeup">
                  <div className="h3">Where's your credit at, roughly?</div>
                  <p className="small mt-2">Best guess is fine. We don't run a credit check until we've spoken with you.</p>
                  <div className="stack gap-2 mt-6">
                    {[
                      {v:"excellent", t:"Excellent", d:"720+"},
                      {v:"good", t:"Good", d:"680–719"},
                      {v:"fair", t:"Fair", d:"620–679"},
                      {v:"building", t:"Building", d:"580–619"},
                      {v:"wip", t:"Work-in-progress", d:"579 & under"},
                      {v:"idk", t:"Not sure", d:"That's OK"},
                    ].map(o => (
                      <button key={o.v} type="button"
                        className={`choice ${credit === o.v ? "selected":""}`}
                        onClick={() => { setCredit(o.v); setTimeout(advance, 180); }}
                      >
                        <span className="choice-radio" />
                        <span className="choice-body">
                          <span className="choice-title">{o.t}</span>
                        </span>
                        <span className="choice-suffix tnum">{o.d}</span>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {step === 1 && (
                <div className="anim-fadeup">
                  <div className="h3">Monthly income after taxes?</div>
                  <p className="small mt-2">Roughly. We confirm later.</p>
                  <div className="stack gap-2 mt-6">
                    {[
                      "Under $2,000", "$2,000 – $3,500", "$3,500 – $5,000",
                      "$5,000 – $7,500", "Over $7,500"
                    ].map(o => (
                      <button key={o} type="button"
                        className={`choice ${income === o ? "selected":""}`}
                        onClick={() => { setIncome(o); setTimeout(advance, 180); }}
                      >
                        <span className="choice-radio" />
                        <span className="choice-body">
                          <span className="choice-title tnum">{o}</span>
                        </span>
                      </button>
                    ))}
                  </div>
                  <button className="btn btn-ghost btn-sm mt-6" onClick={back}>
                    <Icon name="arrowLeft" size={14}/> Back
                  </button>
                </div>
              )}

              {step === 2 && (
                <div className="anim-fadeup">
                  <div className="h3">When are you planning to buy?</div>
                  <p className="small mt-2">Helps us prioritize your file.</p>
                  <div className="stack gap-2 mt-6">
                    {["This week", "This month", "Next 1–3 months", "Just exploring"].map(o => (
                      <button key={o} type="button"
                        className={`choice ${purpose === o ? "selected":""}`}
                        onClick={() => { setPurpose(o); setTimeout(advance, 180); }}
                      >
                        <span className="choice-radio" />
                        <span className="choice-body">
                          <span className="choice-title">{o}</span>
                        </span>
                      </button>
                    ))}
                  </div>
                  <button className="btn btn-ghost btn-sm mt-6" onClick={back}>
                    <Icon name="arrowLeft" size={14}/> Back
                  </button>
                </div>
              )}

              {step === total && (
                <div className="anim-fadeup text-center" style={{padding: "8px 0"}}>
                  <div style={{
                    width: 56, height: 56, borderRadius: "50%",
                    background: "var(--success-soft)", color: "var(--success)",
                    display: "grid", placeItems: "center", margin: "0 auto 16px",
                  }}>
                    <Icon name="check" size={28} stroke={2.5} />
                  </div>
                  <div className="h2" style={{maxWidth: 360, margin: "0 auto"}}>
                    Yes — we can probably help.
                  </div>
                  <p className="lede mt-4" style={{maxWidth: 380, margin: "16px auto 0"}}>
                    Your profile matches lenders in our network. We can't guarantee
                    approval until we review your file, but you're a strong start.
                  </p>
                  <button className="btn btn-primary btn-xl btn-block mt-6" onClick={startApply}>
                    Start full application <Icon name="arrowRight" size={16}/>
                  </button>
                  <p className="tiny mt-4">No credit check until we've spoken with you.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
      <style>{`
        .hero { padding: 56px 0 80px; position: relative; overflow: hidden; }
        .hero-grid { display: grid; grid-template-columns: 1fr 1.05fr; gap: 56px; align-items: center; }
        @media (max-width: 980px) { .hero-grid { grid-template-columns: 1fr; gap: 32px; } }
        @media (max-width: 880px) { .hero { padding: 32px 0 48px; } }
      `}</style>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Estimator hero — payment slider
// ─────────────────────────────────────────────────────────────
function HeroEstimator() {
  const { go } = useRoute();
  const [price, setPrice] = _uS(28000);
  const [down, setDown] = _uS(2000);
  const [term, setTerm] = _uS(72);
  const [credit, setCredit] = _uS("good");

  const apr = useMemo(() => {
    const map = { excellent: 6.99, good: 9.49, fair: 12.99, building: 15.99, wip: 18.99 };
    return map[credit] ?? 9.49;
  }, [credit]);

  const monthly = useMemo(() => {
    const principal = Math.max(price - down, 1000);
    const r = (apr / 100) / 12;
    const n = term;
    if (r === 0) return Math.round(principal / n);
    return Math.round((principal * r) / (1 - Math.pow(1 + r, -n)));
  }, [price, down, term, apr]);

  const fmt = (n) => "$" + n.toLocaleString("en-CA");

  return (
    <section className="hero hero-est">
      <div className="container">
        <div className="hero-grid">
          <div className="anim-fadeup" style={{maxWidth: 520}}>
            <div className="eyebrow">Ontario · Quebec</div>
            <h1 className="h-hero mt-4">See your<br/>monthly payment<br/>in real time.</h1>
            <p className="lede-lg mt-6">
              Adjust price and term to see what a payment could look like
              for your credit profile. No personal info required.
            </p>
            <div className="mt-8" style={{display:"flex",gap:12,flexWrap:"wrap"}}>
              <button className="btn btn-primary btn-xl" onClick={() => go("/apply")}>
                Start application <Icon name="arrowRight" size={16}/>
              </button>
              <button className="btn btn-secondary btn-xl" onClick={() => go("/financing")}>
                How we set rates
              </button>
            </div>
          </div>
          <div className="anim-fadeup anim-fadeup-d2">
            <div className="card card-pad-lg" style={{boxShadow:"var(--shadow-lg)"}}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom: 20}}>
                <div>
                  <div className="tiny" style={{textTransform:"uppercase",letterSpacing:".08em",fontWeight:600,color:"var(--text-soft)"}}>
                    Estimated monthly
                  </div>
                  <div className="tnum" style={{fontSize: 52, fontWeight: 700, letterSpacing: "-0.03em", lineHeight: 1, marginTop: 4}}>
                    {fmt(monthly)}<span style={{fontSize: 22, color: "var(--text-muted)", fontWeight: 500}}>/mo</span>
                  </div>
                </div>
                <div style={{textAlign:"right"}}>
                  <div className="tiny" style={{textTransform:"uppercase",letterSpacing:".08em",fontWeight:600,color:"var(--text-soft)"}}>
                    Rep. APR
                  </div>
                  <div className="tnum" style={{fontSize: 24, fontWeight: 600, letterSpacing: "-0.02em", marginTop: 4}}>
                    {apr.toFixed(2)}<span style={{fontSize:16,color:"var(--text-muted)"}}>%</span>
                  </div>
                </div>
              </div>

              <div className="stack gap-6">
                <Slider label="Vehicle price" value={price} onChange={setPrice} min={5000} max={75000} step={500} fmt={fmt} />
                <Slider label="Down payment" value={down} onChange={setDown} min={0} max={20000} step={250} fmt={fmt} />
                <div>
                  <label className="field-label" style={{justifyContent:"space-between",display:"flex"}}>
                    <span>Loan term</span>
                    <span className="tnum soft">{term} months</span>
                  </label>
                  <div style={{display:"flex",gap:6,marginTop:8}}>
                    {[36,48,60,72,84].map(t => (
                      <button key={t} type="button" onClick={() => setTerm(t)}
                        className="btn-sm tnum"
                        style={{
                          flex:1, padding: "8px 0", borderRadius: 8,
                          border: "1px solid " + (term===t? "var(--primary)":"var(--border)"),
                          background: term===t? "var(--primary-tint)" : "var(--surface)",
                          color: term===t? "var(--primary)":"var(--text-muted)",
                          fontWeight: term===t? 600: 500, fontSize: 13,
                        }}
                      >{t}</button>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="field-label">Estimated credit</label>
                  <CalSelect
                    value={credit}
                    onChange={setCredit}
                    options={[
                      { value: "excellent", label: "Excellent", hint: "720+" },
                      { value: "good", label: "Good", hint: "680–719" },
                      { value: "fair", label: "Fair", hint: "620–679" },
                      { value: "building", label: "Building", hint: "580–619" },
                      { value: "wip", label: "Work-in-progress", hint: "579 & under" },
                    ]}
                  />
                </div>
              </div>

              <div className="mt-6 small" style={{
                padding: 12, borderRadius: 10,
                background: "var(--surface-muted)", color: "var(--text-muted)",
                fontSize: 12, lineHeight: 1.5, display: "flex", gap: 8,
              }}>
                <Icon name="info" size={14} style={{flex:"0 0 14px",marginTop:1,color:"var(--text-soft)"}} />
                <span>
                  For illustration only. Representative APR <span className="tnum">{apr.toFixed(2)}%</span> over <span className="tnum">{term}</span> months.
                  Not an offer of credit. All financing subject to credit approval.
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        .hero { padding: 56px 0 80px; position: relative; overflow: hidden; }
        .hero-grid { display: grid; grid-template-columns: 1fr 1.1fr; gap: 56px; align-items: center; }
        @media (max-width: 980px) { .hero-grid { grid-template-columns: 1fr; gap: 32px; } }
        @media (max-width: 880px) { .hero { padding: 32px 0 48px; } }
      `}</style>
    </section>
  );
}

function Slider({ label, value, onChange, min, max, step, fmt }) {
  const pct = Math.max(0, Math.min(100, ((value - min) / (max - min)) * 100));
  return (
    <div>
      <label className="field-label" style={{justifyContent:"space-between",display:"flex"}}>
        <span>{label}</span>
        <span className="tnum" style={{color:"var(--primary)",fontWeight:600}}>{fmt(value)}</span>
      </label>
      <input
        type="range" min={min} max={max} step={step} value={value}
        onChange={(e)=>onChange(parseInt(e.target.value,10))}
        className="cal-range"
        style={{ width:"100%", marginTop: 10, "--p": pct + "%" }}
      />
      <div className="tiny tnum" style={{display:"flex",justifyContent:"space-between",marginTop:4,color:"var(--text-soft)"}}>
        <span>{fmt(min)}</span><span>{fmt(max)}</span>
      </div>
      <style>{`
        .cal-range { -webkit-appearance: none; appearance: none; background: transparent; height: 22px; }
        .cal-range::-webkit-slider-runnable-track { height: 6px; border-radius: 999px; background: linear-gradient(to right, var(--primary) 0%, var(--primary) var(--p, 50%), var(--border) var(--p, 50%), var(--border) 100%); }
        .cal-range::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 20px; height: 20px; border-radius: 50%; background: white; border: 1.5px solid var(--primary); margin-top: -7px; box-shadow: var(--shadow-sm); cursor: pointer; transition: transform .12s ease; }
        .cal-range::-webkit-slider-thumb:hover { transform: scale(1.08); }
        .cal-range::-moz-range-track { height: 6px; border-radius: 999px; background: linear-gradient(to right, var(--primary) 0%, var(--primary) var(--p, 50%), var(--border) var(--p, 50%), var(--border) 100%); }
        .cal-range::-moz-range-thumb { width: 20px; height: 20px; border-radius: 50%; background: white; border: 1.5px solid var(--primary); }
      `}</style>
    </div>
  );
}

// React useMemo helper alias
const { useMemo } = React;

// ─────────────────────────────────────────────────────────────
// Sections shared by all home variants
// ─────────────────────────────────────────────────────────────

function TrustStrip() {
  return (
    <section style={{
      background: "var(--bg-2)",
      borderTop: "1px solid var(--border)",
      borderBottom: "1px solid var(--border)",
    }}>
      <div className="container">
        <div className="trust-strip-grid">
          <div>
            <div className="gchip" style={{boxShadow:"none",background:"transparent",border:"none",padding:0}}>
              <Icon name="google" size={16} stroke={0} />
              <StarRating value={4.1} size={14} />
              <b className="tnum">4.1</b>
              <span className="soft">on Google · 214 reviews</span>
            </div>
          </div>
          <div className="trust-item"><Icon name="shield" size={16} /><div><b>Ottawa auto dealer</b><span className="soft"> · Ontario &amp; Quebec</span></div></div>
          <div className="trust-item"><Icon name="users" size={16} /><div><b>Real concierge team</b><span className="soft"> · Ottawa-based</span></div></div>
          <div className="trust-item"><Icon name="lock" size={16} /><div><b>No surprise checks</b><span className="soft"> · We talk first</span></div></div>
        </div>
      </div>
      <style>{`
        .trust-strip-grid {
          display: grid;
          grid-template-columns: auto 1fr 1fr 1fr;
          align-items: center;
          gap: 32px;
          padding: 18px 0;
        }
        @media (max-width: 880px) { .trust-strip-grid { grid-template-columns: 1fr 1fr; gap: 14px; padding: 16px 0; } }
        @media (max-width: 520px) { .trust-strip-grid { grid-template-columns: 1fr; } }
        .trust-item { display: flex; align-items: center; gap: 10px; color: var(--text-muted); font-size: 14px; }
        .trust-item b { color: var(--text); font-weight: 600; }
      `}</style>
    </section>
  );
}

function HowItWorks() {
  const steps = [
    { n: "01", t: "Apply in 3 minutes", d: "Tell us about you, your income, and the vehicle you want. We never sell your data.", icon: "edit" },
    { n: "02", t: "We shop our lender network", d: "Your concierge takes your profile to lenders likely to say yes — and brings back the best rate available to you.", icon: "search" },
    { n: "03", t: "Vehicle delivered to your door", d: "Approve the paperwork, choose your vehicle from our partner inventory, and we deliver it to your door.", icon: "truck" },
  ];
  return (
    <section style={{padding: "96px 0 60px"}}>
      <div className="container">
        <div style={{maxWidth: 620, margin: "0 auto", textAlign: "center"}}>
          <div className="eyebrow" style={{justifyContent:"center"}}>How it works</div>
          <h2 className="h1 mt-4">Three steps. Zero pressure.</h2>
          <p className="lede mt-4">
            We sell the vehicle and arrange the financing in one place. No
            second stop. No bouncing between a dealer and a lender.
          </p>
        </div>
        <div className="how-grid mt-12">
          {steps.map((s) => (
            <div key={s.n} className="how-card">
              <div className="how-num tnum">{s.n}</div>
              <div className="how-icon"><Icon name={s.icon} size={22} /></div>
              <div className="h3 mt-4">{s.t}</div>
              <p className="mt-2 muted" style={{fontSize: 15, lineHeight: 1.55, margin: "8px 0 0"}}>{s.d}</p>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        .how-grid {
          display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px;
        }
        @media (max-width: 880px) { .how-grid { grid-template-columns: 1fr; } }
        .how-card {
          padding: 28px;
          border: 1px solid var(--border);
          border-radius: var(--r-xl);
          background: var(--surface);
          position: relative;
        }
        .how-num {
          position: absolute; top: 24px; right: 28px;
          font-size: 13px; font-weight: 600; color: var(--text-soft);
          letter-spacing: 0.06em;
        }
        .how-icon {
          width: 44px; height: 44px; border-radius: 12px;
          background: var(--primary-tint); color: var(--primary);
          display: grid; place-items: center;
        }
      `}</style>
    </section>
  );
}

function ValueProps() {
  const items = [
    {
      icon: "users", t: "Real people, not a portal",
      d: "Ecaterina leads sales; Barb and Caroline handle delivery. You'll talk to the same humans from application to keys.",
    },
    {
      icon: "shield", t: "Honest about credit",
      d: "We don't promise approval, ever. We do tell you what's possible for your profile and exactly how we get paid.",
    },
    {
      icon: "truck", t: "Door-to-door delivery",
      d: "No dealership pressure. We deliver the vehicle to your address anywhere in Ontario or Quebec.",
    },
    {
      icon: "trending", t: "7,000+ vehicle network",
      d: "We source from a partner inventory across the country, so we can match the vehicle to the financing.",
    },
  ];
  return (
    <section style={{padding: "60px 0 100px"}}>
      <div className="container">
        <div style={{display:"grid",gridTemplateColumns:"1fr 1.2fr",gap:64,alignItems:"flex-start"}} className="vp-grid">
          <div style={{position:"sticky", top: "calc(var(--nav-h) + 24px)"}}>
            <div className="eyebrow">Why CAL</div>
            <h2 className="h1 mt-4">Built for the&nbsp;people banks make&nbsp;feel small.</h2>
            <p className="lede mt-6" style={{maxWidth: 420}}>
              We started CAL because the people most likely to be turned down by a bank
              are also the most likely to be condescended to about it.
              Our job is to make this part of buying a car feel uncomplicated.
            </p>
            <div className="mt-8">
              <Link to="/about" className="btn btn-secondary">Meet the team <Icon name="arrowRight" size={14}/></Link>
            </div>
          </div>
          <div className="vp-cards">
            {items.map((it, i) => (
              <div key={it.t} className="vp-card">
                <div className="vp-icon"><Icon name={it.icon} size={20} /></div>
                <div>
                  <div className="h3" style={{fontSize: 18}}>{it.t}</div>
                  <p style={{margin: "6px 0 0", color:"var(--text-muted)", fontSize: 15, lineHeight: 1.55}}>{it.d}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 980px) { .vp-grid { grid-template-columns: 1fr !important; gap: 40px !important; } }
        .vp-cards { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        @media (max-width: 640px) { .vp-cards { grid-template-columns: 1fr; } }
        .vp-card {
          padding: 24px;
          background: var(--surface);
          border: 1px solid var(--border);
          border-radius: var(--r-lg);
          display: flex; gap: 16px; align-items: flex-start;
        }
        .vp-icon {
          width: 38px; height: 38px; border-radius: 10px; flex: 0 0 38px;
          background: var(--primary-tint); color: var(--primary);
          display: grid; place-items: center;
        }
      `}</style>
    </section>
  );
}

function Testimonials({ placement }) {
  if (placement === "strip") return null;
  return (
    <section style={{padding: "60px 0", background: "var(--bg-2)", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)"}}>
      <div className="container">
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-end",flexWrap:"wrap",gap:24,marginBottom: 40}}>
          <div style={{maxWidth: 520}}>
            <div className="eyebrow">Reviews</div>
            <h2 className="h1 mt-4">Real reviews from real customers.</h2>
          </div>
          <a className="gchip" href="#" aria-label="See all Google reviews">
            <Icon name="google" size={14} stroke={0} />
            <StarRating value={4.1} />
            <b className="tnum">4.1</b>
            <span className="soft">· 214 Google reviews</span>
            <Icon name="external" size={12} />
          </a>
        </div>
        <div className="testi-grid">
          {TESTIMONIALS.slice(0, 3).map((t) => <ReviewCard key={t.name} t={t} />)}
        </div>
      </div>
      <style>{`
        .testi-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
        @media (max-width: 880px) { .testi-grid { grid-template-columns: 1fr; } }
      `}</style>
    </section>
  );
}

function TeamPreview() {
  const people = [
    { name: "Ecaterina", role: "Sales lead", since: "Since 2019", init: "EC" },
    { name: "Tyler", role: "Sales", since: "", init: "TY" },
    { name: "Barb", role: "Delivery driver", since: "", init: "BB" },
  ];
  return (
    <section style={{padding: "96px 0"}}>
      <div className="container">
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-end",flexWrap:"wrap",gap:24,marginBottom: 40}}>
          <div style={{maxWidth: 520}}>
            <div className="eyebrow">Concierge team</div>
            <h2 className="h1 mt-4">Real names. Real desks. Real Ottawa office.</h2>
          </div>
          <Link to="/about" className="btn btn-secondary">More about us <Icon name="arrowRight" size={14}/></Link>
        </div>
        <div className="team-grid">
          {people.map((p, i) => (
            <div key={p.name} className="card card-pad" style={{display:"flex",gap:18,alignItems:"center"}}>
              <div style={{
                width: 64, height: 64, borderRadius: "50%",
                background: TINT_BG[i % 3],
                color: "white", fontWeight: 600, fontSize: 22,
                display: "grid", placeItems: "center", flex: "0 0 64px",
              }}>{p.init}</div>
              <div>
                <div className="h3" style={{fontSize:18}}>{p.name}</div>
                <div className="small">{p.role}</div>
                {p.since && <div className="tiny mt-2"><span className="pill pill-neutral" style={{fontSize:11}}>{p.since}</span></div>}
              </div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        .team-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
        @media (max-width: 880px) { .team-grid { grid-template-columns: 1fr; } }
      `}</style>
    </section>
  );
}

function FaqPreview() {
  const items = [
    { q: "Will applying hurt my credit score?", a: "Applying does nothing to your credit on its own. We only run a credit check after we've spoken with you and you've approved proceeding — and we'll always tell you before we do." },
    { q: "Can I qualify if I've had a bankruptcy?", a: "Often, yes. Lenders in our network look at your full picture — current income, time since discharge, stability of employment — not just a credit number." },
    { q: "Do you operate outside Ontario and Quebec?", a: "Not yet. We're licensed for Ontario and Quebec residents only. Other provinces are on our roadmap." },
  ];
  const [open, setOpen] = _uS(0);
  return (
    <section style={{padding: "60px 0 100px"}}>
      <div className="container" style={{maxWidth: 820}}>
        <div className="eyebrow">Common questions</div>
        <h2 className="h1 mt-4 mb-8">Straight answers, in plain language.</h2>
        <div className="stack">
          {items.map((it, i) => (
            <button key={it.q}
              className="faq-item"
              onClick={() => setOpen(open === i ? -1 : i)}
              aria-expanded={open === i}
            >
              <div className="faq-q">
                <span style={{fontWeight:600,fontSize:17,letterSpacing:"-0.01em"}}>{it.q}</span>
                <Icon name="chevronDown" size={18}
                  style={{transition:"transform .2s ease", transform: open===i ? "rotate(180deg)":"none", color:"var(--text-muted)"}}
                />
              </div>
              {open === i && (
                <p className="faq-a anim-fadeup" style={{margin: "10px 0 0", color:"var(--text-muted)", fontSize: 15.5, lineHeight: 1.6, textAlign:"left"}}>
                  {it.a}
                </p>
              )}
            </button>
          ))}
        </div>
        <div className="text-center mt-8">
          <Link to="/financing" className="btn btn-ghost">See full FAQ <Icon name="arrowRight" size={14}/></Link>
        </div>
      </div>
      <style>{`
        .faq-item {
          appearance: none; text-align: left; width: 100%; cursor: pointer;
          padding: 22px 4px; border: 0; background: transparent;
          border-bottom: 1px solid var(--border); color: inherit;
          display: flex; flex-direction: column;
        }
        .faq-item:hover { background: var(--surface-muted); }
        .faq-q { display: flex; justify-content: space-between; align-items: center; gap: 16px; }
      `}</style>
    </section>
  );
}

function FinalCTA() {
  const { go } = useRoute();
  return (
    <section style={{padding: "20px 0 100px"}}>
      <div className="container">
        <div style={{
          background: "linear-gradient(135deg, oklch(0.32 0.08 28), oklch(0.22 0.05 30))",
          color: "white",
          borderRadius: 24,
          padding: "64px 56px",
          position: "relative",
          overflow: "hidden",
        }}>
          <div className="final-bg" />
          <div style={{position:"relative",display:"grid",gridTemplateColumns:"1.4fr 1fr",gap:48,alignItems:"center"}} className="final-grid">
            <div>
              <h2 className="h-display" style={{color:"white",fontSize:"clamp(34px, 4.4vw, 56px)",lineHeight:1.05}}>
                Three minutes between you and<br/>your next vehicle.
              </h2>
              <p style={{color:"oklch(0.88 0.04 60)", fontSize: 18, lineHeight: 1.5, marginTop: 20, maxWidth: 460}}>
                Credit check only after we talk. No obligation. A human reviews every file.
              </p>
            </div>
            <div style={{display:"flex",flexDirection:"column",gap:12}}>
              <button className="btn btn-xl" style={{background:"white",color:"var(--primary)"}} onClick={() => go("/apply")}>
                Start application <Icon name="arrowRight" size={18}/>
              </button>
              <button className="btn btn-xl" style={{background:"transparent",color:"white",border:"1px solid rgba(255,255,255,.3)"}} onClick={() => go("/financing")}>
                How it works
              </button>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 720px) {
          .final-grid { grid-template-columns: 1fr !important; }
        }
        .final-bg {
          position: absolute; inset: 0;
          background-image:
            radial-gradient(circle at 90% 20%, oklch(0.55 0.2 35 / 0.4), transparent 50%),
            radial-gradient(circle at 10% 90%, oklch(0.45 0.15 25 / 0.35), transparent 50%);
        }
      `}</style>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Home root
// ─────────────────────────────────────────────────────────────
function Home({ heroVariant, trustPlacement, showMoment }) {
  let Hero;
  switch (heroVariant) {
    case "mini-app": Hero = HeroMiniApp; break;
    case "quiz": Hero = HeroQuiz; break;
    case "estimator": Hero = HeroEstimator; break;
    default: Hero = HeroTraditional;
  }
  return (
    <>
      <Hero />
      <TrustStrip />
      <HowItWorks />
      {showMoment && <MomentBanner />}
      <ValueProps />
      {(trustPlacement === "section" || trustPlacement === "inline") && <Testimonials placement={trustPlacement} />}
      <TeamPreview />
      <FaqPreview />
      <FinalCTA />
    </>
  );
}

function MomentBanner() {
  return (
    <section style={{padding: "20px 0 80px"}}>
      <div className="container">
        <div className="moment-grid">
          <div className="moment-text">
            <div className="eyebrow">A real moment</div>
            <h2 className="h2 mt-4">No dealership lot.<br/>Just keys, at your door.</h2>
            <p className="lede mt-4" style={{maxWidth: 380}}>
              Mark or Nick drops the vehicle off, walks you through the paperwork,
              and leaves you with the keys. That's the entire handoff.
            </p>
          </div>
          <image-slot
            id="moment-banner"
            src={(typeof window !== 'undefined' && window.__resources && window.__resources.momentKeys) || "assets/moment-keys.jpg"}
            shape="rounded"
            radius="20"
            placeholder="Hands exchanging a single car key over a kitchen counter. Soft daylight, slight grain, no faces. Documentary style. 16:9."
            style={{ width: "100%", aspectRatio: "16 / 10", height: "auto", display: "block" }}
          ></image-slot>
        </div>
      </div>
      <style>{`
        .moment-grid { display: grid; grid-template-columns: 1fr 1.6fr; gap: 48px; align-items: center; }
        @media (max-width: 880px) { .moment-grid { grid-template-columns: 1fr; gap: 24px; } }
      `}</style>
    </section>
  );
}

Object.assign(window, {
  Home, HeroTraditional, HeroMiniApp, HeroQuiz, HeroEstimator,
  TrustStrip, HowItWorks, ValueProps, Testimonials, TeamPreview, FaqPreview, FinalCTA,
  MomentBanner, Slider,
});
