/* ============================================================
   RouteMap — mapa aéreo estilizado com carrinho animado
   percorrendo a rota recomendada (BR-277 → PR-180 → Chácara).
   ============================================================ */
const { useState: useStateRM, useEffect: useEffectRM, useRef: useRefRM } = React;

/* Pontos de virada da rota recomendada (coords no viewBox 1000x720) */
const RM_WAYPOINTS = [
  { x: 95, y: 72 },   // 0 Trevo das Cataratas (saída)
  { x: 592, y: 316 }, // 1 entra na PR-180 (ao lado da PRF)
  { x: 548, y: 584 }, // 2 vira à esquerda (após Cantinho Caseiro)
  { x: 716, y: 608 }, // 3 vira à esquerda de novo
  { x: 770, y: 486 }, // 4 chácara
];

/* path da rota correta: BR-277 reta → entra na PR-180 → passa Cantinho Caseiro
   → esquerda (reto na estrada rural) → esquerda → reto até a chácara (gancho em C) */
const RM_ROUTE_D =
  "M95,72 L560,286 Q592,300 586,332 L560,440 L548,560 Q546,584 568,594 L700,606 Q718,610 720,586 L756,500 L770,486";

/* BR-277 que CONTINUA após o trevo (não seguir reto) */
const RM_277_CONT_D = "M592,300 L724,314 L884,320";

/* atalho de terra (NÃO usar) — sai da BR-277 depois do trevo, chega pelo leste */
const RM_BAD_D = "M712,316 L788,410 L808,498 L780,492";

function RouteMap() {
  const wrapRef = useRefRM(null);
  const routeRef = useRefRM(null);
  const trailRef = useRefRM(null);
  const carRef = useRefRM(null);
  const [step, setStep] = useStateRM(0);
  const [playing, setPlaying] = useStateRM(false);
  const stateRef = useRefRM({ raf: 0, fracs: [], len: 0, start: 0, stepIdx: -1 });

  /* mede a rota e as frações de comprimento de cada waypoint */
  useEffectRM(() => {
    const path = routeRef.current;
    if (!path) return;
    const len = path.getTotalLength();
    const N = 700;
    const samples = [];
    for (let i = 0; i <= N; i++) {
      const p = path.getPointAtLength((i / N) * len);
      samples.push(p);
    }
    const fracs = RM_WAYPOINTS.map((w) => {
      let best = 0,
        bd = Infinity;
      for (let i = 0; i <= N; i++) {
        const dx = samples[i].x - w.x,
          dy = samples[i].y - w.y;
        const d = dx * dx + dy * dy;
        if (d < bd) {
          bd = d;
          best = i;
        }
      }
      return best / N;
    });
    fracs[0] = 0;
    fracs[fracs.length - 1] = 1;
    stateRef.current.fracs = fracs;
    stateRef.current.len = len;
    if (trailRef.current) {
      trailRef.current.style.strokeDasharray = len;
      trailRef.current.style.strokeDashoffset = len;
    }
    placeCar(0);
  }, []);

  function placeCar(t) {
    const path = routeRef.current,
      car = carRef.current;
    if (!path || !car) return;
    const len = stateRef.current.len || path.getTotalLength();
    const p = path.getPointAtLength(t * len);
    const ahead = path.getPointAtLength(Math.min(len, t * len + 6));
    const ang = (Math.atan2(ahead.y - p.y, ahead.x - p.x) * 180) / Math.PI;
    car.setAttribute("transform", `translate(${p.x},${p.y}) rotate(${ang})`);
    if (trailRef.current) trailRef.current.style.strokeDashoffset = len * (1 - t);
  }

  function frame(now) {
    const st = stateRef.current;
    if (!st.start) st.start = now;
    const DUR = 8200;
    let t = (now - st.start) / DUR;
    if (t > 1) t = 1;
    placeCar(t);
    // passo ativo
    let idx = 0;
    for (let i = 0; i < st.fracs.length; i++) if (t >= st.fracs[i] - 0.001) idx = i;
    if (idx !== st.stepIdx) {
      st.stepIdx = idx;
      setStep(idx);
    }
    if (t < 1) {
      st.raf = requestAnimationFrame(frame);
    } else {
      // pausa e repete
      st.raf = setTimeout(() => {
        st.start = 0;
        st.stepIdx = -1;
        st.raf = requestAnimationFrame(frame);
      }, 1600);
    }
  }

  function start() {
    const st = stateRef.current;
    cancelAnimationFrame(st.raf);
    clearTimeout(st.raf);
    st.start = 0;
    st.stepIdx = -1;
    setPlaying(true);
    st.raf = requestAnimationFrame(frame);
  }

  /* autoplay ao entrar na viewport */
  useEffectRM(() => {
    const el = wrapRef.current;
    if (!el) return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) {
      placeCar(1);
      setStep(RM_WAYPOINTS.length - 1);
      return;
    }
    const io = new IntersectionObserver(
      (es) => {
        if (es[0].isIntersecting) {
          start();
          io.disconnect();
        }
      },
      { threshold: 0.35 }
    );
    io.observe(el);
    return () => {
      io.disconnect();
      cancelAnimationFrame(stateRef.current.raf);
      clearTimeout(stateRef.current.raf);
    };
  }, []);

  const markerColor = (i) => (i <= step ? "#c2a15a" : "#ffffff");

  return (
   <div className="rm-wrap">
    <div ref={wrapRef} className="rm-frame">
      <div className="rm-sky"></div>
      <div className="rm-tilt">
        <svg viewBox="0 0 1000 720" className="rm-svg" preserveAspectRatio="xMidYMid slice">
          <defs>
            <linearGradient id="rmGround" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="#e7eed8" />
              <stop offset="1" stopColor="#d4e0c0" />
            </linearGradient>
            <filter id="rmShadow" x="-40%" y="-40%" width="180%" height="180%">
              <feDropShadow dx="0" dy="3" stdDeviation="3" floodColor="#11331f" floodOpacity="0.28" />
            </filter>
          </defs>

          {/* terreno */}
          <rect x="0" y="0" width="1000" height="720" fill="url(#rmGround)" />

          {/* manchas de mata */}
          {[
            [150, 520, 90, 60], [250, 640, 120, 70], [820, 200, 110, 80],
            [905, 430, 80, 70], [470, 640, 120, 65], [760, 470, 80, 55],
            [180, 360, 70, 48], [70, 470, 80, 60], [430, 360, 60, 44],
          ].map((b, i) => (
            <ellipse key={i} cx={b[0]} cy={b[1]} rx={b[2]} ry={b[3]} fill="#bcd0a3" opacity="0.7" />
          ))}

          {/* Rio São Salvador */}
          <path d="M300,300 C322,400 282,470 305,560 C322,628 300,672 322,712" fill="none" stroke="#bcd4e6" strokeWidth="9" strokeLinecap="round" opacity="0.85" />
          <text x="288" y="500" fontSize="13" fill="#8fa6b8" fontFamily="Hanken Grotesk" transform="rotate(-80 288 500)">Rio São Salvador</text>

          {/* malha urbana (Cascavel) topo-esquerda */}
          {[0, 1, 2].map((r) =>
            [0, 1, 2].map((c) => (
              <rect key={r + "-" + c} x={18 + c * 30} y={30 + r * 26} width="22" height="18" rx="3" fill="#cfcabd" opacity="0.7" />
            ))
          )}

          {/* rede viária base (vias reais em branco) */}
          {/* BR-277 reta */}
          <path d="M95,72 L592,300 L884,320" fill="none" stroke="#ffffff" strokeWidth="14" strokeLinecap="round" opacity="0.95" />
          {/* PR-180 e estrada rural (sob a rota) */}
          <path d={RM_ROUTE_D} fill="none" stroke="#ffffff" strokeWidth="11" strokeLinecap="round" strokeLinejoin="round" opacity="0.9" />
          {/* ramais menores */}
          <path d="M740,576 L900,600 M560,470 L450,500" fill="none" stroke="#ffffff" strokeWidth="6" strokeLinecap="round" opacity="0.55" />

          {/* Autódromo (landmark) */}
          <g opacity="0.9">
            <ellipse cx="300" cy="250" rx="44" ry="28" fill="none" stroke="#9bb083" strokeWidth="6" />
            <circle cx="300" cy="250" r="5" fill="#7fae5a" />
          </g>
          <text x="300" y="300" fontSize="12.5" textAnchor="middle" fill="#7a8a66" fontFamily="Hanken Grotesk">Autódromo</text>

          {/* BR-277 que CONTINUA (não seguir reto) */}
          <path d={RM_277_CONT_D} fill="none" stroke="#9aa6b8" strokeWidth="4" strokeLinecap="round" strokeDasharray="10 7" opacity="0.8" />
          <text x="892" y="320" fontSize="13" fill="#8a93a3" fontFamily="Hanken Grotesk">Centralito →</text>

          {/* atalho de terra — NÃO usar (sai da BR-277 depois do trevo) */}
          <path d={RM_BAD_D} fill="none" stroke="#d4584a" strokeWidth="6" strokeLinecap="round" strokeDasharray="2 12" opacity="0.95" />
          <g transform="translate(800,452)">
            <circle r="15" fill="#d4584a" filter="url(#rmShadow)" />
            <path d="M-6,-6 L6,6 M6,-6 L-6,6" stroke="#fff" strokeWidth="3" strokeLinecap="round" />
          </g>
          <text x="690" y="408" fontSize="12.5" fontWeight="600" fill="#c0473b" fontFamily="Hanken Grotesk">Estrada de terra</text>

          {/* rota recomendada — base + trilha revelada */}
          <path ref={routeRef} d={RM_ROUTE_D} fill="none" stroke="#1c5b39" strokeWidth="9" strokeLinecap="round" strokeLinejoin="round" opacity="0.26" />
          <path ref={trailRef} d={RM_ROUTE_D} fill="none" stroke="#1c5b39" strokeWidth="9" strokeLinecap="round" strokeLinejoin="round" />

          {/* PRF + trevo de acesso à PR-180 */}
          <g transform="translate(548,284)" filter="url(#rmShadow)">
            <rect x="-15" y="-15" width="30" height="30" rx="6" fill="#2d63b8" />
            <text x="0" y="5" textAnchor="middle" fontSize="12" fontWeight="700" fill="#fff" fontFamily="Hanken Grotesk">PRF</text>
          </g>
          <text x="548" y="262" textAnchor="middle" fontSize="12.5" fontWeight="600" fill="#3a5078" fontFamily="Hanken Grotesk">Polícia Rodoviária</text>
          <text x="630" y="296" fontSize="11.5" fill="#7a8a66" fontFamily="Hanken Grotesk">Trevo acesso PR-180</text>

          {/* Cantinho Caseiro (referência na PR-180) */}
          <circle cx="560" cy="440" r="6" fill="#fff" stroke="#6b7464" strokeWidth="3" />
          <text x="540" y="436" textAnchor="end" fontSize="12.5" fontWeight="600" fill="#5b6450" fontFamily="Hanken Grotesk">Cantinho Caseiro</text>

          {/* São Domingos */}
          <circle cx="628" cy="652" r="5" fill="#9a8f80" />
          <text x="628" y="676" textAnchor="middle" fontSize="12.5" fill="#6b7464" fontFamily="Hanken Grotesk">São Domingos</text>

          {/* marcadores de virada */}
          {RM_WAYPOINTS.map((w, i) => {
            if (i === RM_WAYPOINTS.length - 1) return null;
            const active = i <= step;
            return (
              <g key={i} transform={`translate(${w.x},${w.y})`} filter="url(#rmShadow)">
                <circle r="15" fill={i === 0 ? "#11331f" : active ? "#c2a15a" : "#ffffff"} stroke="#11331f" strokeWidth="2.5" />
                <text x="0" y="5" textAnchor="middle" fontSize="16" fontWeight="700" fill={i === 0 ? "#e0c98c" : active ? "#11331f" : "#1c5b39"} fontFamily="Hanken Grotesk, sans-serif">
                  {i + 1}
                </text>
              </g>
            );
          })}

          {/* pino da chácara */}
          <g transform={`translate(${RM_WAYPOINTS[4].x},${RM_WAYPOINTS[4].y})`} filter="url(#rmShadow)">
            <path d="M0,4 C-16,-14 -16,-34 0,-34 C16,-34 16,-14 0,4 Z" fill={step >= 4 ? "#c2a15a" : "#1c5b39"} stroke="#11331f" strokeWidth="2" />
            <circle cx="0" cy="-22" r="7" fill="#fff" />
          </g>
          <text x="790" y="488" fontSize="13" fontWeight="600" fill="#1c5b39" fontFamily="Hanken Grotesk">Chácara</text>

          {/* carrinho */}
          <g ref={carRef} filter="url(#rmShadow)">
            <g>
              <rect x="-19" y="-11" width="38" height="22" rx="7" fill="#fbfaf6" stroke="#11331f" strokeWidth="1.5" />
              <rect x="-3" y="-9" width="15" height="18" rx="4" fill="#1c5b39" />
              <rect x="-13" y="-8" width="8" height="16" rx="3" fill="#cdd8e6" />
              <circle cx="16" cy="-7" r="2.4" fill="#e0c98c" />
              <circle cx="16" cy="7" r="2.4" fill="#e0c98c" />
            </g>
          </g>

          {/* rótulos de rodovia */}
          <text x="300" y="172" fontSize="17" fontWeight="700" fill="#6f8060" fontFamily="Hanken Grotesk" transform="rotate(24 300 172)">BR-277</text>
          <text x="492" y="506" fontSize="16" fontWeight="700" fill="#6f8060" fontFamily="Hanken Grotesk">PR-180</text>
          <text x="95" y="56" fontSize="12.5" fontWeight="600" fill="#6b7464" fontFamily="Hanken Grotesk">Trevo Cataratas</text>
        </svg>
      </div>

      {/* legenda flutuante */}
      <div className="rm-legend">
        <span className="rm-leg-item"><span className="rm-dot rm-dot-good"></span> Rota recomendada</span>
        <span className="rm-leg-item"><span className="rm-dot rm-dot-bad"></span> Atalho de terra — não use</span>
      </div>
    </div>

    {/* caption do passo atual — ABAIXO do mapa (não tapa o carrinho) */}
    <div className="rm-caption">
      <span className="rm-step-num">{step === LV.rota.passos.length - 1 ? "★" : step + 1}</span>
      <span className="rm-step-txt">
        <strong>{LV.rota.passos[step].t}</strong>
        {LV.rota.passos[step].d}
      </span>
      <button className="rm-replay" onClick={start} aria-label="Refazer o trajeto">
        {playing ? "↻" : "▶"}
      </button>
    </div>
   </div>
  );
}

window.RouteMap = RouteMap;
