// Regional price comparison table.
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

const PC_ROWS = [
  { model: "BYD Seal",     type: "EV · SEDAN",         trim: "Design FWD",       uae: 40820, ksa: 31970, leb: 52000, icon: 31500, save: 20500, pct: 39 },
  { model: "BYD Seal",     type: "EV · SEDAN",         trim: "Performance AWD",  uae: 55790, ksa: 44000, leb: 68000, icon: 44200, save: 23800, pct: 35 },
  { model: "BYD Atto 3",   type: "EV · COMPACT SUV",   trim: "Standard",         uae: 29930, ksa: 32000, leb: 42000, icon: 23800, save: 18200, pct: 43 },
  { model: "BYD Atto 3",   type: "EV · COMPACT SUV",   trim: "Extended Range",   uae: 35370, ksa: 37300, leb: 48000, icon: 28400, save: 19600, pct: 41 },
  { model: "Zeekr 001",    type: "EV · SHOOTING BRAKE", trim: null,              uae: 58000, ksa: 54000, leb: 72000, icon: 47500, save: 24500, pct: 34 },
  { model: "Hongqi H5",    type: "SEDAN",              trim: null,               uae: 32000, ksa: 30000, leb: 38000, icon: 26800, save: 11200, pct: 29 },
  { model: "Geely Coolray", type: "SUV",               trim: null,               uae: 24500, ksa: 22000, leb: 29000, icon: 20200, save:  8800, pct: 30 },
];

function usePCCount(target, run, duration = 900, delay = 0) {
  const [v, setV] = useStateP(0);
  useEffectP(() => {
    if (!run) { setV(0); return; }
    let raf, t0;
    const id = setTimeout(() => {
      const tick = (t) => {
        if (!t0) t0 = t;
        const p = Math.min(1, (t - t0) / duration);
        const eased = 1 - Math.pow(1 - p, 3);
        setV(Math.round(target * eased));
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    }, delay);
    return () => { clearTimeout(id); cancelAnimationFrame(raf); };
  }, [run, target, duration, delay]);
  return v;
}

function fmtP(n) { return "$" + n.toLocaleString("en-US"); }

function PCRow({ row, idx, run }) {
  const delay = 200 + idx * 100;
  const uae  = usePCCount(row.uae,  run, 850, delay);
  const ksa  = usePCCount(row.ksa,  run, 850, delay + 60);
  const leb  = usePCCount(row.leb,  run, 850, delay + 120);
  const icon = usePCCount(row.icon, run, 850, delay + 180);
  const save = usePCCount(row.save, run, 1000, delay + 280);
  const [open, setOpen] = useStateP(false);

  return (
    <>
      {/* Desktop row */}
      <div className="pc-row pc-desk" style={{ opacity: run ? 1 : 0, transform: run ? "none" : "translateY(8px)", transitionDelay: delay + "ms" }}>
        <div className="pc-c pc-model">
          <div className="serif" style={{ fontSize: 22, color: "var(--bone)", letterSpacing: "-.01em", lineHeight: 1.1 }}>{row.model}</div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: ".15em", color: "var(--mute-2)", marginTop: 6 }}>{row.type}</div>
          {row.trim && <div style={{ fontSize: 12, color: "var(--mute)", marginTop: 4 }}>{row.trim}</div>}
        </div>
        <div className="pc-c">
          <div className="num pc-price">{fmtP(uae)}</div>
          <div className="pc-sub">Dubai dealer 🇦🇪</div>
        </div>
        <div className="pc-c">
          <div className="num pc-price">{fmtP(ksa)}</div>
          <div className="pc-sub">Riyadh dealer 🇸🇦</div>
        </div>
        <div className="pc-c">
          <div className="num pc-price pc-leb">{fmtP(leb)}</div>
          <div className="pc-sub">Local dealer</div>
        </div>
        <div className="pc-c pc-icon">
          <div className="num pc-price-hero">{fmtP(icon)}</div>
          <div className="pc-sub" style={{ color: "var(--amber)" }}>Icon One · all-in 🚢</div>
        </div>
        <div className="pc-c pc-save">
          <div className="serif num" style={{ fontSize: 26, color: "var(--bone)", letterSpacing: "-.01em", lineHeight: 1 }}>{fmtP(save)}</div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: ".15em", color: "var(--amber)", marginTop: 6, textTransform: "uppercase" }}>{row.pct}% LESS</div>
        </div>
      </div>

      {/* Mobile card */}
      <div className="pc-card pc-mob" onClick={() => setOpen((o) => !o)} style={{ opacity: run ? 1 : 0, transform: run ? "none" : "translateY(8px)", transitionDelay: delay + "ms" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, marginBottom: 14 }}>
          <div>
            <div className="serif" style={{ fontSize: 22, color: "var(--bone)", letterSpacing: "-.01em", lineHeight: 1.1 }}>{row.model}</div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: ".15em", color: "var(--mute-2)", marginTop: 4 }}>{row.type}</div>
            {row.trim && <div style={{ fontSize: 12, color: "var(--mute)", marginTop: 3 }}>{row.trim}</div>}
          </div>
          <span style={{ color: "var(--mute-2)", fontSize: 18, transform: open ? "rotate(45deg)" : "none", transition: "transform .25s" }}>+</span>
        </div>
        <div className="pc-mob-rows">
          <div className="pc-mob-line"><span>Dubai 🇦🇪</span><span className="num">{fmtP(uae)}</span></div>
          <div className="pc-mob-line"><span>Riyadh 🇸🇦</span><span className="num">{fmtP(ksa)}</span></div>
          <div className="pc-mob-line"><span>Local dealer</span><span className="num">{fmtP(leb)}</span></div>
          <div className="pc-mob-line pc-mob-hero"><span>Icon One landed 🚢</span><span className="num">{fmtP(icon)}</span></div>
        </div>
        <div className="pc-mob-save">
          <span className="serif" style={{ fontSize: 22, color: "var(--bone)" }}>You save <span className="num">{fmtP(save)}</span></span>
          <span className="mono" style={{ fontSize: 10, letterSpacing: ".15em", color: "var(--amber)", marginInlineStart: 8 }}>{row.pct}% LESS</span>
        </div>
        {open && (
          <div className="pc-mob-expand">
            <div className="mono" style={{ fontSize: 10, letterSpacing: ".15em", color: "var(--mute-2)", textTransform: "uppercase", marginBottom: 10 }}>Where the savings come from</div>
            <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "grid", gap: 8, fontSize: 13, color: "var(--mute)", lineHeight: 1.5 }}>
              <li>· No local dealer margin</li>
              <li>· Direct factory invoice from China</li>
              <li>· Flat 5% Icon One fee, fully disclosed</li>
              <li>· Customs and freight at wholesale rates</li>
            </ul>
          </div>
        )}
      </div>
    </>
  );
}

function PriceComparison() {
  const ref = useRefP(null);
  const [run, setRun] = useStateP(false);
  useEffectP(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => es.forEach((e) => { if (e.isIntersecting) { setRun(true); io.disconnect(); } }), { threshold: 0.12 });
    io.observe(el); return () => io.disconnect();
  }, []);

  const avgSave = usePCCount(18500, run, 1100, 600);
  const wa = WA.beirut;

  return (
    <section id="compare" ref={ref} style={{ padding: "120px 0", borderTop: "1px solid var(--line)", background: "var(--ink-0)" }}>
      <div className="wrap">
        <SectionLabel
          eyebrow="Price comparison · May 2026"
          title="The same car. Five different prices."
          sub="Regional dealer prices vs. Icon One landed cost at your door. Updated quarterly. All figures USD."
          lang="en"
        />

        <div className="pc-table" data-reveal>
          {/* Desktop header */}
          <div className="pc-row pc-head pc-desk">
            <div className="pc-c pc-model"><span className="pc-h-lbl">Model</span></div>
            <div className="pc-c"><span className="pc-h-lbl">UAE 🇦🇪</span></div>
            <div className="pc-c"><span className="pc-h-lbl">KSA 🇸🇦</span></div>
            <div className="pc-c"><span className="pc-h-lbl">Local 🌍</span></div>
            <div className="pc-c pc-icon"><span className="pc-h-lbl pc-h-hero">Icon One Landed 🚢</span></div>
            <div className="pc-c pc-save"><span className="pc-h-lbl">You Save</span></div>
          </div>

          {/* Highlight band on Icon One column (desktop only) */}
          <div className="pc-band" aria-hidden="true">
            <div className="pc-band-fill" style={{ transform: run ? "scaleY(1)" : "scaleY(0)" }} />
          </div>

          {PC_ROWS.map((r, i) => <PCRow key={i} row={r} idx={i} run={run} />)}
        </div>

        <p className="pc-foot" data-reveal>
          Dealer prices benchmarked May 2026 from official dealer websites: BYD UAE, BYD KSA, and verified regional dealer networks.
          Icon One landed prices include China factory cost, sea freight to your port, local customs and VAT, registration, plates, notarization, and Icon One's flat 5% service fee.
          Final quote depends on spec, color, destination, exchange rate, and current freight rates. Confirm via WhatsApp.
        </p>

        <div className="pc-cta" data-reveal>
          <div className="pc-cta-micro">
            Average Icon One customer saves <span className="num" style={{ color: "var(--amber)" }}>${avgSave.toLocaleString("en-US")}</span> vs the local dealer.
            No dealer markup. No hidden fees. Direct from China.
          </div>
          <a href={wa} target="_blank" rel="noopener" className="btn btn-wa pc-cta-btn">
            <WAIcon /> Get my exact landed quote
          </a>
          <a href="#cost" className="pc-cta-ghost">
            Why is Icon One cheaper? See the breakdown <span className="flip">→</span>
          </a>
        </div>
      </div>

      <style>{`
        .pc-table { position: relative; border-top: 1px solid var(--line-2); }
        .pc-row { display: grid; grid-template-columns: 1.4fr .9fr .9fr 1fr 1.1fr 1.1fr; gap: 16px; align-items: center;
                  padding: 22px 16px; border-bottom: 1px solid rgba(239,233,221,0.10);
                  transition: opacity .55s cubic-bezier(.2,.7,.2,1), transform .55s cubic-bezier(.2,.7,.2,1), background .2s ease;
                  position: relative; z-index: 1; }
        .pc-row:hover { background: rgba(232,115,46,0.04); }
        .pc-head { padding-block: 14px; border-bottom: 1px solid var(--line-2); }
        .pc-head:hover { background: transparent; }
        .pc-h-lbl { font-family: var(--mono); font-size: 10px; letter-spacing: .18em; text-transform: uppercase; color: var(--mute-2); }
        .pc-h-hero { color: var(--amber); }
        .pc-c { min-width: 0; }
        .pc-price { font-family: var(--mono); font-size: 16px; color: var(--bone); font-variant-numeric: tabular-nums; }
        .pc-leb { font-weight: 500; }
        .pc-price-hero { font-family: var(--mono); font-size: 20px; color: var(--amber); font-weight: 500; font-variant-numeric: tabular-nums; }
        .pc-sub { font-family: var(--mono); font-size: 10px; letter-spacing: .12em; text-transform: uppercase; color: var(--mute-2); margin-top: 6px; }
        .pc-icon { position: relative; }
        .pc-save { text-align: end; }

        /* Highlight band over Icon One column */
        .pc-band {
          position: absolute; top: 60px; bottom: 0; pointer-events: none;
          /* Position calculated approximately for the 5th column */
          left: calc(((100% - 80px) / 6.4) * 4.0 + 16px);
          width: calc(((100% - 80px) / 6.4) * 1.1 - 8px);
          overflow: hidden; z-index: 0;
        }
        .pc-band-fill {
          position: absolute; inset: 0;
          background: linear-gradient(180deg, rgba(232,115,46,0.08) 0%, rgba(232,115,46,0.04) 60%, rgba(232,115,46,0) 100%);
          border-inline-start: 1px solid rgba(232,115,46,0.18);
          border-inline-end:   1px solid rgba(232,115,46,0.18);
          transform-origin: top; transform: scaleY(0);
          transition: transform .8s cubic-bezier(.4,.05,.2,1) .3s;
        }

        .pc-mob { display: none; }
        .pc-desk { display: grid; }

        @media (max-width: 900px) {
          .pc-desk { display: none; }
          .pc-mob { display: block; }
          .pc-band { display: none; }
          .pc-table { border-top: 0; }
        }

        .pc-card {
          padding: 22px 20px; border: 1px solid var(--line);
          background: var(--ink-1); border-radius: 4px;
          margin-bottom: 12px; cursor: pointer;
          transition: opacity .55s cubic-bezier(.2,.7,.2,1), transform .55s cubic-bezier(.2,.7,.2,1), border-color .2s, background .2s;
        }
        .pc-card:hover { border-color: rgba(232,115,46,0.3); }
        .pc-mob-rows { display: grid; gap: 8px; padding-block: 6px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
        .pc-mob-line { display: flex; justify-content: space-between; align-items: baseline; padding: 6px 0; font-size: 14px; color: var(--mute); font-family: var(--sans); }
        .pc-mob-line .num { font-family: var(--mono); color: var(--bone); font-variant-numeric: tabular-nums; }
        .pc-mob-line.pc-mob-hero { padding-top: 10px; border-top: 1px dashed rgba(232,115,46,0.2); }
        .pc-mob-line.pc-mob-hero .num { color: var(--amber); font-size: 16px; font-weight: 500; }
        .pc-mob-line.pc-mob-hero span:first-child { color: var(--bone); }
        .pc-mob-save { margin-top: 14px; display: flex; align-items: baseline; flex-wrap: wrap; gap: 6px; }
        .pc-mob-expand { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--line); }

        .pc-foot {
          margin-top: 28px; max-width: 880px;
          font-family: var(--sans); font-style: italic; font-size: 12px; line-height: 1.65; color: var(--mute-2);
        }
        .pc-cta {
          margin-top: 56px; padding-top: 36px; border-top: 1px solid var(--line);
          display: flex; flex-direction: column; align-items: flex-start; gap: 18px;
        }
        .pc-cta-micro { font-size: 14px; color: var(--mute); line-height: 1.55; max-width: 640px; }
        .pc-cta-btn { padding: 16px 28px; font-size: 15px; }
        .pc-cta-ghost { color: var(--mute); text-decoration: none; font-size: 14px; border-bottom: 1px solid var(--line-2); padding-bottom: 3px; transition: color .2s, border-color .2s; }
        .pc-cta-ghost:hover { color: var(--bone); border-bottom-color: var(--amber); }

        @media (prefers-reduced-motion: reduce) {
          .pc-row, .pc-card, .pc-band-fill { transition: none !important; }
        }
      `}</style>
    </section>
  );
}

window.PriceComparison = PriceComparison;
