/* global React, L, SHead, CD, ICONS */
const { useState: bS, useEffect: bE, useRef: bR, useMemo: bM } = React;

/* ===== PALMARÉS accordion ===== */
function Palmares({ lang }) {
  const t = L.t[lang];
  const [open, setOpen] = bS(() => new Set([0]));
  const toggle = (i) => setOpen((prev) => {
    const n = new Set(prev);
    n.has(i) ? n.delete(i) : n.add(i);
    return n;
  });
  const MD = { gold: ["g", "●"], silver: ["s", "●"], bronze: ["b", "●"] };
  const counts = (items) => {
    const c = { gold: 0, silver: 0, bronze: 0 };
    items.forEach((it) => { if (it.medal) c[it.medal]++; });
    return c;
  };
  return (
    <section className="sec" id="palmares">
      <div className="wrap">
        <SHead n={t.palNum} title={t.palTitle} sub={t.palSub} />
        <div className="acc" data-rv>
          {L.palmares.map((y, i) => {
            const c = counts(y.items);
            const isOpen = open.has(i);
            return (
              <div className={`acc-i${isOpen ? " open" : ""}`} key={y.year}>
                <button className="acc-h" onClick={() => toggle(i)} aria-expanded={isOpen}>
                  <span className="acc-y">{y.year}</span>
                  <span className="acc-l" />
                  <span className="acc-c">
                    {c.gold ? <span className="mchip g">● {c.gold}</span> : null}
                    {c.silver ? <span className="mchip s">● {c.silver}</span> : null}
                    {c.bronze ? <span className="mchip b">● {c.bronze}</span> : null}
                    <span className="mchip">{y.items.length}</span>
                  </span>
                  <span className="acc-x">+</span>
                </button>
                <div className="acc-p">
                  <ul className="acc-list">
                    {y.items.map((it, j) => {
                      const m = it.medal ? MD[it.medal] : null;
                      return (
                        <li key={j} className={it.medal === "gold" ? "gold" : ""}>
                          <span className={`md ${m ? m[0] : "n"}`}>{m ? m[1] : "◇"}</span>
                          <span>{it[lang]}</span>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </div>
            );
          })}
        </div>
        <div className="hint">{t.palHint}</div>
      </div>
    </section>
  );
}

/* ===== MAP (Leaflet) ===== */
function RaceMap({ lang, nextIdx = 0 }) {
  const ref = bR(null);
  const mapRef = bR(null);
  bE(() => {
    if (!ref.current || mapRef.current || !window.L_LEAFLET) return;
    const LF = window.L_LEAFLET;
    const map = LF.map(ref.current, {
      center: [46, 5], zoom: 4, scrollWheelZoom: false, zoomControl: true, attributionControl: true
    });
    mapRef.current = map;
    LF.tileLayer("https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png", {
      attribution: '&copy; OpenStreetMap &copy; CARTO', maxZoom: 12, subdomains: "abcd"
    }).addTo(map);

    const pin = (color) => LF.divIcon({
      className: "lh-pin",
      html: `<i style="background:${color}"></i>`,
      iconSize: [18, 18], iconAnchor: [9, 9]
    });
    const bounds = [];
    L.upcoming.forEach((u, i) => {
      const color = new Date(u.start).getTime() < Date.now() ? "#5B7C9E" : (i === nextIdx ? "#FF6B35" : "#0066FF");
      const m = LF.marker([u.lat, u.lon], { icon: pin(color) }).addTo(map);
      m.bindPopup(`<div class="lh-pop"><b>${u.event[lang]}</b><span>${u.city[lang]}<br>${u.dates[lang]}</span></div>`);
      bounds.push([u.lat, u.lon]);
    });
    // home base
    const home = LF.marker([38.34, -0.48], { icon: pin("#FFB531") }).addTo(map);
    home.bindPopup(`<div class="lh-pop"><b>${lang === "es" ? "Base" : "Base"}</b><span>Alicante, ESP</span></div>`);
    bounds.push([38.34, -0.48]);
    map.fitBounds(bounds, { padding: [46, 46] });
    setTimeout(() => map.invalidateSize(), 260);
    return () => { map.remove(); mapRef.current = null; };
  }, [lang, nextIdx]);
  return <div id="lhmap" ref={ref} role="img" aria-label={lang === "es" ? "Mapa de próximas regatas" : "Map of upcoming events"} />;
}

/* ===== UPCOMING ===== */
function Upcoming({ lang }) {
  const t = L.t[lang];
  const nextIdx = bM(() => {
    const now = Date.now();
    const i = L.upcoming.findIndex((u) => new Date(u.start).getTime() >= now);
    return i === -1 ? L.upcoming.length - 1 : i;
  }, []);
  return (
    <section className="sec sec-alt diag-tb" id="proximas">
      <div className="wrap">
        <SHead n={t.upNum} title={t.upTitle} sub={t.upSub} />
        <div className="up" data-rv="s">
          {L.upcoming.map((u, i) => {
            const past = new Date(u.start).getTime() < Date.now();
            const isNext = i === nextIdx;
            return (
              <article className={`upc ${isNext ? "a" : "b"}${past ? " past" : ""}`} key={u.id} style={{ "--d": `${i * 130}ms` }}>
                {isNext ? <span className="upc-tag">{lang === "es" ? "Próxima" : "Next up"}</span> : null}
                {past ? <span className="upc-tag done">{lang === "es" ? "Disputada" : "Completed"}</span> : null}
                <div className="upc-m">{u.month[lang]}</div>
                <h3>{u.event[lang]}</h3>
                <div className="upc-rows">
                  <div className="upc-r"><i aria-hidden="true">◷</i><span>{u.dates[lang]}</span></div>
                  <div className="upc-r"><span className="ccode">{u.code}</span><span>{u.city[lang]}</span></div>
                  <div className="upc-r"><i aria-hidden="true">◆</i><span>ILCA 6 {lang === "es" ? "Femenino" : "Women"}</span></div>
                </div>
                {past
                  ? <div className="upc-cd"><div className="upc-cd-l">{lang === "es" ? "Estado" : "Status"}</div><div className="upc-done">{lang === "es" ? "Regata disputada" : "Event completed"}</div></div>
                  : <CD iso={u.start} lbl={t.countdown} t={t} />}
                <a href="#contacto" className={`btn ${isNext ? "btn-p" : "btn-o"}`}>{past ? (lang === "es" ? "Ver resultados" : "See results") : u.cta[lang]} →</a>
              </article>
            );
          })}
        </div>
        <div className="mapblk" data-rv>
          <div className="map-h">
            <h3>{t.mapTitle}</h3>
            <div className="map-legend">
              <span><i style={{ background: "#FFB531" }} />{lang === "es" ? "Base" : "Base"}</span>
              <span><i style={{ background: "#FF6B35" }} />{lang === "es" ? "Próxima regata" : "Next event"}</span>
            </div>
          </div>
          <RaceMap lang={lang} nextIdx={nextIdx} />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Palmares, Upcoming, RaceMap });
