/* global React, ReactDOM, KENNY, GWM_DEALER, GWM_MODELS, GWM_PROMOS, gwmWa, kennyT, KENNY_HTML_LANG, TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakColor, TweakToggle, DisclaimerStrip, KennyBrand, KennyHero, GwmLocationSeo, AboutKenny, Deliveries, Reviews, LoanCalculator, Brochures, ShowroomInfo, LangSwitch, FloatingLang */
const { useState, useEffect, useMemo, createContext, useContext, useCallback } = React;

const KennyLangContext = createContext(null);
function useKennyLang() {
  const ctx = useContext(KennyLangContext);
  if (!ctx) {
    const lang = "EN";
    return {
      lang,
      setLang: () => {},
      t: (key, vars) => kennyT(lang, key, vars)
    };
  }
  return ctx;
}
window.useKennyLang = useKennyLang;

// Temporarily off — lineup cards stay browse-only; VDP modal code kept below for future use.
const SHOW_MODEL_VDP = false;

/* ============ Inline SVG icons & silhouettes ============ */
const Ico = {
  arrow: (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" {...p}><path d="M5 12h14m-6-6 6 6-6 6" stroke="currentColor" strokeWidth="2" /></svg>,
  wa: (p) => <svg width="28" height="28" viewBox="0 0 32 32" fill="#062b13" {...p}><path d="M16 3a13 13 0 0 0-11 19.7L3 29l6.6-1.8A13 13 0 1 0 16 3Zm0 23.6a10.5 10.5 0 0 1-5.4-1.5l-.4-.2-3.9 1 1-3.8-.3-.4A10.6 10.6 0 1 1 16 26.6Zm5.8-7.9c-.3-.2-1.9-.9-2.2-1s-.5-.2-.7.2-.8 1-1 1.2-.4.2-.7 0a8.7 8.7 0 0 1-4.3-3.7c-.3-.6.3-.5.9-1.7.1-.2 0-.4 0-.6s-.7-1.8-1-2.4-.5-.5-.7-.5h-.6a1.2 1.2 0 0 0-.8.4 3.6 3.6 0 0 0-1.1 2.6 6.2 6.2 0 0 0 1.3 3.3c.2.2 2.2 3.4 5.4 4.7s3.2 1 3.8 1a3.3 3.3 0 0 0 2.2-1.5 2.7 2.7 0 0 0 .2-1.5c-.1-.2-.3-.3-.7-.5Z" /></svg>,
  fb: (p) => <svg width="26" height="26" viewBox="0 0 24 24" fill="#fff" {...p}><path d="M22 12.07C22 6.51 17.52 2 12 2S2 6.51 2 12.07c0 5.02 3.66 9.18 8.44 9.93v-7.02H7.9v-2.91h2.54V9.85c0-2.52 1.49-3.92 3.78-3.92 1.09 0 2.24.2 2.24.2v2.47h-1.26c-1.24 0-1.63.78-1.63 1.57v1.89h2.78l-.45 2.91h-2.33V22c4.78-.75 8.44-4.91 8.44-9.93Z" /></svg>,
  xhs: (p) => <svg width="26" height="26" viewBox="0 0 32 32" fill="#fff" {...p}><text x="16" y="22" textAnchor="middle" fontFamily="-apple-system, sans-serif" fontSize="18" fontWeight="900" fill="#fff" letterSpacing="-0.5">小</text></svg>,
  pin: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M12 21s-7-7.5-7-12a7 7 0 0 1 14 0c0 4.5-7 12-7 12Z" /><circle cx="12" cy="9" r="2.5" /></svg>,
  clock: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>,
  phone: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A15 15 0 0 1 3 6a2 2 0 0 1 2-2Z" /></svg>,
  mail: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><rect x="3" y="5" width="18" height="14" /><path d="m3 6 9 7 9-7" /></svg>,
  close: (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M5 5l14 14M19 5 5 19" /></svg>,
  diff: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><circle cx="12" cy="12" r="8" /><circle cx="12" cy="12" r="3" /><path d="M12 4v4m0 8v4m8-8h-4M8 12H4" /></svg>,
  bolt: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="m13 2-8 12h6l-1 8 8-12h-6l1-8Z" /></svg>,
  cabin: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M3 17h18M5 17V9l3-4h8l3 4v8" /><circle cx="8" cy="17" r="2" /><circle cx="16" cy="17" r="2" /></svg>,
  shield: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6l-8-3Z" /></svg>,
  steering: (p) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="2.5"/><path d="M12 3v6.5M4.2 16.5l5.6-3.2M19.8 16.5l-5.6-3.2"/></svg>
};

/* Studio backdrop + optional car shape + watermark (shared by placeholder and real photos) */
function VehicleSilhouette({
  type = "suv",
  label,
  showShape = true,
  showModelLabel = true,
  showWatermark = true,
  showBackdropSky = true,
  showFloor = true
}) {
  const id = (label || type).replace(/\s+/g, "_");
  const isHatch = type === "hatch";
  const isMpv = type === "mpv";
  const needsDefs = showBackdropSky || showFloor || showShape;
  const svgClass = showFloor && !showBackdropSky
    ? "vehicle-photo__floor"
    : showBackdropSky
      ? "vehicle-photo__sky"
      : "vehicle-photo__watermark";
  return (
    <svg viewBox="0 0 800 480" preserveAspectRatio="xMidYMid slice" className={svgClass} style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }} aria-hidden="true">
      {needsDefs &&
      <defs>
        <linearGradient id={`bg-${id}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#1f1f1f" />
          <stop offset="0.6" stopColor="#0c0c0c" />
          <stop offset="1" stopColor="#000" />
        </linearGradient>
        <radialGradient id={`spot-${id}`} cx="0.65" cy="0.85" r="0.55">
          <stop offset="0" stopColor="rgba(225,29,46,0.45)" />
          <stop offset="1" stopColor="rgba(225,29,46,0)" />
        </radialGradient>
        <radialGradient id={`spot2-${id}`} cx="0.15" cy="0.15" r="0.4">
          <stop offset="0" stopColor="rgba(255,255,255,0.06)" />
          <stop offset="1" stopColor="rgba(255,255,255,0)" />
        </radialGradient>
        <linearGradient id={`floor-${id}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#525252" />
          <stop offset="1" stopColor="#343434" />
        </linearGradient>
        <linearGradient id={`body-${id}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#1a1a1a" />
          <stop offset="1" stopColor="#050505" />
        </linearGradient>
        <linearGradient id={`glass-${id}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#2a2a2a" />
          <stop offset="1" stopColor="#0a0a0a" />
        </linearGradient>
      </defs>
      }

      {showBackdropSky &&
      <>
        <rect width="800" height="480" fill={`url(#bg-${id})`} />
        <rect width="800" height="480" fill={`url(#spot-${id})`} />
        <rect width="800" height="480" fill={`url(#spot2-${id})`} />
      </>
      }

      {showFloor &&
      <>
        <line x1="0" y1="362" x2="800" y2="362" stroke="#5c5c5c" strokeWidth="1" />
        <rect y="362" width="800" height="118" fill={`url(#floor-${id})`} />
      </>
      }

      {showBackdropSky && showShape && (isHatch ?
      <g>
          <path d="M120 360 Q160 280 250 260 L420 245 Q540 250 620 295 L690 320 L700 360 L120 360 Z" fill={`url(#body-${id})`} stroke="#3c3c3c" strokeWidth="1" />
          <path d="M260 265 L360 235 L480 232 L560 270 L555 305 L260 305 Z" fill={`url(#glass-${id})`} stroke="#3c3c3c" strokeWidth="0.8" />
          <ellipse cx="240" cy="365" rx="42" ry="42" fill="#000" stroke="#3c3c3c" />
          <ellipse cx="240" cy="365" rx="22" ry="22" fill="#1a1a1a" stroke="#262626" />
          <ellipse cx="560" cy="365" rx="42" ry="42" fill="#000" stroke="#3c3c3c" />
          <ellipse cx="560" cy="365" rx="22" ry="22" fill="#1a1a1a" stroke="#262626" />
        </g> :
      isMpv ?
      <g>
          <path d="M80 360 Q110 220 230 200 L500 195 Q620 205 700 270 L740 320 L735 360 L80 360 Z" fill={`url(#body-${id})`} stroke="#3c3c3c" />
          <path d="M220 210 L350 175 L490 175 L600 230 L600 295 L220 295 Z" fill={`url(#glass-${id})`} stroke="#3c3c3c" strokeWidth="0.8" />
          <ellipse cx="220" cy="365" rx="50" ry="50" fill="#000" stroke="#3c3c3c" />
          <ellipse cx="600" cy="365" rx="50" ry="50" fill="#000" stroke="#3c3c3c" />
        </g> :

      // SUV (default — TANK / HAVAL / WEY)
      <g>
          <path d="M70 360 Q140 280 240 268 L380 258 L450 200 L610 195 Q690 205 730 250 L755 310 L750 360 L70 360 Z" fill={`url(#body-${id})`} stroke="#3c3c3c" strokeWidth="1" />
          <path d="M380 258 L450 205 L600 200 L620 258 Z" fill={`url(#glass-${id})`} stroke="#3c3c3c" strokeWidth="0.8" />
          <path d="M250 285 L380 270 L380 320 L250 320 Z" fill={`url(#glass-${id})`} opacity="0.7" stroke="#3c3c3c" strokeWidth="0.6" />
          <ellipse cx="200" cy="365" rx="60" ry="60" fill="#000" stroke="#3c3c3c" />
          <ellipse cx="200" cy="365" rx="30" ry="30" fill="#1a1a1a" stroke="#262626" />
          <ellipse cx="200" cy="365" rx="10" ry="10" fill="#2a2a2a" />
          <ellipse cx="610" cy="365" rx="60" ry="60" fill="#000" stroke="#3c3c3c" />
          <ellipse cx="610" cy="365" rx="30" ry="30" fill="#1a1a1a" stroke="#262626" />
          <ellipse cx="610" cy="365" rx="10" ry="10" fill="#2a2a2a" />
          {/* tail-light hint */}
          <rect x="725" y="270" width="22" height="8" fill="#E11D2E" opacity="0.75" rx="1" />
        </g>
      )}

      {showWatermark &&
      <g opacity="0.6">
        <text x="44" y="56" fontFamily="Inter" fontSize="11" fill="#7e7e7e" letterSpacing="3" fontWeight="700">GWM · KOTA DAMANSARA</text>
        {showModelLabel && label &&
        <text x="44" y="448" fontFamily="Inter" fontSize="56" fontWeight="900" fill="#1a1a1a" letterSpacing="-1">{label}</text>
        }
      </g>
      }
    </svg>);

}

const CARD_PHOTO_DEFAULT = window.GWM_CARD_PHOTO_DEFAULT || { scale: 100, x: 50, y: 55 };

function mergeCardPhoto(cardPhoto) {
  return { ...CARD_PHOTO_DEFAULT, ...(cardPhoto || {}) };
}

function vehiclePhotoType(id) {
  if (id === "ora03" || id === "oragoodcat" || id === "oragt") return "hatch";
  if (id === "weyg9") return "mpv";
  return "suv";
}

/* Real photo on studio backdrop; watermark stays above the photo */
function VehiclePhoto({ src, alt, type = "suv", label, style, cardPhoto }) {
  const [loaded, setLoaded] = useState(false);
  const [failed, setFailed] = useState(false);
  const hasSrc = src && src.trim().length > 0;
  const usePhoto = hasSrc && !failed;
  const showShape = !usePhoto || !loaded;
  const tune = mergeCardPhoto(cardPhoto);
  const offsetX = tune.x - CARD_PHOTO_DEFAULT.x;
  const offsetY = tune.y - CARD_PHOTO_DEFAULT.y;
  const imgTransform = loaded
    ? `translate(${offsetX}%, ${offsetY}%) scale(${tune.scale / 100})`
    : undefined;
  return (
    <div className="vehicle-photo" style={{ position: "absolute", inset: 0, ...style }}>
      <VehicleSilhouette
        type={type}
        label={label}
        showShape={showShape}
        showModelLabel={showShape}
        showWatermark={!usePhoto || !loaded}
        showBackdropSky
        showFloor />

      {usePhoto &&
      <img
        className="vehicle-photo__img"
        src={src}
        alt={alt || ""}
        onLoad={() => setLoaded(true)}
        onError={() => setFailed(true)}
        style={{
          opacity: loaded ? 1 : 0,
          transition: "opacity 400ms ease",
          objectPosition: `${CARD_PHOTO_DEFAULT.x}% ${CARD_PHOTO_DEFAULT.y}%`,
          transform: imgTransform,
          transformOrigin: `${CARD_PHOTO_DEFAULT.x}% ${CARD_PHOTO_DEFAULT.y}%`
        }} />

      }

      {usePhoto && loaded &&
      <VehicleSilhouette
        type={type}
        showBackdropSky={false}
        showFloor={false}
        showShape={false}
        showModelLabel={false} />
      }
    </div>);

}

window.VehiclePhoto = VehiclePhoto;

/* ============ Components ============ */
function BrandMark({ variant = "white" }) {
  return (
    <a href="#top" className="brand">
      <img src="assets/gwm-logo.png" alt="GWM" className="brand-logo" />
      <span className="brand-divider" />
      <div className="brand-text">
        <div className="a">KOTA DAMANSARA</div>
        <div className="b">Authorised Dealer</div>
      </div>
    </a>);

}

function Nav({ onOpenModel, layout = "full" }) {
  const { t } = useKennyLang();
  return (
    <header className="nav">
      <div className="shell nav-inner">
        <KennyBrand />
        <nav className="nav-links">
          <a href="#about-kenny">{t("nav.about")}</a>
          <a href="#lineup">{t("nav.models")}</a>
          <a href="#deliveries">{t("nav.gallery")}</a>
          <a href="#reviews">{t("nav.reviews")}</a>
          <a href="#loan">{t("nav.loan")}</a>
          <a href="#showroom">{t("nav.location")}</a>
        </nav>
        <div className="nav-right">
          <a className="btn btn--sm btn--primary" href="#booking">
            <Ico.steering style={{marginRight:'5px',verticalAlign:'middle'}} /> {t("nav.testDrive")}
          </a>
        </div>
      </div>
      <div className="gwm-stripe" />
    </header>);

}

function Hero({ onExplore }) {
  const hero = GWM_MODELS[0]; // TANK 300
  return (
    <section className="hero" id="top">
      <div className="hero-bg" />
      <div className="hero-grid" />
      <div className="hero-img-wrap">
        <VehiclePhoto src={hero.hero} alt={hero.heroAlt} type="suv" />
      </div>
      <div className="hero-vignette" />
      <div className="shell hero-content">
        <div className="hero-eyebrow">Now at GWM Kota Damansara</div>
        <h1 className="display-xl">The all-new<br /><span style={{ color: "var(--accent)" }}>TANK 300</span> Hybrid</h1>
        <p className="hero-sub">An off-road icon, reimagined. 255 PS hybrid powertrain, three locking differentials, and a luxury cabin that doesn't quit on the trail.</p>
        <div className="hero-ctas">
          <button className="btn btn--primary" onClick={() => onExplore("tank300")}>
            Explore TANK 300 <Ico.arrow />
          </button>
          <a className="btn" href="#booking">Book a Test Drive</a>
        </div>
      </div>
      <div className="hero-meta">
        <div className="stat">
          <div className="l">Starts from</div>
          <div className="v">RM 250,000</div>
        </div>
        <div className="stat">
          <div className="l">Power</div>
          <div className="v">255 PS</div>
        </div>
        <div className="stat">
          <div className="l">0–100 km/h</div>
          <div className="v">8.6 s</div>
        </div>
      </div>
    </section>);

}

function ModelCard({ m, onOpen }) {
  const { t } = useKennyLang();
  const clickable = SHOW_MODEL_VDP && m.available;
  const brochure = (window.KENNY_BROCHURE_BY_MODEL || {})[m.id];
  const priceList = window.KENNY_PRICE_LIST;
  const stopBubble = (e) => e.stopPropagation();

  const colors = Array.isArray(m.colors) ? m.colors : [];
  const [colorIdx, setColorIdx] = useState(0);
  const activeColor = colors[colorIdx];
  const photoSrc = activeColor?.image || m.hero;
  const photoAlt = activeColor
    ? `${m.name} in ${activeColor.name}`
    : m.heroAlt || m.name;

  return (
    <article
      className={`model-card${clickable ? "" : " model-card--browse-only"}`}
      onClick={clickable ? () => onOpen(m.id) : undefined}
      style={{ cursor: clickable ? "pointer" : "default" }}>
      
      <div className="img-frame">
        <VehiclePhoto
          src={photoSrc}
          alt={photoAlt}
          type={vehiclePhotoType(m.id)}
          label={m.name}
          cardPhoto={m.cardPhoto} />
        {m.comingSoon && <div className="badge-coming">{t("model.comingSoon")}</div>}
        {colors.length > 1 &&
        <div className="color-toggle" onClick={stopBubble}>
          {colors.map((c, i) =>
          <button
            key={c.name}
            type="button"
            className={`color-toggle__swatch${i === colorIdx ? " is-active" : ""}`}
            style={{ background: c.swatch }}
            onClick={(e) => { e.stopPropagation(); setColorIdx(i); }}
            aria-label={c.name}
            aria-pressed={i === colorIdx}
            title={c.name} />
          )}
        </div>
        }
        {activeColor &&
        <div className="color-toggle__name" aria-hidden="true">{activeColor.name}</div>
        }
      </div>
      <div className="body-pad">
        <div className="seg">{m.segment}</div>
        <div className="name">{m.name}</div>
        <div className="price-row">
          <div className="price">
            <div className="pre">{t("model.startFrom")}</div>
            <div className="v">{m.price}</div>
          </div>
          <a
            className="text-link"
            href={gwmWa(t("wa.model", { model: m.name, price: m.price }))}
            target="_blank" rel="noreferrer"
            style={{ color: "var(--accent)" }}
            onClick={stopBubble}>
            <Ico.wa width="14" height="14" style={{ filter: "brightness(2.8) saturate(1.2)" }} /> {t("model.whatsapp")}</a>
        </div>
        {(brochure || priceList) &&
        <div className="model-downloads" onClick={stopBubble}>
            {brochure &&
          <a className="model-dl" href={brochure} target="_blank" rel="noreferrer">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9l-6-6Z" /><path d="M14 3v6h6M9 13h6M9 17h6" /></svg>
                {t("model.brochure")}
              </a>
          }
            {priceList &&
          <a className="model-dl" href={priceList} target="_blank" rel="noreferrer">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9l-6-6Z" /><path d="M14 3v6h6M9 13h6M9 17h6" /></svg>
                {t("model.priceList")}
              </a>
          }
          </div>
        }
      </div>
    </article>);

}

function Lineup({ onOpenModel }) {
  const { t } = useKennyLang();
  return (
    <section className="section" id="lineup">
      <div className="shell">
        <div className="section-head">
          <div>
            <span className="label-muted">{t("lineup.label")}</span>
            <h2 className="display-lg">{t("lineup.title")}</h2>
          </div>
          <p className="body" style={{ maxWidth: 380 }}>
            {t("lineup.intro")}
          </p>
        </div>

        <div className="model-grid">
          {GWM_MODELS.map((m) =>
          <ModelCard key={m.id} m={m} onOpen={onOpenModel} />
          )}
        </div>
      </div>
    </section>);

}

/* ===== VDP ===== */
function VDP({ model, onClose }) {
  useEffect(() => {
    document.body.classList.add("modal-open");
    const esc = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", esc);
    return () => {
      document.body.classList.remove("modal-open");
      window.removeEventListener("keydown", esc);
    };
  }, [onClose]);

  if (!model) return null;
  const m = model;

  return (
    <div className="vdp-overlay" onClick={(e) => e.target.classList.contains("vdp-overlay") && onClose()}>
      <article className="vdp">
        {/* Top bar */}
        <div className="vdp-topbar">
          <div className="shell" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}>
            <div className="crumbs">
              GWM Kota Damansara &nbsp;/&nbsp; Models &nbsp;/&nbsp; <b>{m.name}</b>
            </div>
            <button className="vdp-close" onClick={onClose} aria-label="Close"><Ico.close /></button>
          </div>
        </div>

        {/* Hero */}
        <section className="vdp-hero">
          <div className="vdp-hero-img"><VehiclePhoto src={m.hero} alt={m.heroAlt} type={vehiclePhotoType(m.id)} label={m.name} cardPhoto={m.cardPhoto} /></div>
          <div className="shell vdp-hero-content">
            <div className="vdp-hero-grid">
              <div className="name-block">
                <div className="seg">{m.segment}</div>
                <h1 className="display-xl" style={{ fontSize: "clamp(48px, 7vw, 96px)" }}>{m.name}</h1>
                <p className="body" style={{ maxWidth: 540, marginTop: 16, fontSize: 18, color: "var(--body-strong)" }}>{m.headline}</p>
              </div>
              <div className="price-tag">
                <div className="pre">Start from</div>
                <div className="v">{m.price}</div>
                <div className="suf">{m.priceNote}</div>
              </div>
            </div>
          </div>
        </section>

        {/* Quick spec strip */}
        <div className="vdp-specs">
          {m.stats.map((s, i) =>
          <div className="cell" key={i}>
              <div className="l">{s.label}</div>
              <div className="v">{s.value}<span className="u"> {s.unit}</span></div>
            </div>
          )}
        </div>

        {/* Body */}
        <div className="shell vdp-body">
          {/* Overview row */}
          <div className="vdp-row">
            <div>
              <h3>Overview</h3>
              <div className="sub">01 · {m.name.toLowerCase()}</div>
            </div>
            <div>
              <p style={{ fontSize: 22, lineHeight: 1.4, fontWeight: 300, color: "var(--ink)", margin: 0, textWrap: "pretty" }}>
                {m.summary}
              </p>
              <div style={{ marginTop: 28, display: "flex", gap: 14, flexWrap: "wrap" }}>
                <a className="btn btn--wa" href={gwmWa(`Hi, I am interested in the ${m.name} (${m.price}). Can I get more info?`)} target="_blank" rel="noreferrer">
                  <Ico.wa width="16" height="16" /> Chat on WhatsApp
                </a>
                <a className="btn" href="#booking" onClick={onClose}>Book Test Drive</a>
              </div>
            </div>
          </div>

          {/* Gallery row */}
          <div className="vdp-row">
            <div>
              <h3>Gallery</h3>
              <div className="sub">02 · exterior & interior</div>
            </div>
            <div>
              <div className="gallery">
                <div className="g"><VehiclePhoto src={m.hero} alt="" type="suv" /></div>
                {m.gallery.slice(0, 3).map((g, i) =>
                <div className="g" key={i}><VehiclePhoto src={g} alt="" type="suv" /></div>
                )}
              </div>
            </div>
          </div>

          {/* Pillars row */}
          <div className="vdp-row">
            <div>
              <h3>Key Highlights</h3>
              <div className="sub">03 · what makes it stand out</div>
            </div>
            <div>
              <div className="pillars">
                {m.pillars.map((p, i) => {
                  const I = Ico[p.icon] || Ico.bolt;
                  return (
                    <div className="pillar" key={i}>
                      <div className="ico"><I /></div>
                      <h4>{p.title}</h4>
                      <p>{p.desc}</p>
                    </div>);

                })}
              </div>
            </div>
          </div>

          {/* Specs row */}
          <div className="vdp-row" style={{ marginBottom: 0 }}>
            <div>
              <h3>Specifications</h3>
              <div className="sub">04 · technical detail</div>
            </div>
            <div>
              <div className="spec-table">
                {m.specs.map((g, i) =>
                <div className="group" key={i} style={{ paddingLeft: i % 2 === 1 ? 32 : 0, paddingRight: i % 2 === 0 ? 32 : 0 }}>
                    <h4>{g.group}</h4>
                    {g.rows.map((r, j) =>
                  <div className="row" key={j}><span>{r[0]}</span><b>{r[1]}</b></div>
                  )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Sticky CTA at bottom */}
        <div className="vdp-cta">
          <div className="shell vdp-cta-grid">
            <div>
              <h3>Ready to take the {m.name} home?</h3>
              <p>Speak to our sales team at GWM Kota Damansara. We'll get you a financing quote in minutes.</p>
            </div>
            <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
              <a className="btn btn--wa" href={gwmWa(`Hi, I would like a quote for the ${m.name} (${m.price}). Please assist.`)} target="_blank" rel="noreferrer">
                <Ico.wa width="16" height="16" /> WhatsApp Sales
              </a>
              <a className="btn btn--primary" href="#booking" onClick={onClose}>Reserve a Test Drive</a>
            </div>
          </div>
        </div>
      </article>
    </div>);

}

/* ===== Promos ===== */
function Promos() {
  return (
    <section className="section hairline" id="promos" style={{ background: "var(--soft)" }}>
      <div className="shell">
        <div className="section-head">
          <div>
            <span className="label-muted">Current Offers</span>
            <h2 className="display-lg">This month at <span style={{ color: "var(--accent)" }}>Kota Damansara</span>.</h2>
          </div>
        </div>
        <div className="promos">
          {GWM_PROMOS.map((p, i) =>
          <a key={i} className="promo" href={gwmWa(p.msg)} target="_blank" rel="noreferrer">
              <div className="promo-bg"><VehiclePhoto src={p.bg} alt="" type="suv" /></div>
              <div className="promo-content">
                <span className="tag">{p.tag}</span>
                <div>
                  <h3>{p.title}</h3>
                  <p className="promo-desc">{p.desc}</p>
                  <span className="text-link" style={{ color: "var(--ink)" }}>{p.cta}</span>
                </div>
              </div>
            </a>
          )}
        </div>
      </div>
    </section>);

}

/* ===== About / Showroom — now Kenny-led; delegates to kenny-sections.jsx ===== */
function About() {return <ShowroomInfo />;}

/* ===== About / Showroom (legacy dealer block — replaced by ShowroomInfo) ===== */
function _AboutLegacy() {
  return (
    <section className="section" id="about">
      <div className="shell">
        <div className="about-grid">
          <div>
            <span className="label-muted">Visit Us</span>
            <h2 className="display-lg" style={{ marginTop: 12 }}>The showroom at Sunway Giza.</h2>
            <p className="body" style={{ marginTop: 20, maxWidth: 520 }}>
              Operated by Recengine Trading Sdn. Bhd., your authorised GWM dealer in the Klang Valley. Walk-ins welcome — every car in the lineup is on display, with expert sales consultants on the floor seven days a week.
            </p>
            <div className="info-list">
              <div className="info-row">
                <div className="ico"><Ico.pin /></div>
                <div>
                  <div className="l">Address</div>
                  <div className="v">{GWM_DEALER.address}</div>
                </div>
              </div>
              <div className="info-row">
                <div className="ico"><Ico.clock /></div>
                <div>
                  <div className="l">Sales Hours</div>
                  <div className="v">Monday — Sunday · 10:00 AM – 7:00 PM</div>
                </div>
              </div>
              <div className="info-row">
                <div className="ico"><Ico.phone /></div>
                <div>
                  <div className="l">Sales WhatsApp</div>
                  <div className="v">
                    <a href={gwmWa("Hi, I would like to enquire about a GWM model.")} target="_blank" rel="noreferrer" style={{ color: "var(--accent)" }}>
                      {GWM_DEALER.whatsappDisplay}
                    </a>
                  </div>
                </div>
              </div>
              <div className="info-row">
                <div className="ico"><Ico.mail /></div>
                <div>
                  <div className="l">Email</div>
                  <div className="v">{GWM_DEALER.email}</div>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 32, display: "flex", gap: 12, flexWrap: "wrap" }}>
              <a className="btn btn--primary" href={GWM_DEALER.gmaps} target="_blank" rel="noreferrer">Get Directions <Ico.arrow /></a>
              <a className="btn btn--wa" href={gwmWa("Hi, I would like to visit the GWM Kota Damansara showroom today.")} target="_blank" rel="noreferrer">
                <Ico.wa width="16" height="16" /> Confirm Visit
              </a>
            </div>
          </div>

          <div>
            <div className="map-frame">
              <iframe
                title="GWM Kota Damansara Map"
                width="100%" height="100%"
                style={{ border: 0, filter: "invert(0.92) hue-rotate(180deg) saturate(0.6) brightness(0.95)" }}
                src="https://www.google.com/maps?q=GWM%20Kota%20Damansara&output=embed"
                loading="lazy" />
              
            </div>
            <div className="caption" style={{ marginTop: 12 }}>Sunway Giza Mall · Block A, Ground Floor</div>
          </div>
        </div>
      </div>
    </section>);

}

/* ===== Booking form ===== */
function Booking() {
  const { t } = useKennyLang();
  const today = new Date().toISOString().slice(0, 10);
  const bookingModels = useMemo(
    () => (GWM_MODELS || []).map((m) => m.name),
    []
  );
  const bookingExtra = t("booking.notSure");
  const [state, setState] = useState({
    name: "",
    model: bookingModels[0] || "TANK 300",
    date: today,
    time: ""
  });
  const [submitted, setSubmitted] = useState(false);

  const onChange = (k) => (e) => setState((s) => ({ ...s, [k]: e.target.value }));

  const onSubmit = (e) => {
    e.preventDefault();
    setSubmitted(true);
    const msg = t("wa.booking", {
      name: state.name,
      model: state.model,
      date: state.date,
      time: state.time || "-"
    });
    setTimeout(() => {
      window.open(gwmWa(msg), "_blank");
    }, 800);
  };

  return (
    <section className="section hairline" id="booking" style={{ background: "var(--soft)" }}>
      <div className="shell">
        <div className="section-head">
          <div>
            <span className="label-muted">{t("booking.label")}</span>
            <h2 className="display-lg">{t("booking.title")}</h2>
          </div>
          <p className="body" style={{ maxWidth: 380 }}>
            {t("booking.intro")}
          </p>
        </div>

        {submitted ?
        <div className="success-block">
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--whatsapp)", display: "inline-grid", placeItems: "center", marginBottom: 16 }}>
              <Ico.wa />
            </div>
            <h3 className="display-md" style={{ marginBottom: 12 }}>{t("booking.successTitle")}</h3>
            <p className="body" style={{ maxWidth: 480, margin: "0 auto" }}>
              {t("booking.successBody")}
            </p>
            <div style={{ marginTop: 24 }}>
              <button className="btn" onClick={() => setSubmitted(false)}>{t("booking.submitAnother")}</button>
            </div>
          </div> :

        <form className="form-card" onSubmit={onSubmit}>
            <div className="form-grid">
              <div className="field">
                <label>{t("booking.name")}</label>
                <input required value={state.name} onChange={onChange("name")} placeholder="" />
              </div>
              <div className="field">
                <label>{t("booking.model")}</label>
                <select required value={state.model} onChange={onChange("model")}>
                  {bookingModels.map((name) =>
                  <option key={name} value={name}>{name}</option>
                  )}
                  <option value={bookingExtra}>{bookingExtra}</option>
                </select>
              </div>
              <div className="field">
                <label>{t("booking.date")}</label>
                <div className="date-picker-wrap">
                  <input
                    required
                    type="date"
                    min={today}
                    value={state.date}
                    onChange={onChange("date")}
                    className="date-picker"
                    onClick={(e) => { try { e.currentTarget.showPicker && e.currentTarget.showPicker(); } catch {} }}
                  />
                  <svg className="date-picker-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                    <rect x="3" y="5" width="18" height="16" rx="1"/>
                    <path d="M3 9h18M8 3v4M16 3v4"/>
                  </svg>
                </div>
              </div>
              <div className="field">
                <label>{t("booking.time")}</label>
                <select value={state.time} onChange={onChange("time")}>
                  <option value="">{t("booking.timePlaceholder")}</option>
                  <option>{t("booking.timeSlot1")}</option>
                  <option>{t("booking.timeSlot2")}</option>
                  <option>{t("booking.timeSlot3")}</option>
                  <option>{t("booking.timeSlot4")}</option>
                </select>
              </div>
            </div>
            <div style={{ marginTop: 32, display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
              <button type="submit" className="btn btn--primary">{t("booking.submit")} <Ico.arrow /></button>
              <span className="caption">{t("booking.submitHint")}</span>
            </div>
          </form>
        }
      </div>
    </section>);

}

/* ===== Footer ===== */
function Footer() {
  const { t } = useKennyLang();
  return (
    <footer className="footer">
      <div className="shell footer-grid">
        <div>
          <KennyBrand />
        </div>
        <div>
          <div className="footer-heading">{t("footer.models")}</div>
          {GWM_MODELS.map((m) =>
          <React.Fragment key={m.id}>
              <a href="#lineup">{m.name}</a><br />
            </React.Fragment>
          )}
        </div>
        <div>
          <div className="footer-heading">{t("footer.quickLinks")}</div>
          <a href="#about-kenny">{t("nav.about")}</a><br />
          <a href="#deliveries">{t("nav.gallery")}</a><br />
          <a href="#reviews">{t("nav.reviews")}</a><br />
          <a href="#loan">{t("loan.label")}</a><br />
          <a href="#booking">{t("booking.label")}</a>
        </div>
        <div>
          <div className="footer-heading">{t("footer.talk")}</div>
          <a href={gwmWa(t("wa.footer"))} target="_blank" rel="noreferrer">WhatsApp · {KENNY.whatsappDisplay}</a><br />
          <a href={KENNY.facebook} target="_blank" rel="noreferrer">Facebook</a><br />
          <a href={KENNY.xhs} target="_blank" rel="noreferrer">Xiaohongshu</a><br />
          <a href={`mailto:${KENNY.email}`}>{KENNY.email}</a>
        </div>
      </div>
      <div className="shell footer-bottom">
        <div>{t("footer.copyright")}</div>
        <div>{t("footer.disclaimer")}</div>
      </div>
      <div className="gwm-stripe" style={{ marginTop: 28 }} />
    </footer>);

}

/* ===== Floating Social Buttons ===== */
function FloatingWa({ lang, setLang }) {
  const { t } = useKennyLang();
  return (
    <div className="fab-stack">
      <a className="fab fab-wa" href={gwmWa(t("wa.fab"))} target="_blank" rel="noreferrer" aria-label="WhatsApp">
        <Ico.wa />
      </a>
      <FloatingLang lang={lang} setLang={setLang} />
    </div>);

}

/* ===== Tweaks ===== */
const ACCENT_PRESETS = {
  "GWM Red": { accent: "#E11D2E", accent2: "#F26B2A" },
  "Sunset Orange": { accent: "#F26B2A", accent2: "#E11D2E" },
  "Electric Blue": { accent: "#1C69D4", accent2: "#0fa3ff" },
  "Deep Crimson": { accent: "#8b0000", accent2: "#E11D2E" }
};

/* ===== WhatsApp Click-to-Chat Modal =====
   wa.me 302-redirects through api.whatsapp.com — which is blocked on many
   corporate / regional networks. This modal makes the click-to-chat usable
   regardless: shows the number, copyable prefilled text, and 3 launch routes
   (web, app deep-link, raw api fallback). */
function WaModal({ payload, onClose }) {
  const [copiedField, setCopiedField] = useState(null);
  useEffect(() => {
    const esc = (e) => e.key === "Escape" && onClose();
    document.body.classList.add("modal-open");
    window.addEventListener("keydown", esc);
    return () => {
      document.body.classList.remove("modal-open");
      window.removeEventListener("keydown", esc);
    };
  }, [onClose]);

  if (!payload) return null;
  const { phone, message } = payload;
  const phoneDisplay = GWM_DEALER.whatsappDisplay;
  const waMeUrl = `https://api.whatsapp.com/send?phone=${phone}&text=${encodeURIComponent(message)}`;
  const appDeepLink = `whatsapp://send?phone=${phone}&text=${encodeURIComponent(message)}`;

  const copy = async (text, field) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedField(field);
      setTimeout(() => setCopiedField(null), 1800);
    } catch {
      // fallback
      const ta = document.createElement("textarea");
      ta.value = text;
      document.body.appendChild(ta);
      ta.select();
      try {document.execCommand("copy");} catch {}
      document.body.removeChild(ta);
      setCopiedField(field);
      setTimeout(() => setCopiedField(null), 1800);
    }
  };

  return (
    <div className="wa-modal-overlay" onClick={(e) => e.target.classList.contains("wa-modal-overlay") && onClose()}>
      <div className="wa-modal" role="dialog" aria-modal="true">
        <button className="wa-modal-close" onClick={onClose} aria-label="Close"><Ico.close /></button>

        <div className="wa-modal-head">
          <div className="wa-modal-badge"><Ico.wa /></div>
          <div>
            <div className="label-muted">Chat with GWM Kota Damansara</div>
            <h3 className="display-md" style={{ marginTop: 6, fontSize: 28, textTransform: "none", letterSpacing: "-0.4px" }}>Sales · Mon–Sun · 10am–7pm</h3>
          </div>
        </div>

        <div className="wa-modal-body">
          <div className="wa-field">
            <div className="wa-field-l">WhatsApp Number</div>
            <div className="wa-field-row">
              <div className="wa-field-v">{phoneDisplay}</div>
              <button className="btn btn--sm" onClick={() => copy(phoneDisplay, "phone")}>
                {copiedField === "phone" ? "Copied ✓" : "Copy"}
              </button>
            </div>
          </div>

          {message &&
          <div className="wa-field">
              <div className="wa-field-l">Prefilled Message</div>
              <div className="wa-message-box">{message}</div>
              <div style={{ marginTop: 10 }}>
                <button className="btn btn--sm" onClick={() => copy(message, "msg")}>
                  {copiedField === "msg" ? "Copied ✓" : "Copy Message"}
                </button>
              </div>
            </div>
          }

          <div className="wa-divider">
            <span>OR LAUNCH WHATSAPP</span>
          </div>

          <div className="wa-launch-grid">
            <a className="wa-launch" href={appDeepLink}>
              <div className="wa-launch-ico" style={{ background: "var(--whatsapp)", color: "#062b13" }}><Ico.wa /></div>
              <div>
                <div className="wa-launch-t">Open WhatsApp App</div>
                <div className="wa-launch-d">If installed on this device</div>
              </div>
            </a>
            <a className="wa-launch" href={waMeUrl} target="_blank" rel="noreferrer">
              <div className="wa-launch-ico" style={{ background: "#1c69d4", color: "#fff" }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" /></svg>
              </div>
              <div>
                <div className="wa-launch-t">Open in Browser</div>
                <div className="wa-launch-d">via api.whatsapp.com</div>
              </div>
            </a>
          </div>

          <p className="caption" style={{ marginTop: 18, lineHeight: 1.5 }}>
            If the launch buttons don't open WhatsApp on your network, copy the number
            and start a new chat manually — your message is already in your clipboard.
          </p>
        </div>
      </div>
    </div>);

}

function App() {
  const [openId, setOpenId] = useState(null);
  const [lang, setLangState] = useState(() => {
    try {return localStorage.getItem("kenny.lang") || "EN";} catch {return "EN";}
  });
  const setLang = (v) => {
    setLangState(v);
    try {localStorage.setItem("kenny.lang", v);} catch {}
  };

  const [t, setTweak] = useTweaks(/*EDITMODE-BEGIN*/{
    "accent": "GWM Red",
    "disclaimer": "off",
    "showReviews": true,
    "showDeliveries": true,
    "showPromos": false,
    "showWaFab": true
  } /*EDITMODE-END*/);

  // Apply accent
  useEffect(() => {
    const preset = ACCENT_PRESETS[t.accent] || ACCENT_PRESETS["GWM Red"];
    document.documentElement.style.setProperty("--accent", preset.accent);
    document.documentElement.style.setProperty("--accent-2", preset.accent2);
  }, [t.accent]);

  const openModel = useMemo(() => GWM_MODELS.find((m) => m.id === openId) || null, [openId]);
  const jumpTo = (id) => () => {
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 78, behavior: "smooth" });
  };

  const translate = useCallback((key, vars) => kennyT(lang, key, vars), [lang]);
  const langValue = useMemo(() => ({ lang, setLang, t: translate }), [lang, setLang, translate]);

  useEffect(() => {
    document.documentElement.lang = KENNY_HTML_LANG[lang] || "en";
  }, [lang]);

  return (
    <KennyLangContext.Provider value={langValue}>
      <DisclaimerStrip prominence={t.disclaimer} />
      <Nav onOpenModel={setOpenId} />
      <main id="main-content">
        <KennyHero />
        <GwmLocationSeo />
        <AboutKenny onJumpModels={jumpTo("lineup")} />
        <Lineup onOpenModel={setOpenId} />
        {t.showDeliveries && <Deliveries />}
        {t.showReviews && <Reviews />}
        <LoanCalculator />
        {t.showPromos && <Promos />}
        <ShowroomInfo />
        <Booking />
      </main>
      <Footer />
      {t.showWaFab && <FloatingWa lang={lang} setLang={setLang} />}
      {SHOW_MODEL_VDP && openModel && <VDP model={openModel} onClose={() => setOpenId(null)} />}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Disclaimer Prominence" />
        <TweakRadio
          label="Visibility"
          value={t.disclaimer}
          options={["strong", "medium", "off"]}
          onChange={(v) => setTweak("disclaimer", v)} />
        
        <TweakSection label="Brand Accent" />
        <TweakRadio
          label="Color"
          value={t.accent}
          options={Object.keys(ACCENT_PRESETS)}
          onChange={(v) => setTweak("accent", v)} />
        
        <TweakSection label="Sections" />
        <TweakToggle label="Customer Reviews" value={t.showReviews} onChange={(v) => setTweak("showReviews", v)} />
        <TweakToggle label="Delivery Wall" value={t.showDeliveries} onChange={(v) => setTweak("showDeliveries", v)} />
        <TweakToggle label="Current Offers" value={t.showPromos} onChange={(v) => setTweak("showPromos", v)} />
        <TweakSection label="Floating WhatsApp" />
        <TweakToggle
          label="Show pulse button"
          value={t.showWaFab}
          onChange={(v) => setTweak("showWaFab", v)} />
        
      </TweaksPanel>
    </KennyLangContext.Provider>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);