// V3 — Ledger. Anti-marketing price decomposition. Big editorial numbers,
// animated count-up on load, side-by-side bars showing the gap between
// China showroom, Icon One delivered, and local dealer.
// Tone: financial pages / spec sheet. No car image.
//
// Now rotates through a set of real example cars every ROTATE_MS so the
// section reads as a live ticker rather than a single hardcoded quote.

const { useEffect: useEffectL, useState: useStateL, useRef: useRefL } = React;

const ROTATE_MS = 5500;

// Hand-curated set of cars spanning city EV → flagship supercar so the
// rotation shows the spread (cheap → expensive, save 33% → 50%). Pricing
// matches the catalog audit (Lebanon market, May 2026). `dealer: null`
// is allowed and renders the "no comparable offer" row.
const LEDGER_EXAMPLES = [
  { id: "xiaomi-su7-ultra", name: "Xiaomi SU7 Ultra",   sub: "Tri-motor 1,548 hp · Performance EV flagship", china: 73000, icon: 94300,  dealer: 141400, days: 47, pct: 33 },
  { id: "jetour-t2-idm",    name: "Jetour T2 i-DM",     sub: "PHEV Defender-style adventure SUV",            china: 15100, icon: 22000,  dealer: 33000,  days: 47, pct: 33 },
  { id: "byd-seagull",      name: "BYD Seagull",        sub: "City BEV · the everyday Chinese EV",           china:  7800, icon: 13400,  dealer: 20100,  days: 47, pct: 33 },
  { id: "byd-han",          name: "BYD Han",            sub: "Premium EV sedan · Tesla Model S alt.",        china: 14200, icon: 21000,  dealer: 31500,  days: 47, pct: 33 },
  { id: "jetour-x70-plus",  name: "Jetour X70 Plus",    sub: "Mid family SUV · chrome trim",                 china: 14500, icon: 21500,  dealer: 43000,  days: 47, pct: 50 },
  { id: "byd-tang",         name: "BYD Tang",           sub: "7-seat family SUV · PHEV / BEV",               china: 21400, icon: 30200,  dealer: 45300,  days: 47, pct: 33 },
  { id: "jetour-g700",      name: "Jetour G700",        sub: "Premium boxy off-roader · PHEV 4WD",           china: 32700, icon: 44800,  dealer: 67200,  days: 47, pct: 33 },
  { id: "bmw-i3-35l",       name: "BMW i3 eDrive 35L",  sub: "China-exclusive electric 3-Series sedan",      china: 38600, icon: 58000,  dealer: null,   days: 47, pct: 25 },
];

function useCountUp(target, durationMs = 1400) {
  const [v, setV] = useStateL(0);
  useEffectL(() => {
    let raf;
    const start = performance.now();
    const from = 0; // re-count from 0 every time target changes
    const tick = (now) => {
      const t = Math.min(1, (now - start) / durationMs);
      const e = 1 - Math.pow(1 - t, 3); // ease-out cubic
      setV(from + (target - from) * e);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, durationMs]);
  return v;
}

function fmtUSD(n, lang) {
  const r = Math.round(n);
  if (lang === "fr") return r.toLocaleString("fr-FR").replace(/ /g, " ") + " $";
  if (lang === "es") return "$" + r.toLocaleString("es-ES");
  if (lang === "ar") return r.toLocaleString("ar-EG") + " $";
  return "$" + r.toLocaleString("en-US");
}

function HeroLedger({ lang }) {
  const [idx, setIdx] = useStateL(0);
  const ex = LEDGER_EXAMPLES[idx];

  // Auto-rotate. Pause on hover via state below.
  const [paused, setPaused] = useStateL(false);
  useEffectL(() => {
    if (paused) return;
    const t = setInterval(() => setIdx((i) => (i + 1) % LEDGER_EXAMPLES.length), ROTATE_MS);
    return () => clearInterval(t);
  }, [paused]);

  const savingsTarget = ex.dealer ? (ex.dealer - ex.icon) : 0;
  const china   = useCountUp(ex.china,    1100);
  const icon    = useCountUp(ex.icon,     1500);
  const dealer  = useCountUp(ex.dealer || 0, 1300);
  const savings = useCountUp(savingsTarget, 1700);
  const days    = useCountUp(ex.days,     900);
  const noMarkup = useCountUp(ex.pct,     1300);

  const labels = {
    en: {
      r1: "China showroom",     r1n: "Manufacturer direct",
      r2: "China Bridge delivered", r2n: "Door-to-door · all-in",
      r3: "Local dealer",       r3n: "Same spec · Lebanon market",
      r3none: "Same spec · not available locally",
      na: "No comparable offer",
      d1: "Avg. saved vs. dealer", d2: "Door to door", d3: "No dealer margin",
      sub: "Every China Bridge quote breaks down into the same three numbers. We publish all three.",
      now: "Now showing",
    },
    fr: {
      r1: "Showroom Chine",     r1n: "Fabricant direct",
      r2: "Livré China Bridge", r2n: "Porte-à-porte · tout compris",
      r3: "Concessionnaire local", r3n: "Mêmes specs · marché libanais",
      r3none: "Mêmes specs · indisponible localement",
      na: "Pas d'offre comparable",
      d1: "Économie moy. vs concess.", d2: "Porte-à-porte", d3: "Sans marge concess.",
      sub: "Chaque devis China Bridge se décompose en trois mêmes chiffres. Nous les publions tous.",
      now: "Exemple en cours",
    },
    es: {
      r1: "Showroom China",     r1n: "Fabricante directo",
      r2: "Entregado China Bridge", r2n: "Puerta a puerta · todo incluido",
      r3: "Concesionario local", r3n: "Misma spec · mercado libanés",
      r3none: "Misma spec · no disponible localmente",
      na: "Sin oferta comparable",
      d1: "Ahorro medio vs conces.", d2: "Puerta a puerta", d3: "Sin margen concesionario",
      sub: "Cada cotización China Bridge se descompone en las mismas tres cifras. Publicamos las tres.",
      now: "Ejemplo actual",
    },
    ar: {
      r1: "معرض الصين",     r1n: "المصنع مباشرة",
      r2: "تشاينا بريدج واصلة", r2n: "من الباب إلى الباب · شامل",
      r3: "وكيل محلي",      r3n: "نفس المواصفات · السوق اللبناني",
      r3none: "نفس المواصفات · غير متوفر محلياً",
      na: "لا عرض مقارن",
      d1: "متوسط التوفير", d2: "من الباب إلى الباب", d3: "بدون هامش وكيل",
      sub: "كل عرض من تشاينا بريدج أوتو يتفكك إلى نفس الأرقام الثلاثة. ننشرها كاملة.",
      now: "العرض الحالي",
    },
  };
  const L = labels[lang] || labels.en;

  // Bar scaling — relative to the highest visible price in this example,
  // so rows always span a meaningful range no matter the price tier.
  const max = Math.max(ex.china, ex.icon, ex.dealer || ex.icon) * 1.1;
  const w1 = (ex.china / max) * 100;
  const w2 = (ex.icon  / max) * 100;
  const w3 = ex.dealer ? (ex.dealer / max) * 100 : 0;

  return (
    <div className="hv-ledger" aria-label="Price decomposition"
         onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>

      <div className="hv-ledger-head">
        <p className="hv-sub" style={{maxWidth:"58ch", margin:0}}>{L.sub}</p>
        <div className="hv-ledger-now">
          <span className="hv-ledger-now-label">{L.now}</span>
          <span className="hv-ledger-now-name">{ex.name}</span>
          <span className="hv-ledger-now-sub">{ex.sub}</span>
        </div>
        <div className="hv-ledger-dots" role="tablist" aria-label="Rotate examples">
          {LEDGER_EXAMPLES.map((_, i) => (
            <button key={i}
                    role="tab"
                    aria-selected={i === idx}
                    aria-label={`Example ${i + 1}`}
                    className={"hv-ledger-dot" + (i === idx ? " on" : "")}
                    onClick={() => { setIdx(i); setPaused(true); }} />
          ))}
        </div>
      </div>

      {/* key={idx} forces the rows to remount on each rotation so the
          bar-grow CSS animation re-fires. The count-up hooks re-fire via
          their target deps, but CSS keyframes need a fresh element. */}
      <div className="hv-ledger-rows" key={`rows-${idx}`}>
        <div className="hv-ledger-row">
          <div>
            <div className="hv-ledger-label">{L.r1}</div>
            <div className="hv-ledger-note">{L.r1n}</div>
          </div>
          <div className="hv-ledger-bar">
            <div className="hv-ledger-bar-fill" style={{width: `${w1}%`, animationDelay: "0.05s"}} />
          </div>
          <div className="hv-ledger-value">{fmtUSD(china, lang)}</div>
        </div>

        <div className="hv-ledger-row">
          <div>
            <div className="hv-ledger-label" style={{color:"#efe9dd"}}>{L.r2}</div>
            <div className="hv-ledger-note">{L.r2n}</div>
          </div>
          <div className="hv-ledger-bar">
            <div className="hv-ledger-bar-fill accent" style={{width: `${w2}%`, animationDelay: "0.4s"}} />
          </div>
          <div className="hv-ledger-value accent">{fmtUSD(icon, lang)}</div>
        </div>

        <div className="hv-ledger-row">
          <div>
            <div className="hv-ledger-label">{L.r3}</div>
            <div className="hv-ledger-note">{ex.dealer ? L.r3n : L.r3none}</div>
          </div>
          {ex.dealer ? (
            <div className="hv-ledger-bar">
              <div className="hv-ledger-bar-fill muted" style={{width: `${w3}%`, animationDelay: "0.7s"}} />
            </div>
          ) : (
            <div className="hv-ledger-bar-na">{L.na}</div>
          )}
          <div className={"hv-ledger-value" + (ex.dealer ? "" : " muted")}>
            {ex.dealer ? fmtUSD(dealer, lang) : "n/a"}
          </div>
        </div>
      </div>

      <div className="hv-ledger-delta">
        <div>
          <span className="l">{L.d1}</span>
          <span className="v save">{ex.dealer ? fmtUSD(savings, lang) : "n/a"}</span>
        </div>
        <div>
          <span className="l">{L.d2}</span>
          <span className="v">{Math.round(days)}d</span>
        </div>
        <div>
          <span className="l">{L.d3}</span>
          <span className="v">−{Math.round(noMarkup)}%</span>
        </div>
      </div>

    </div>
  );
}

// Brand coverage strip — real Wikimedia Commons logos hotlinked (PD/CC-BY-SA).
// `mono: true` means the brand's official mark is dark ink (designed for
// white backgrounds), so we apply a brightness(0)+invert filter to render
// it as a clean white silhouette on the dark hero. Coloured brand marks
// (BMW roundel, BYD red, Xiaomi orange, etc.) render as-is. If a remote
// URL ever 404s, the local bone wordmark placeholder takes over.
function LedgerBrands({ lang }) {
  const labels = {
    en: { lead: "We can get you cars from", more: "+ 22 more" },
    fr: { lead: "Nous vous procurons des voitures de", more: "+ 22 autres" },
    es: { lead: "Te conseguimos autos de", more: "+ 22 más" },
    ar: { lead: "نوفّر لك سيارات من", more: "+ ٢٢ أخرى" },
  };
  const L = labels[lang] || labels.en;

  // `src` can be a full URL (verified hotlinkable) or null to use the
  // local SVG only. Some brand marks live in Commons (Special:FilePath),
  // others only in the per-language Wikipedia upload namespace, which is
  // why the URLs differ. ROX has no Wikipedia logo at all — local only.
  const WC = "https://commons.wikimedia.org/wiki/Special:FilePath/";
  const brands = [
    { id: "xiaomi", name: "Xiaomi", src: `${WC}${encodeURIComponent("Xiaomi_logo_(2021-).svg")}`,             mono: false },
    { id: "huawei", name: "Huawei", src: "https://upload.wikimedia.org/wikipedia/en/0/04/Huawei_Standard_logo.svg", mono: false },
    { id: "byd",    name: "BYD",    src: `${WC}${encodeURIComponent("BYD_Auto_2022_logo.svg")}`,              mono: false },
    { id: "bmw",    name: "BMW",    src: `${WC}${encodeURIComponent("BMW.svg")}`,                              mono: false },
    { id: "rox",    name: "ROX",    src: null,                                                                 mono: true  },
    { id: "jetour", name: "Jetour", src: `${WC}${encodeURIComponent("Jetour_logo.svg")}`,                     mono: true  },
    { id: "geely",  name: "Geely",  src: `${WC}${encodeURIComponent("Geely_logo.svg")}`,                      mono: true  },
    { id: "zeekr",  name: "Zeekr",  src: `${WC}${encodeURIComponent("Zeekr_logo.svg")}`,                      mono: true  },
    { id: "nio",    name: "Nio",    src: `${WC}${encodeURIComponent("NIO_logo.svg")}`,                        mono: true  },
    { id: "xpeng",  name: "XPeng",  src: `${WC}${encodeURIComponent("XPeng_logo.svg")}`,                      mono: true  },
    { id: "hongqi", name: "Hongqi", src: "https://upload.wikimedia.org/wikipedia/en/7/7a/Hongqi_logo.svg",     mono: false },
  ];

  return (
    <div className="hv-ledger-brands" aria-label="Brands we source">
      <span className="hv-ledger-brands-lead">
        <span className="hv-ledger-brands-tick" aria-hidden="true" />
        {L.lead}
      </span>
      <div className="hv-ledger-brands-list">
        {brands.map((b) => (
          <img key={b.id}
               className={"hv-ledger-brand" + (b.mono ? " is-mono" : "")}
               src={b.src || `assets/brand-logos/${b.id}.svg`}
               alt={b.name}
               loading="lazy"
               onError={(e) => { e.currentTarget.onerror = null; e.currentTarget.src = `assets/brand-logos/${b.id}.svg`; }} />
        ))}
        <span className="hv-ledger-brands-more">{L.more}</span>
      </div>
    </div>
  );
}

window.HeroLedger = HeroLedger;

// ─── Standalone brand wall section ────────────────────────────────────────
// Hosts the same brand strip as a standalone credibility section so app.jsx
// can place it well below the hero (between Quality+Parts and FAQ) instead
// of crammed into the hero footer where it competed for attention.
function BrandWall({ lang }) {
  return (
    <section style={{
      padding: "100px 0 110px",
      borderTop: "1px solid var(--line)",
      background: "var(--ink-0)",
    }}>
      <div className="wrap" data-reveal>
        <LedgerBrands lang={lang} />
      </div>
    </section>
  );
}
window.BrandWall = BrandWall;
