/* global React */
// ============================================================
// SPEI Routes — animated "global reach at a glance" visual.
// Origin (México) → flowing animated route → destination card
// that cycles through real cities with their country flags.
// Plus a marquee strip of destination flags underneath.
// Flags are served from flagcdn.com (crisp PNGs by ISO code).
// ============================================================
const { useState, useEffect, useRef } = React;

const SR_DESTS = [
  { code: "gb", city: "Londres",   country: "Reino Unido" },
  { code: "us", city: "Nueva York", country: "Estados Unidos" },
  { code: "es", city: "Madrid",    country: "España" },
  { code: "sg", city: "Singapur",  country: "Singapur" },
  { code: "jp", city: "Tokio",     country: "Japón" },
  { code: "ae", city: "Dubái",     country: "E. Á. Unidos" },
  { code: "br", city: "São Paulo", country: "Brasil" },
  { code: "au", city: "Sídney",    country: "Australia" },
];

// Strip of flags for the reach marquee (origin + destinations)
const SR_STRIP = ["mx","gb","us","es","sg","jp","ae","br","au","de","ca","cn","in","cl","co"];

function Flag({ code, w = 44 }) {
  return (
    <img
      className="sr-flag"
      src={`https://flagcdn.com/w80/${code}.png`}
      srcSet={`https://flagcdn.com/w160/${code}.png 2x`}
      width={w}
      height={Math.round(w * 0.66)}
      alt=""
      loading="lazy"
      draggable="false"
    />
  );
}

function DestItem({ dest, cls }) {
  return (
    <div className={`sr-rotor-item ${cls}`}>
      <Flag code={dest.code} />
      <div className="sr-meta">
        <span className="sr-cap">{dest.country}</span>
        <span className="sr-city">{dest.city}</span>
      </div>
    </div>
  );
}

function SpeiRoutes() {
  const [i, setI] = useState(0);
  const [exiting, setExiting] = useState(null);
  const prevRef = useRef(0);

  useEffect(() => {
    const id = setInterval(() => setI((p) => (p + 1) % SR_DESTS.length), 3400);
    return () => clearInterval(id);
  }, []);

  // When the index changes, keep the previous item mounted briefly so it
  // can animate OUT (downward) while the new one animates IN (from above).
  useEffect(() => {
    const old = prevRef.current;
    if (old === i) return;
    setExiting(old);
    prevRef.current = i;
    const t = setTimeout(() => setExiting(null), 680);
    return () => clearTimeout(t);
  }, [i]);

  const d = SR_DESTS[i];
  const ex = exiting !== null && exiting !== i ? SR_DESTS[exiting] : null;

  return (
    <div className="spei-routes">
      <div className="sr-track">
        {/* Origin */}
        <div className="sr-endpoint sr-origin">
          <Flag code="mx" />
          <div className="sr-meta">
            <span className="sr-cap">Origen</span>
            <span className="sr-city">México</span>
          </div>
        </div>

        {/* Flowing route line */}
        <div className="sr-line" aria-hidden="true">
          <svg viewBox="0 0 200 40" preserveAspectRatio="none">
            <path className="sr-path-base" d="M2 20 H198" />
            <path className="sr-path-flow" d="M2 20 H198" />
          </svg>
          <span className="sr-comet" />
        </div>

        {/* Destination — content rotates vertically inside a fixed window */}
        <div className="sr-endpoint sr-dest">
          <div className="sr-rotor">
            <DestItem key={i} dest={d} cls="sr-rotor-in" />
            {ex && <DestItem key={`ex-${exiting}`} dest={ex} cls="sr-rotor-out" />}
          </div>
        </div>
      </div>

      {/* Reach marquee */}
      <div className="sr-strip" aria-hidden="true">
        <div className="sr-strip-row">
          {SR_STRIP.concat(SR_STRIP).map((c, idx) => (
            <Flag key={idx} code={c} w={30} />
          ))}
        </div>
      </div>

      <p className="sr-foot">
        <strong>+70 países</strong><Fn n={3}/> · Mismo día<Fn n={1}/> · Sin comisiones ocultas<Fn n={2}/>
      </p>
    </div>
  );
}

window.SpeiRoutes = SpeiRoutes;
