/* global React, Icon */
const { useState, useEffect, useMemo } = React;

function Hero({ audience }) {
  const tagline = audience === 'fleet' ? 'Tu patrimonio en tus manos.' : 'Protege lo que más amas.';
  const sub = audience === 'fleet'
    ? 'Rastreo satelital y monitoreo profesional para flotillas, transporte y logística. Cobertura nacional.'
    : 'Rastreo satelital con cobertura nacional, monitoreo 24/7 y respuesta inmediata cuando algo no encaja.';

  return (
    <section id="top" className="hero">
      <div className="hero-grain" aria-hidden />
      <div className="container hero-grid">
        <div className="hero-left">
          <span className="pill">
            <span className="dot" />
            <span>Cobertura nacional · Monitoreo 24/7</span>
          </span>

          <h1 className="display hero-title">{tagline}</h1>
          <p className="hero-sub">{sub}</p>

          <div className="hero-cta">
            <a href="#contacto" className="btn btn-primary">
              Cotiza tu GPS <Icon name="arrow" size={16} />
            </a>
            <a href="#producto" className="btn btn-ghost">
              Conoce el sistema
            </a>
          </div>

          <HeroStats />
        </div>

        <div className="hero-right">
          <NavigatorMap />
        </div>
      </div>

      <style>{`
        .hero {
          position: relative; overflow: hidden;
          padding: clamp(40px, 6vw, 90px) 0 clamp(60px, 8vw, 120px);
        }
        .hero-grain {
          position: absolute; inset: 0;
          background:
            radial-gradient(1200px 600px at 80% 0%, color-mix(in oklab, var(--petrol) 18%, transparent), transparent 60%),
            radial-gradient(900px 500px at 0% 100%, color-mix(in oklab, var(--peach) 8%, transparent), transparent 60%);
          pointer-events: none; opacity: .8;
        }
        .hero-grid {
          position: relative;
          display: grid;
          grid-template-columns: 1fr 1.15fr;
          gap: clamp(32px, 5vw, 80px);
          align-items: center;
        }
        @media (max-width: 980px) { .hero-grid { grid-template-columns: 1fr; } }
        .hero-left { display: flex; flex-direction: column; gap: 28px; }
        .hero-title { font-size: clamp(40px, 8.4vw, 108px); margin: 4px 0 0; font-weight: 600; }
        @media (max-width: 600px) {
          .hero-cta { flex-direction: column; align-items: stretch; }
          .hero-cta .btn { justify-content: center; }
        }
        .hero-sub {
          font-size: clamp(17px, 1.4vw, 20px);
          color: var(--ink-2); max-width: 52ch; margin: 0;
          line-height: 1.45; text-wrap: pretty;
        }
        .hero-cta { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 4px; }
        .hero-play-icon {
          display: inline-grid; place-items: center;
          width: 22px; height: 22px;
          border-radius: 50%;
          background: var(--petrol);
          color: #07171a;
          font-size: 9px;
          padding-left: 1px;
        }

        .hero-right { position: relative; }
      `}</style>
    </section>
  );
}

function HeroStats() {
  const stats = [
    { k: '32 estados', v: 'cobertura nacional' },
    { k: '1,200+',   v: 'unidades monitoreadas' },
    { k: '24/7',     v: 'monitoreo y soporte' },
  ];
  return (
    <div className="hero-stats">
      {stats.map((s, i) => (
        <div key={i} className="hero-stat">
          <div className="hero-stat-k display">{s.k}</div>
          <div className="hero-stat-v">{s.v}</div>
        </div>
      ))}
      <style>{`
        .hero-stats {
          display: grid; grid-template-columns: repeat(3, 1fr);
          gap: 18px; padding-top: 28px;
          border-top: 1px solid var(--line); margin-top: 12px;
        }
        @media (max-width: 480px) {
          .hero-stats { gap: 12px; padding-top: 22px; }
        }
        .hero-stat-k { font-size: 22px; font-weight: 600; letter-spacing: -0.02em; }
        @media (max-width: 480px) {
          .hero-stat-k { font-size: 17px; }
          .hero-stat-v { font-size: 9px; letter-spacing: 0.06em; }
        }
        .hero-stat-v {
          font-family: var(--font-mono); font-size: 11px;
          letter-spacing: 0.1em; text-transform: uppercase;
          color: var(--ink-mute); margin-top: 4px; line-height: 1.4;
        }
      `}</style>
    </div>
  );
}

/* ============================================================
   A — NavigatorMap: dark zoomed-in street map (Mapbox-style)
   ============================================================ */
function NavigatorMap() {
  const [tick, setTick] = useState(0);
  const [feed, setFeed] = useState([]);
  // Vehicle moves along a polyline 0..1
  const [t, setT] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setTick(x => (x + 1) % 1000), 700);
    return () => clearInterval(id);
  }, []);

  useEffect(() => {
    let raf;
    let last = performance.now();
    const loop = (now) => {
      const dt = (now - last) / 1000; last = now;
      setT(v => (v + dt * 0.08) % 1);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Live feed
  useEffect(() => {
    const events = [
      { t: 'Geo-cerca confirmada', city: 'Insurgentes Sur', kind: 'good' },
      { t: 'Encendido de motor',   city: 'Polanco',         kind: 'info' },
      { t: 'Exceso de velocidad',  city: 'Periférico',      kind: 'alert' },
      { t: 'Botón de pánico',      city: 'Tlalpan',         kind: 'urgent' },
      { t: 'Ruta completada',      city: 'Reforma',         kind: 'good' },
    ];
    let i = 0;
    const id = setInterval(() => {
      const ev = events[i % events.length];
      setFeed(prev => [{ ...ev, ts: Date.now(), id: Math.random() }, ...prev].slice(0, 4));
      i++;
    }, 2200);
    return () => clearInterval(id);
  }, []);

  // Main route — a curving polyline through the "city"
  const route = useMemo(() => {
    return [
      [60, 480], [110, 460], [165, 430], [210, 405],
      [260, 380], [310, 360], [360, 340], [420, 320],
      [470, 280], [520, 240], [560, 215], [610, 200],
      [660, 175], [710, 150], [760, 130], [810, 115],
      [870, 100], [930, 90],
    ];
  }, []);
  const routePath = 'M ' + route.map(p => p.join(' ')).join(' L ');
  const routeLen = useMemo(() => {
    let total = 0;
    for (let i = 1; i < route.length; i++) {
      const dx = route[i][0] - route[i - 1][0];
      const dy = route[i][1] - route[i - 1][1];
      total += Math.sqrt(dx * dx + dy * dy);
    }
    return total;
  }, [route]);

  // Vehicle position along route
  const veh = useMemo(() => {
    let dist = t * routeLen;
    for (let i = 1; i < route.length; i++) {
      const dx = route[i][0] - route[i - 1][0];
      const dy = route[i][1] - route[i - 1][1];
      const seg = Math.sqrt(dx * dx + dy * dy);
      if (dist <= seg) {
        const f = dist / seg;
        return {
          x: route[i - 1][0] + dx * f,
          y: route[i - 1][1] + dy * f,
          angle: Math.atan2(dy, dx) * 180 / Math.PI,
        };
      }
      dist -= seg;
    }
    return { x: route[route.length - 1][0], y: route[route.length - 1][1], angle: 0 };
  }, [t, route, routeLen]);

  return (
    <div className="navmap">
      <svg viewBox="0 0 1000 600" preserveAspectRatio="xMidYMid slice" className="navmap-svg">
        <defs>
          <radialGradient id="nightSky" cx="50%" cy="0%" r="100%">
            <stop offset="0%" stopColor="#102b32" />
            <stop offset="100%" stopColor="#040b0d" />
          </radialGradient>
          <linearGradient id="routeGrad" x1="0" x2="1" y1="0" y2="0">
            <stop offset="0%" stopColor="#4fb3c4" stopOpacity="0.2" />
            <stop offset="40%" stopColor="#6ed1de" stopOpacity="0.9" />
            <stop offset="100%" stopColor="#f2c792" />
          </linearGradient>
          <filter id="glowSoft" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="2.5" />
          </filter>
        </defs>

        <rect width="1000" height="600" fill="url(#nightSky)" />

        {/* City blocks (extruded looking, but flat) */}
        <CityBlocks />

        {/* Streets: a dense grid plus diagonals */}
        <StreetGrid />

        {/* Secondary roads (lit) */}
        <g opacity="0.55">
          <path d="M 0 540 Q 200 520 400 530 T 1000 510" stroke="#1a3a42" strokeWidth="6" fill="none" />
          <path d="M 0 540 Q 200 520 400 530 T 1000 510" stroke="#3d6e78" strokeWidth="1" fill="none" strokeOpacity="0.7" />
          <path d="M 80 0 Q 100 200 180 320 T 360 600" stroke="#1a3a42" strokeWidth="5" fill="none" />
          <path d="M 80 0 Q 100 200 180 320 T 360 600" stroke="#3d6e78" strokeWidth="1" fill="none" strokeOpacity="0.6" />
          <path d="M 700 600 Q 740 400 820 280 T 990 0" stroke="#1a3a42" strokeWidth="5" fill="none" />
        </g>

        {/* Active route — main road */}
        <g>
          <path d={routePath} stroke="#0e3640" strokeWidth="14" strokeLinecap="round" strokeLinejoin="round" fill="none" />
          <path d={routePath} stroke="#1a5a68" strokeWidth="10" strokeLinecap="round" strokeLinejoin="round" fill="none" />
          {/* glowing trail behind vehicle */}
          <path
            d={routePath}
            stroke="url(#routeGrad)"
            strokeWidth="3"
            strokeLinecap="round"
            strokeLinejoin="round"
            fill="none"
            strokeDasharray={`${t * routeLen} ${routeLen}`}
            filter="url(#glowSoft)"
            opacity="0.95"
          />
          <path
            d={routePath}
            stroke="#6ed1de"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            fill="none"
            strokeDasharray={`${t * routeLen} ${routeLen}`}
          />
        </g>

        {/* Other vehicles (idle) */}
        {[
          { x: 280, y: 470 }, { x: 540, y: 510 }, { x: 740, y: 380 },
          { x: 200, y: 240 }, { x: 880, y: 270 }, { x: 420, y: 130 },
        ].map((p, i) => (
          <g key={i} opacity={(tick + i) % 4 === 0 ? 0.85 : 0.55}>
            <circle cx={p.x} cy={p.y} r="3" fill="#f2c792" />
            <circle cx={p.x} cy={p.y} r="6" fill="none" stroke="#f2c792" strokeOpacity="0.4" />
          </g>
        ))}

        {/* Origin & Destination markers */}
        <Marker x={route[0][0]} y={route[0][1]} label="Origen" kind="origin" />
        <Marker x={route[route.length - 1][0]} y={route[route.length - 1][1]} label="Destino" kind="dest" />

        {/* Active vehicle */}
        <g transform={`translate(${veh.x},${veh.y})`}>
          <circle r="22" fill="#4fb3c4" opacity="0.18">
            <animate attributeName="r" values="22;38;22" dur="2s" repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.25;0;0.25" dur="2s" repeatCount="indefinite" />
          </circle>
          <circle r="11" fill="#4fb3c4" opacity="0.35" />
          <g transform={`rotate(${veh.angle})`}>
            <rect x="-9" y="-6" width="18" height="12" rx="3" fill="#6ed1de" stroke="#0a1f24" strokeWidth="1.2" />
            <rect x="-3" y="-4" width="6" height="8" rx="1" fill="#0a1f24" />
            <circle cx="-6" cy="6" r="1.4" fill="#1a1208" />
            <circle cx="6"  cy="6" r="1.4" fill="#1a1208" />
            <circle cx="-6" cy="-6" r="1.4" fill="#1a1208" />
            <circle cx="6"  cy="-6" r="1.4" fill="#1a1208" />
          </g>
        </g>

        {/* Street labels */}
        <StreetLabels />
      </svg>

      {/* HUD overlay */}
      <div className="navmap-hud">
        <div className="hud-row hud-top">
          <div className="hud-tag">
            <span className="hud-led" />
            <span className="mono">EN VIVO · CDMX</span>
          </div>
          <div className="hud-coords mono">19.4326°N · 99.1332°O</div>
        </div>

        <div className="hud-bottom">
          <div className="hud-info">
            <div>
              <div className="mono hud-info-label">Velocidad</div>
              <div className="display hud-info-val">{Math.round(40 + Math.sin(t * 6.28) * 18 + 25)}<span> km/h</span></div>
            </div>
            <div>
              <div className="mono hud-info-label">ETA</div>
              <div className="display hud-info-val">{Math.max(1, Math.round((1 - t) * 14))}<span> min</span></div>
            </div>
            <div>
              <div className="mono hud-info-label">Distancia</div>
              <div className="display hud-info-val">{((1 - t) * 6.4).toFixed(1)}<span> km</span></div>
            </div>
          </div>

          <div className="hud-feed">
            {feed.slice(0, 3).map((f, i) => (
              <div key={f.id} className={`hud-feed-row k-${f.kind}`} style={{ opacity: 1 - i * 0.22 }}>
                <span className="hud-feed-dot" />
                <span className="hud-feed-t">{f.t}</span>
                <span className="hud-feed-c">{f.city}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <style>{`
        .navmap {
          position: relative;
          aspect-ratio: 5 / 4;
          background: #06161a;
          border: 1px solid var(--line);
          border-radius: var(--radius-xl);
          overflow: hidden;
          box-shadow: var(--shadow-lg);
        }
        .navmap-svg { width: 100%; height: 100%; }
        .navmap-hud {
          position: absolute; inset: 0;
          padding: 18px;
          pointer-events: none;
          display: flex; flex-direction: column;
          justify-content: space-between;
        }
        .hud-row { display: flex; justify-content: space-between; align-items: center; }
        .hud-top { }
        .hud-tag {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 6px 10px;
          background: rgba(7,23,26,0.78);
          border: 1px solid var(--line);
          border-radius: 999px;
          backdrop-filter: blur(8px);
        }
        .hud-led {
          width: 8px; height: 8px; border-radius: 50%;
          background: var(--signal);
          animation: pulse 1.6s infinite;
        }
        .hud-coords {
          color: var(--ink-mute); font-size: 11px;
          padding: 6px 10px;
          background: rgba(7,23,26,0.6);
          border: 1px solid var(--line);
          border-radius: 999px;
          backdrop-filter: blur(8px);
        }
        .hud-bottom {
          display: grid; gap: 12px;
        }
        .hud-info {
          display: grid; grid-template-columns: repeat(3, 1fr);
          gap: 18px;
          padding: 14px 18px;
          background: rgba(7,23,26,0.78);
          border: 1px solid var(--line);
          border-radius: var(--radius-md);
          backdrop-filter: blur(10px);
        }
        .hud-info-label { color: var(--ink-mute); font-size: 9px; }
        .hud-info-val {
          font-size: 24px; font-weight: 600;
          letter-spacing: -0.02em;
          color: var(--ink); margin-top: 2px;
        }
        .hud-info-val span { font-size: 12px; color: var(--ink-mute); font-weight: 400; margin-left: 3px; }
        .hud-feed {
          display: flex; flex-direction: column; gap: 6px;
          padding: 10px 14px;
          background: rgba(7,23,26,0.78);
          border: 1px solid var(--line);
          border-radius: var(--radius-md);
          backdrop-filter: blur(10px);
          font-size: 12px;
          max-width: 360px;
        }
        .hud-feed-row {
          display: grid; grid-template-columns: 10px 1fr auto;
          align-items: center; gap: 10px;
          transition: opacity .4s;
        }
        .hud-feed-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ink-mute); }
        .k-good .hud-feed-dot { background: var(--good); }
        .k-info .hud-feed-dot { background: var(--petrol-bright); }
        .k-alert .hud-feed-dot { background: var(--peach-deep); }
        .k-urgent .hud-feed-dot { background: var(--signal); }
        .hud-feed-t { color: var(--ink); }
        .hud-feed-c { color: var(--ink-mute); font-family: var(--font-mono); font-size: 10px; text-transform: uppercase; }

        @media (max-width: 600px) {
          .navmap-hud { padding: 12px; }
          .hud-coords { display: none; }
          .hud-info { padding: 10px 12px; gap: 10px; }
          .hud-info-val { font-size: 16px; }
          .hud-info-val span { font-size: 9px; }
          .hud-info-label { font-size: 8px; }
          .hud-feed { display: none; }
          .hud-tag { padding: 4px 8px; font-size: 10px; }
        }
      `}</style>
    </div>
  );
}

function CityBlocks() {
  // Static block layout — flat dark polygons for "buildings"
  const blocks = [];
  const seed = (i) => Math.abs(Math.sin(i * 12.9898) * 43758.5453 % 1);
  for (let i = 0; i < 48; i++) {
    const x = (i * 137) % 1000;
    const y = ((i * 89) % 600);
    const w = 30 + seed(i) * 70;
    const h = 30 + seed(i + 7) * 90;
    blocks.push({ x, y, w, h, k: seed(i + 13) });
  }
  return (
    <g opacity="0.7">
      {blocks.map((b, i) => (
        <rect key={i} x={b.x} y={b.y} width={b.w} height={b.h}
          fill={b.k > 0.7 ? '#0c2229' : '#0a1c22'} stroke="#142f37" strokeWidth="0.6" />
      ))}
    </g>
  );
}

function StreetGrid() {
  // dense thin grid of streets
  const lines = [];
  for (let x = 0; x <= 1000; x += 60) {
    lines.push(<line key={`v${x}`} x1={x} y1="0" x2={x + 30} y2="600" stroke="#11343d" strokeWidth="0.6" />);
  }
  for (let y = 0; y <= 600; y += 60) {
    lines.push(<line key={`h${y}`} x1="0" y1={y} x2="1000" y2={y - 12} stroke="#11343d" strokeWidth="0.6" />);
  }
  return <g opacity="0.5">{lines}</g>;
}

function StreetLabels() {
  return (
    <g style={{ fontFamily: 'var(--font-mono)', fontSize: 10, fill: '#5a8088', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
      <text x="220" y="500">Av. Insurgentes</text>
      <text x="500" y="270" transform="rotate(-18 500 270)">Reforma</text>
      <text x="780" y="80">Anillo Periférico</text>
      <text x="120" y="180" transform="rotate(70 120 180)">Eje 1</text>
      <text x="660" y="540">Tlalpan</text>
    </g>
  );
}

function Marker({ x, y, label, kind }) {
  const color = kind === 'origin' ? '#f2c792' : '#58c79e';
  return (
    <g transform={`translate(${x},${y})`}>
      <circle r="9" fill="none" stroke={color} strokeWidth="1.4" opacity="0.7" />
      <circle r="4" fill={color} />
      <g transform="translate(12,4)">
        <rect x="-2" y="-12" width={label.length * 6 + 14} height="16" rx="3" fill="#07171a" stroke={color} strokeOpacity="0.5" />
        <text x="5" y="0" style={{
          fontFamily: 'var(--font-mono)', fontSize: 9, fill: color,
          letterSpacing: '0.12em', textTransform: 'uppercase',
        }}>{label}</text>
      </g>
    </g>
  );
}

/* ============================================================
   B — IsoCity: 2.5D isometric block of city
   ============================================================ */
function IsoCity() {
  const [t, setT] = useState(0);
  const [feed, setFeed] = useState([]);

  useEffect(() => {
    let raf, last = performance.now();
    const loop = (now) => {
      const dt = (now - last) / 1000; last = now;
      setT(v => (v + dt * 0.06) % 1);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  useEffect(() => {
    const events = [
      { t: 'En ruta',           city: 'Bloque 4-A', kind: 'good' },
      { t: 'Geo-cerca',         city: 'Patio Norte', kind: 'info' },
      { t: 'Aceleración',       city: 'Av. Central', kind: 'alert' },
      { t: 'Parada confirmada', city: 'Bloque 7-B', kind: 'good' },
    ];
    let i = 0;
    const id = setInterval(() => {
      setFeed(prev => [{ ...events[i % events.length], id: Math.random() }, ...prev].slice(0, 3));
      i++;
    }, 2400);
    return () => clearInterval(id);
  }, []);

  // iso projection: world (x, y, z) -> screen
  const ISO = (x, y, z = 0) => ({
    sx: 500 + (x - y) * 0.866 * 28,
    sy: 320 + (x + y) * 0.5 * 28 - z * 28,
  });

  // Build a grid of buildings
  const buildings = useMemo(() => {
    const arr = [];
    const hSeed = (a, b) => {
      const v = Math.sin(a * 23.45 + b * 91.7) * 43758.5453;
      return Math.abs(v - Math.floor(v));
    };
    for (let i = -4; i <= 4; i++) {
      for (let j = -4; j <= 4; j++) {
        // Avoid placing buildings on the road tiles (j=0 row, i=0 col)
        if (j === 0 || i === 0) continue;
        const h = 0.6 + hSeed(i, j) * 2.4;
        const accent = hSeed(i, j) > 0.85;
        arr.push({ i, j, h, accent });
      }
    }
    // sort back-to-front for painter's algorithm
    arr.sort((a, b) => (a.i + a.j) - (b.i + b.j));
    return arr;
  }, []);

  // Vehicle path along the cross roads (j=0 then i=0)
  // 0 → 0.5 along j=0 from i=-4 to i=4. 0.5 → 1 along i=0 from j=-4 to j=4
  const vehPos = useMemo(() => {
    if (t < 0.5) {
      const u = t / 0.5;
      const i = -4 + u * 8;
      return { i, j: 0, dir: 'i' };
    } else {
      const u = (t - 0.5) / 0.5;
      const j = -4 + u * 8;
      return { i: 0, j, dir: 'j' };
    }
  }, [t]);

  const vehScreen = ISO(vehPos.i, vehPos.j, 0.05);

  return (
    <div className="iso">
      <svg viewBox="0 0 1000 700" preserveAspectRatio="xMidYMid slice" className="iso-svg">
        <defs>
          <linearGradient id="isoSky" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#0a2128" />
            <stop offset="100%" stopColor="#040b0d" />
          </linearGradient>
          <pattern id="isoDots" width="20" height="20" patternUnits="userSpaceOnUse" patternTransform="rotate(30)">
            <circle cx="10" cy="10" r="0.6" fill="#1f7a8c" opacity="0.3" />
          </pattern>
          <filter id="vehGlow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="3" />
          </filter>
        </defs>

        <rect width="1000" height="700" fill="url(#isoSky)" />
        <rect width="1000" height="700" fill="url(#isoDots)" opacity="0.4" />

        {/* Ground tile under everything */}
        <IsoGround ISO={ISO} />

        {/* Roads (drawn before buildings since lower) */}
        <IsoRoads ISO={ISO} />

        {/* Buildings */}
        {buildings.map((b, idx) => (
          <IsoBuilding key={idx} i={b.i} j={b.j} h={b.h} accent={b.accent} ISO={ISO} />
        ))}

        {/* Route trail */}
        <IsoTrail t={t} ISO={ISO} />

        {/* Vehicle */}
        <g transform={`translate(${vehScreen.sx},${vehScreen.sy})`}>
          <ellipse cx="0" cy="6" rx="22" ry="6" fill="#000" opacity="0.4" />
          <circle r="22" fill="#4fb3c4" opacity="0.2" filter="url(#vehGlow)">
            <animate attributeName="r" values="20;34;20" dur="1.6s" repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.35;0;0.35" dur="1.6s" repeatCount="indefinite" />
          </circle>
          <IsoTruck dir={vehPos.dir} />
        </g>

        {/* Origin / destination markers */}
        <IsoPin pos={ISO(-4, 0, 0)} color="#f2c792" label="Origen" />
        <IsoPin pos={ISO(0, 4, 0)}  color="#58c79e" label="Destino" />

        {/* Idle vehicles dotted around */}
        {[
          { i: 0, j: -3 }, { i: 0, j: 2 }, { i: 3, j: 0 }, { i: -2, j: 0 },
        ].map((p, i) => {
          const s = ISO(p.i, p.j, 0.05);
          return (
            <g key={i} transform={`translate(${s.sx},${s.sy})`} opacity="0.7">
              <circle r="6" fill="#f2c792" opacity="0.25" />
              <circle r="2.5" fill="#f2c792" />
            </g>
          );
        })}
      </svg>

      <div className="iso-hud">
        <div className="hud-row hud-top">
          <div className="hud-tag">
            <span className="hud-led" />
            <span className="mono">VISTA ISO · 3D</span>
          </div>
          <div className="hud-coords mono">SECTOR 04 · ZONA URBANA</div>
        </div>

        <div className="hud-bottom">
          <div className="hud-info">
            <div>
              <div className="mono hud-info-label">Unidad</div>
              <div className="display hud-info-val">MX-2294</div>
            </div>
            <div>
              <div className="mono hud-info-label">Estado</div>
              <div className="display hud-info-val" style={{ color: 'var(--good)' }}>En ruta</div>
            </div>
            <div>
              <div className="mono hud-info-label">Velocidad</div>
              <div className="display hud-info-val">{Math.round(35 + Math.sin(t * 6.28) * 12 + 20)}<span> km/h</span></div>
            </div>
          </div>
          <div className="hud-feed">
            {feed.slice(0, 3).map((f, i) => (
              <div key={f.id} className={`hud-feed-row k-${f.kind}`} style={{ opacity: 1 - i * 0.22 }}>
                <span className="hud-feed-dot" />
                <span className="hud-feed-t">{f.t}</span>
                <span className="hud-feed-c">{f.city}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <style>{`
        .iso {
          position: relative;
          aspect-ratio: 5 / 4;
          background: #04141a;
          border: 1px solid var(--line);
          border-radius: var(--radius-xl);
          overflow: hidden;
          box-shadow: var(--shadow-lg);
        }
        .iso-svg { width: 100%; height: 100%; }
        .iso-hud {
          position: absolute; inset: 0;
          padding: 18px;
          pointer-events: none;
          display: flex; flex-direction: column;
          justify-content: space-between;
        }
      `}</style>
    </div>
  );
}

function IsoGround({ ISO }) {
  const a = ISO(-4.6, -4.6, 0);
  const b = ISO(4.6, -4.6, 0);
  const c = ISO(4.6, 4.6, 0);
  const d = ISO(-4.6, 4.6, 0);
  return (
    <polygon
      points={`${a.sx},${a.sy} ${b.sx},${b.sy} ${c.sx},${c.sy} ${d.sx},${d.sy}`}
      fill="#082028" stroke="#11343d" strokeWidth="1"
    />
  );
}

function IsoRoads({ ISO }) {
  // Cross roads at j=0 and i=0
  const roadStripe = (a1, b1, c1, d1) => (
    <polygon
      points={`${a1.sx},${a1.sy} ${b1.sx},${b1.sy} ${c1.sx},${c1.sy} ${d1.sx},${d1.sy}`}
      fill="#0d2c33" stroke="#1f7a8c" strokeOpacity="0.25" strokeWidth="0.6"
    />
  );
  const horiz = roadStripe(
    ISO(-4.5, -0.4, 0),
    ISO(4.5, -0.4, 0),
    ISO(4.5, 0.4, 0),
    ISO(-4.5, 0.4, 0),
  );
  const vert = roadStripe(
    ISO(-0.4, -4.5, 0),
    ISO(0.4, -4.5, 0),
    ISO(0.4, 4.5, 0),
    ISO(-0.4, 4.5, 0),
  );
  // dashed center lines
  const dashes = [];
  for (let k = -4; k < 4; k += 0.6) {
    const a = ISO(k, 0, 0.01);
    const b = ISO(k + 0.3, 0, 0.01);
    dashes.push(<line key={`dh${k}`} x1={a.sx} y1={a.sy} x2={b.sx} y2={b.sy} stroke="#4fb3c4" strokeOpacity="0.4" strokeWidth="1.4" />);
    const c = ISO(0, k, 0.01);
    const d = ISO(0, k + 0.3, 0.01);
    dashes.push(<line key={`dv${k}`} x1={c.sx} y1={c.sy} x2={d.sx} y2={d.sy} stroke="#4fb3c4" strokeOpacity="0.4" strokeWidth="1.4" />);
  }
  return <g>{horiz}{vert}{dashes}</g>;
}

function IsoBuilding({ i, j, h, accent, ISO }) {
  const sz = 0.42;
  const top    = ISO(i + sz, j + sz, h);
  const topL   = ISO(i - sz, j + sz, h);
  const topR   = ISO(i + sz, j - sz, h);
  const topF   = ISO(i - sz, j - sz, h);
  const botL   = ISO(i - sz, j + sz, 0);
  const botR   = ISO(i + sz, j - sz, 0);
  const botF   = ISO(i - sz, j - sz, 0);

  // Faces
  const left = `${botL.sx},${botL.sy} ${topL.sx},${topL.sy} ${topF.sx},${topF.sy} ${botF.sx},${botF.sy}`;
  const right = `${botR.sx},${botR.sy} ${topR.sx},${topR.sy} ${topF.sx},${topF.sy} ${botF.sx},${botF.sy}`;
  const topFace = `${top.sx},${top.sy} ${topL.sx},${topL.sy} ${topF.sx},${topF.sy} ${topR.sx},${topR.sy}`;

  const baseTop = accent ? '#1f7a8c' : '#143842';
  const baseLeft = accent ? '#13525e' : '#0e2a32';
  const baseRight = accent ? '#0d3a44' : '#0a2026';

  // Window pattern using nested rects on left/right faces (approx via stripes)
  return (
    <g>
      <polygon points={right} fill={baseRight} />
      <polygon points={left}  fill={baseLeft} />
      <polygon points={topFace} fill={baseTop} />
      {/* simple window stripes — small dashed lines along the face */}
      <WindowStripes face="left" botL={botL} topL={topL} topF={topF} botF={botF} accent={accent} />
      <WindowStripes face="right" botR={botR} topR={topR} topF={topF} botF={botF} accent={accent} />
    </g>
  );
}

function WindowStripes({ face, botL, topL, topR, botR, topF, botF, accent }) {
  const stripes = [];
  const steps = 3;
  for (let k = 1; k <= steps; k++) {
    const f = k / (steps + 1);
    if (face === 'left') {
      const a = { x: botL.sx + (topL.sx - botL.sx) * f, y: botL.sy + (topL.sy - botL.sy) * f };
      const b = { x: botF.sx + (topF.sx - botF.sx) * f, y: botF.sy + (topF.sy - botF.sy) * f };
      stripes.push(<line key={`l${k}`} x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke={accent ? '#f2c792' : '#1a4651'} strokeWidth="0.6" strokeOpacity={accent ? 0.7 : 0.5} strokeDasharray="1.8 1.4" />);
    } else if (face === 'right') {
      const a = { x: botR.sx + (topR.sx - botR.sx) * f, y: botR.sy + (topR.sy - botR.sy) * f };
      const b = { x: botF.sx + (topF.sx - botF.sx) * f, y: botF.sy + (topF.sy - botF.sy) * f };
      stripes.push(<line key={`r${k}`} x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke={accent ? '#f2c792' : '#1a4651'} strokeWidth="0.6" strokeOpacity={accent ? 0.5 : 0.4} strokeDasharray="1.8 1.4" />);
    }
  }
  return <g>{stripes}</g>;
}

function IsoTrail({ t, ISO }) {
  // Trail is along the path the truck has already traveled
  const segs = [];
  const N = 60;
  for (let k = 0; k < N; k++) {
    const tt = (k / N) * t;
    let i, j;
    if (tt < 0.5) { i = -4 + (tt / 0.5) * 8; j = 0; }
    else { i = 0; j = -4 + ((tt - 0.5) / 0.5) * 8; }
    const s = ISO(i, j, 0.02);
    segs.push(s);
  }
  if (segs.length < 2) return null;
  const path = 'M ' + segs.map(s => `${s.sx} ${s.sy}`).join(' L ');
  return (
    <g>
      <path d={path} stroke="#6ed1de" strokeWidth="3" fill="none" strokeOpacity="0.25" strokeLinecap="round" />
      <path d={path} stroke="#f2c792" strokeWidth="1.2" fill="none" strokeOpacity="0.9" strokeLinecap="round" />
    </g>
  );
}

function IsoTruck({ dir }) {
  // Simple isometric truck/pickup
  // dir 'i' means truck moves along i axis; rotate body accordingly
  return (
    <g transform={dir === 'i' ? '' : 'scale(-1,1)'}>
      {/* cab */}
      <polygon points="-2,-12 8,-8 8,-2 -2,-6" fill="#f2c792" />
      <polygon points="-2,-12 -2,-6 -10,-2 -10,-8" fill="#e8b576" />
      <polygon points="-2,-12 8,-8 -10,-8" fill="#fadfb5" />
      {/* bed */}
      <polygon points="8,-2 8,4 -10,8 -10,2" fill="#1f7a8c" />
      <polygon points="-2,-6 -2,0 -10,2 -10,-2" fill="#13525e" />
      {/* shadow bottom edge */}
      <polygon points="-10,8 8,4 -2,4 -10,2" fill="#000" opacity="0.2" />
    </g>
  );
}

function IsoPin({ pos, color, label }) {
  return (
    <g transform={`translate(${pos.sx},${pos.sy})`}>
      <ellipse cx="0" cy="2" rx="14" ry="4" fill="#000" opacity="0.4" />
      <line x1="0" y1="0" x2="0" y2="-26" stroke={color} strokeWidth="1.5" />
      <circle cx="0" cy="-30" r="6" fill={color} stroke="#07171a" strokeWidth="1.4" />
      <g transform="translate(10,-30)">
        <rect x="-2" y="-9" width={label.length * 6 + 14} height="14" rx="3" fill="rgba(7,23,26,0.85)" stroke={color} strokeOpacity="0.5" />
        <text x="5" y="1" style={{
          fontFamily: 'var(--font-mono)', fontSize: 9, fill: color,
          letterSpacing: '0.12em', textTransform: 'uppercase',
        }}>{label}</text>
      </g>
    </g>
  );
}

window.Hero = Hero;
