// Shared small components.

const { useState, useEffect, useRef, useMemo, useCallback } = React;

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

function fmtAr(n) {
  // Arabic-Indic digits
  return "$" + Math.round(n).toLocaleString("ar-EG");
}

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll("[data-reveal]:not(.in)");
    if (!("IntersectionObserver" in window)) {
      els.forEach((e) => e.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.2, rootMargin: "0px 0px -10% 0px" }
    );
    els.forEach((e) => io.observe(e));
    return () => io.disconnect();
  });
}

// Counter that animates 0 → target on viewport entry, once.
function useCounter(target, { duration = 1200, decimals = 0 } = {}) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const [done, setDone] = useState(false);
  useEffect(() => {
    if (!ref.current || done) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (!e.isIntersecting) return;
          io.disconnect();
          const start = performance.now();
          const ease = (t) => 1 - Math.pow(1 - t, 3);
          const tick = (now) => {
            const p = Math.min(1, (now - start) / duration);
            setVal(target * ease(p));
            if (p < 1) requestAnimationFrame(tick);
            else setDone(true);
          };
          requestAnimationFrame(tick);
        });
      },
      { threshold: 0.4 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [target, duration, done]);
  return [ref, decimals ? val.toFixed(decimals) : Math.round(val)];
}

// Counter for arbitrary text with leading number — preserves formatting like "20–35%" / "1,000+"
function AnimatedStat({ text, duration = 1200, prefix = "" }) {
  // Extract first number from text
  const match = String(text).match(/(\d[\d,.]*)/);
  if (!match) return <span>{text}</span>;
  const raw = match[1];
  const target = parseFloat(raw.replace(/,/g, ""));
  const before = text.slice(0, match.index);
  const after = text.slice(match.index + raw.length);
  const [ref, val] = useCounter(target, { duration });
  const formatted = raw.includes(",") ? Math.round(val).toLocaleString("en-US") : Math.round(val);
  return <span ref={ref}>{before}{formatted}{after}</span>;
}

// Globe wordmark — recreates the brand mark inline so it scales cleanly on dark.
function LogoMark({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" aria-hidden="true">
      <circle cx="50" cy="50" r="34" fill="none" stroke="#3a5cd9" strokeWidth="3.2" />
      <ellipse cx="50" cy="50" rx="14" ry="34" fill="none" stroke="#3a5cd9" strokeWidth="3.2" />
      <ellipse cx="50" cy="50" rx="34" ry="14" fill="none" stroke="#3a5cd9" strokeWidth="3.2" />
      <line x1="50" y1="16" x2="50" y2="84" stroke="#3a5cd9" strokeWidth="2.4" />
      <line x1="16" y1="50" x2="84" y2="50" stroke="#3a5cd9" strokeWidth="2.4" />
      {/* arrow path Guangzhou → Beirut */}
      <path
        d="M 28 56 Q 42 40 64 44"
        fill="none"
        stroke="#f5a524"
        strokeWidth="3.2"
        strokeLinecap="round"
        strokeDasharray="3 5"
      />
      <path
        d="M 60 38 L 70 44 L 62 50"
        fill="none"
        stroke="#f5a524"
        strokeWidth="3.2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

// Wordmark using animated video logo
function Wordmark({ small = false }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
      <video className={"logo-video" + (small ? " sm" : "")}
             autoPlay muted loop playsInline
             src="assets/logo-animation.mp4" />
      <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
        <span style={{ fontFamily: "var(--serif)", fontSize: small ? 17 : 21, color: "var(--bone)", letterSpacing: "-0.01em" }}>
          Icon One <em style={{ fontStyle: "italic", color: "var(--amber)" }}>Auto</em>
        </span>
        <span className="mono" style={{ fontSize: 9, color: "var(--mute-2)", letterSpacing: "0.18em", textTransform: "uppercase", marginTop: 4 }}>
          China · Worldwide
        </span>
      </div>
    </div>
  );
}

// Inline car silhouette — a stylized side view (placeholder until real photos)
function CarSilhouette({ palette = ["#1d3aa8", "#0c1530"], variant = "sedan" }) {
  const [c1, c2] = palette;
  const id = useMemo(() => "g" + Math.random().toString(36).slice(2, 8), []);
  // simple sedan / suv profile
  const isSUV = variant.toLowerCase().includes("suv");
  const isWagon = variant.toLowerCase().includes("brake");
  const roofY = isSUV ? 38 : isWagon ? 40 : 44;
  return (
    <svg viewBox="0 0 320 140" style={{ width: "100%", height: "100%", display: "block" }} preserveAspectRatio="xMidYMid meet">
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={c1} stopOpacity="0.95" />
          <stop offset="100%" stopColor={c2} stopOpacity="0.95" />
        </linearGradient>
        <linearGradient id={id + "g"} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#fff" stopOpacity="0.18" />
          <stop offset="100%" stopColor="#fff" stopOpacity="0.02" />
        </linearGradient>
      </defs>
      {/* ground reflection */}
      <ellipse cx="160" cy="118" rx="120" ry="6" fill="#000" opacity="0.55" />
      {/* body */}
      <path
        d={`M 30 100
            L 60 100
            C 64 86, 80 78, 100 78
            L 130 78
            L 150 ${roofY}
            L 210 ${roofY}
            L 240 78
            L 260 78
            C 280 78, 290 88, 295 100
            L 305 100
            C 310 100, 312 105, 308 110
            L 35 110
            C 28 110, 26 104, 30 100 Z`}
        fill={`url(#${id})`}
        stroke="rgba(255,255,255,0.06)"
        strokeWidth="0.5"
      />
      {/* windows */}
      <path
        d={`M 105 80
            C 108 70, 118 64, 130 64
            L 148 64
            L 165 ${roofY + 4}
            L 195 ${roofY + 4}
            L 212 64
            L 235 64
            C 245 64, 252 70, 254 80 Z`}
        fill={`url(#${id}g)`}
        opacity="0.7"
      />
      {/* window divider */}
      <line x1="180" y1="64" x2="180" y2="80" stroke="rgba(255,255,255,0.18)" strokeWidth="1" />
      {/* wheels */}
      <circle cx="92" cy="108" r="14" fill="#0a0a0b" />
      <circle cx="92" cy="108" r="9" fill="#1a1a1f" stroke="rgba(255,255,255,0.12)" strokeWidth="0.5" />
      <circle cx="92" cy="108" r="3" fill="#2a2a30" />
      <circle cx="232" cy="108" r="14" fill="#0a0a0b" />
      <circle cx="232" cy="108" r="9" fill="#1a1a1f" stroke="rgba(255,255,255,0.12)" strokeWidth="0.5" />
      <circle cx="232" cy="108" r="3" fill="#2a2a30" />
      {/* headlight glow */}
      <ellipse cx="305" cy="92" rx="6" ry="2" fill="#fff5d8" opacity="0.6" />
      <ellipse cx="32" cy="92" rx="3" ry="1.5" fill="#ff5e5e" opacity="0.5" />
    </svg>
  );
}

// EV silhouette with rim light, headlight bars, reflective floor — Option A
function EVSilhouette() {
  return (
    <svg viewBox="0 0 900 520" preserveAspectRatio="xMidYMid meet" style={{ width: "100%", height: "100%", display: "block" }} aria-hidden="true">
      <defs>
        <linearGradient id="evbody" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#1a1a1f" />
          <stop offset="50%" stopColor="#0e0e10" />
          <stop offset="100%" stopColor="#050506" />
        </linearGradient>
        <linearGradient id="evrim" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="#e8732e" stopOpacity="0" />
          <stop offset="35%" stopColor="#e8732e" stopOpacity="0.85" />
          <stop offset="70%" stopColor="#ffb27a" stopOpacity="1" />
          <stop offset="100%" stopColor="#e8732e" stopOpacity="0" />
        </linearGradient>
        <linearGradient id="evfloor" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#0a0a0b" stopOpacity="0" />
          <stop offset="40%" stopColor="#0a0a0b" stopOpacity="0.6" />
          <stop offset="100%" stopColor="#0a0a0b" stopOpacity="1" />
        </linearGradient>
        <radialGradient id="underglow" cx="0.5" cy="0.5" r="0.5">
          <stop offset="0%" stopColor="#e8732e" stopOpacity="0.55" />
          <stop offset="60%" stopColor="#e8732e" stopOpacity="0.08" />
          <stop offset="100%" stopColor="#e8732e" stopOpacity="0" />
        </radialGradient>
        <linearGradient id="evwindow" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#26262d" stopOpacity="0.9" />
          <stop offset="100%" stopColor="#0a0a0b" stopOpacity="0.95" />
        </linearGradient>
        <filter id="rimblur" x="-20%" y="-20%" width="140%" height="140%">
          <feGaussianBlur stdDeviation="1.4" />
        </filter>
        <filter id="lightblur" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="2.2" />
        </filter>
      </defs>

      {/* under-car warm glow on floor */}
      <ellipse className="ev-underglow" cx="450" cy="395" rx="320" ry="42" fill="url(#underglow)" />

      {/* reflection (mirrored car, faded) */}
      <g transform="translate(0,790) scale(1,-1)" opacity="0.22">
        <path
          d="M 130 360
             C 160 320, 220 300, 280 296
             L 360 220
             C 380 200, 420 192, 460 192
             L 560 192
             C 600 192, 640 208, 660 232
             L 720 296
             C 760 300, 790 320, 810 356
             L 130 360 Z"
          fill="url(#evbody)"
        />
      </g>

      {/* car body — sleek EV sedan / shooting brake silhouette */}
      <g>
        {/* main body */}
        <path
          d="M 130 360
             C 160 320, 220 300, 280 296
             L 360 220
             C 380 200, 420 192, 460 192
             L 560 192
             C 600 192, 640 208, 660 232
             L 720 296
             C 760 300, 790 320, 810 356
             C 815 372, 805 384, 790 384
             L 150 384
             C 130 384, 122 374, 130 360 Z"
          fill="url(#evbody)"
        />

        {/* greenhouse / window */}
        <path
          d="M 300 296
             C 320 250, 360 226, 400 222
             L 555 222
             C 590 224, 620 244, 640 280
             L 660 296
             L 300 296 Z"
          fill="url(#evwindow)"
        />
        {/* window pillar (b-pillar suggestion) */}
        <line x1="478" y1="222" x2="478" y2="296" stroke="rgba(0,0,0,0.6)" strokeWidth="1.2" />

        {/* shoulder rim light — top edge along roof to hood */}
        <path
          d="M 280 296
             L 360 220
             C 380 200, 420 192, 460 192
             L 560 192
             C 600 192, 640 208, 660 232
             L 720 296"
          fill="none"
          stroke="url(#evrim)"
          strokeWidth="2.4"
          strokeLinecap="round"
          filter="url(#rimblur)"
        />
        {/* sharp inner highlight */}
        <path
          d="M 360 220
             C 380 200, 420 192, 460 192
             L 560 192
             C 600 192, 640 208, 660 232"
          fill="none"
          stroke="rgba(255,210,170,0.9)"
          strokeWidth="0.9"
        />

        {/* belt-line crease (subtle) */}
        <path
          d="M 180 332 L 800 332"
          stroke="rgba(232,115,46,0.08)"
          strokeWidth="1"
        />

        {/* front (right) headlight — thin horizontal bar */}
        <g className="ev-headlight">
          <rect x="772" y="334" width="36" height="3" rx="1.5" fill="#ffb27a" filter="url(#lightblur)" opacity="0.8" />
          <rect x="772" y="334" width="36" height="2" rx="1" fill="#fff1de" />
          {/* projection beam */}
          <path d="M 808 335 L 870 326 L 870 344 Z" fill="#e8732e" opacity="0.18" />
        </g>

        {/* rear (left) light bar — same modern signature */}
        <g className="ev-headlight">
          <rect x="132" y="334" width="32" height="3" rx="1.5" fill="#e8732e" filter="url(#lightblur)" opacity="0.55" />
          <rect x="132" y="334" width="32" height="2" rx="1" fill="#ffb27a" opacity="0.85" />
        </g>

        {/* wheels — flush, modern EV aero look */}
        <g>
          {/* rear */}
          <circle cx="240" cy="384" r="36" fill="#050506" />
          <circle cx="240" cy="384" r="26" fill="#16161a" stroke="rgba(255,255,255,0.06)" strokeWidth="0.5" />
          <circle cx="240" cy="384" r="14" fill="#0e0e10" />
          {/* aero spokes */}
          <g stroke="rgba(255,255,255,0.05)" strokeWidth="1" fill="none">
            <line x1="240" y1="362" x2="240" y2="406" />
            <line x1="222" y1="370" x2="258" y2="398" />
            <line x1="222" y1="398" x2="258" y2="370" />
            <line x1="218" y1="384" x2="262" y2="384" />
          </g>
          <circle cx="240" cy="384" r="3" fill="#1a1a1f" />
          {/* subtle rim light on top of wheel */}
          <path d="M 214 380 A 26 26 0 0 1 266 380" fill="none" stroke="rgba(232,115,46,0.35)" strokeWidth="0.8" />

          {/* front */}
          <circle cx="700" cy="384" r="36" fill="#050506" />
          <circle cx="700" cy="384" r="26" fill="#16161a" stroke="rgba(255,255,255,0.06)" strokeWidth="0.5" />
          <circle cx="700" cy="384" r="14" fill="#0e0e10" />
          <g stroke="rgba(255,255,255,0.05)" strokeWidth="1" fill="none">
            <line x1="700" y1="362" x2="700" y2="406" />
            <line x1="682" y1="370" x2="718" y2="398" />
            <line x1="682" y1="398" x2="718" y2="370" />
            <line x1="678" y1="384" x2="722" y2="384" />
          </g>
          <circle cx="700" cy="384" r="3" fill="#1a1a1f" />
          <path d="M 674 380 A 26 26 0 0 1 726 380" fill="none" stroke="rgba(232,115,46,0.35)" strokeWidth="0.8" />
        </g>

        {/* underbody soft warm glow strip */}
        <ellipse cx="470" cy="384" rx="240" ry="3" fill="#e8732e" opacity="0.35" filter="url(#lightblur)" />
      </g>

      {/* reflective floor fade */}
      <rect x="0" y="384" width="900" height="136" fill="url(#evfloor)" />
      {/* horizon hairline */}
      <line x1="0" y1="384" x2="900" y2="384" stroke="rgba(255,255,255,0.05)" strokeWidth="0.5" />
    </svg>
  );
}

// Hero backdrop — minimal: just a soft warm halo behind the car
function HeroBackdrop() {
  return (
    <div className="hero-img" aria-hidden="true">
      <div className="hero-grid" />
    </div>
  );
}

window.useReveal = useReveal;
window.useCounter = useCounter;
window.AnimatedStat = AnimatedStat;
window.LogoMark = LogoMark;
window.Wordmark = Wordmark;
window.CarSilhouette = CarSilhouette;
window.HeroBackdrop = HeroBackdrop;
window.EVSilhouette = EVSilhouette;

// Brand wordmarks — drawn as text in each brand's typographic style.
// Restrained, monochrome bone color so they read as editorial labels not stickers.
function BrandMark({ id, color = "var(--bone)" }) {
  const common = { fill: color };
  switch (id) {
    case "byd-seal":
    case "byd-atto-3":
      return (
        <svg viewBox="0 0 120 28" height="22" aria-label="BYD" style={{ display: "block" }}>
          <text x="0" y="22" {...common} style={{ fontFamily: "var(--sans)", fontSize: 24, fontWeight: 700, letterSpacing: "0.06em" }}>BYD</text>
        </svg>
      );
    case "zeekr-001":
      return (
        <svg viewBox="0 0 140 28" height="20" aria-label="ZEEKR" style={{ display: "block" }}>
          <text x="0" y="22" {...common} style={{ fontFamily: "var(--sans)", fontSize: 22, fontWeight: 500, letterSpacing: "0.32em" }}>ZEEKR</text>
        </svg>
      );
    case "hongqi-h5":
      return (
        <svg viewBox="0 0 160 28" height="20" aria-label="HONGQI" style={{ display: "block" }}>
          <text x="0" y="22" {...common} style={{ fontFamily: "var(--serif)", fontSize: 22, fontStyle: "italic", letterSpacing: "0.06em" }}>Hongqi</text>
        </svg>
      );
    case "geely-coolray":
      return (
        <svg viewBox="0 0 140 28" height="20" aria-label="GEELY" style={{ display: "block" }}>
          <text x="0" y="22" {...common} style={{ fontFamily: "var(--sans)", fontSize: 20, fontWeight: 600, letterSpacing: "0.22em" }}>GEELY</text>
        </svg>
      );
    default:
      return null;
  }
}
window.BrandMark = BrandMark;
window.fmt = fmt;
window.fmtAr = fmtAr;
