/* global React, L, Ornaments */
const { useState, useEffect, useRef, useMemo } = React;
const { Leaf, Sprig, Flower, Butterfly, Bee, Squiggle, Branch, Illus, openLightbox } = Ornaments;

/* ───────────────────────────  NOS ACTIONS  ─────────────────────────── */
const NosActions = () => {
  const actions2024 = [
    "Vignoble partagé de la Bellangerais avec Rennes Jardin pour la Ville de Rennes",
    "Aménagement du Parc du Bonheur de Maurepas pour la Ville de Rennes",
    "Ciné-débat dans le cadre du festival Alimenterre, en partenariat avec la MJC Bréquigny et Aubépine",
    "78 animations organisées dans les jardins partagés de la Ville, ayant rassemblé 433 participant·e·s",
    "Observer, Cueillir, Cuisiner : projet biodiversité, jardinage et cuisine, en partenariat avec Aux Goûts du Jour et Les Cols Verts",
    "Brico à Brac, un événement festif organisé du côté du Hangar, en partenariat avec Comme un établi",
    "Accueil de la SAESAT Maffrais Service de Thorigné-Foulard une à deux fois par mois",
  ];
  const extras = "Plus d'événements : peinture, fabrication de farine et de pain dans le four à bois, programme Twiste de culture de plantes mellifères, fabrication de plantes médicinales à partir des plantes du jardin, etc.";

  const actions2026 = [
    "Programme Pair – culture de graines",
    "(autres projets 2026 à venir)",
  ];

  return (
    <section id="actions" data-screen-label="05 Actions" className="bg-white">
      {/* PINK BANNER */}
      <div className="banner bg-pink-vp relative overflow-hidden">
        <div className="absolute pointer-events-none" style={{ top: 18, right: 30, opacity: 0.4 }}>
          <Sprig color="white" size={90} rotate={20} />
        </div>
        <div className="absolute pointer-events-none" style={{ bottom: 14, left: 40, opacity: 0.5 }}>
          <Flower color="white" size={50} fillCenter="white" />
        </div>
        <h2>NOS ACTIONS</h2>
      </div>

      <div className="max-w-6xl mx-auto px-6 py-16">
        <div className="text-center mb-12">
          <p className="font-bold text-lg">
            En 2024 et 2025, plusieurs projets ont été accompagnés&nbsp;:
          </p>
          <div className="flex justify-center mt-3"><Squiggle color="#84BF9E" w={100} /></div>
        </div>

        {/* Actions list */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          {actions2024.map((a, i) => (
            <div key={i} className="flex gap-3 vp-card-soft p-5 hover-lift bg-sand-soft">
              <Leaf color="#7a8246" size={26} rotate={i % 2 === 0 ? -20 : 20} strokeWidth={1.8} style={{ flexShrink: 0 }} />
              <p className="text-[15px] leading-relaxed">{a}</p>
            </div>
          ))}
        </div>

        <div className="mt-6 vp-card-soft p-6 bg-sand flex gap-4 items-start">
          <span className="text-coral text-2xl">✨</span>
          <p className="text-[14px] italic leading-relaxed text-gray-700">{extras}</p>
        </div>

        {/* 2026 */}
        <div className="mt-16">
          <div className="flex items-center gap-4 mb-6">
            <span className="font-script text-pink-vp text-4xl">Et ça continue en 2026&nbsp;:</span>
            <div className="flex-1 h-px bg-sand" />
            <span className="bg-lime-vp text-olive font-brush text-2xl px-4 py-1 rounded-full">2026</span>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
            {actions2026.map((a, i) => (
              <div key={i} className={`vp-card-soft p-5 flex gap-3 hover-lift ${i === 1 ? "bg-white border-2 border-dashed border-sand" : "bg-white"}`}>
                <Flower color="#F27D52" size={28} fillCenter="#F2527D" strokeWidth={1.8} style={{ flexShrink: 0 }} />
                <p className={`text-[15px] leading-relaxed ${i === 1 ? "italic text-gray-500" : ""}`}>{a}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

/* ─────────────────────────  CHIFFRES CLÉS  ───────────────────────── */
const ChiffresCles = () => (
  <section id="chiffres" data-screen-label="03 Chiffres" className="bg-white pt-8 pb-16 relative overflow-hidden">
    {/* Illustrations charte : romarin (x2, #84BF9E) sur les bords, escargot (#F2527D) */}
    <div className="absolute pointer-events-none mobile-illus-hide" style={{ top: 0, bottom: 0, left: 0, display: "flex", alignItems: "center", zIndex: 0 }}>
      <Illus src="images/illus/romarin-bleu.png" size={820} opacity={0.85} tint="#84BF9E" style={{ transform: "translateX(-42%) rotate(45deg)" }} />
    </div>
    <div className="absolute pointer-events-none mobile-illus-hide" style={{ top: 0, bottom: 0, right: 0, display: "flex", alignItems: "center", zIndex: 0 }}>
      <Illus src="images/illus/romarin-bleu.png" size={820} opacity={0.85} tint="#84BF9E" style={{ transform: "scaleX(-1) translateX(-42%) rotate(45deg)" }} />
    </div>

    <div className="max-w-6xl mx-auto px-6 relative">
      <div className="text-center mb-10">
        <span className="font-script text-pink-vp" style={{ fontSize: "clamp(34px, 9vw, 48px)", lineHeight: 1 }}>Vilaine Pousse en chiffres</span>
        <div className="flex justify-center mt-2">
          <Illus src="images/illus/escargot-rose.png" size={72} opacity={0.9} tint="#F2527D" />
        </div>
        <p className="text-gray-700 mt-3 max-w-2xl mx-auto">
          Nous semons, animons et faisons germer le collectif aux quatre coins de Rennes et sa métropole.
        </p>
        <p className="font-script text-olive mt-4" style={{ fontSize: 26, lineHeight: 1 }}>
          Entre 2024 et 2025
        </p>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <StatCard num="193" label="animations organisées" sub="dans les jardins partagés" tone="sage" img="images/chiffre-1.jpg" />
        <StatCard num="1167" label="personnes rassemblées" sub="" tone="coral" img="images/chiffre-2.jpg" />
        <StatCard num="43" label="jardins accompagnés" sub="" tone="lime" img="images/chiffre-3.jpg" />
      </div>
    </div>
  </section>
);

/* ──────────────────────  GALERIE PHOTOS (bandeau défilant)  ────────────────────── */
const GALLERY_PHOTOS = Array.from(
  { length: 41 },
  (_, i) => `images/photos-carousel/photo-${String(i + 1).padStart(2, "0")}.jpg`
);

/* Bandeau défilant continu (auto + drag), chaque photo cliquable → lightbox.
   Distingue le clic du glissé via un seuil de déplacement (drag.moved). */
const PhotoCarousel = ({ photos }) => {
  const ref = useRef(null);
  const paused = useRef(false);
  const drag = useRef({ down: false, startX: 0, startScroll: 0, moved: false });
  const items = [...photos, ...photos]; // 2 copies pour une boucle sans couture

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    let raf;
    const speed = 0.5; // px / frame
    const step = () => {
      const half = el.scrollWidth / 2;
      if (half > 0) {
        if (!reduce && !paused.current && !drag.current.down) el.scrollLeft += speed;
        if (el.scrollLeft >= half) el.scrollLeft -= half;
        else if (el.scrollLeft < 0) el.scrollLeft += half;
      }
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [photos]);

  const onPointerDown = (e) => {
    const el = ref.current;
    drag.current = { down: true, startX: e.clientX, startScroll: el.scrollLeft, moved: false };
    el.classList.add("is-dragging");
    // NB : pas de setPointerCapture ici — il redirige le pointerup vers le conteneur
    // et supprime l'event `click` sur la photo (donc la lightbox ne s'ouvrait pas).
  };
  const onPointerMove = (e) => {
    if (!drag.current.down) return;
    const dx = e.clientX - drag.current.startX;
    if (Math.abs(dx) > 6) drag.current.moved = true;
    ref.current.scrollLeft = drag.current.startScroll - dx;
  };
  const endDrag = () => {
    drag.current.down = false;
    if (ref.current) ref.current.classList.remove("is-dragging");
  };
  const onItemClick = (src) => (e) => {
    if (drag.current.moved) { e.preventDefault(); return; } // c'était un glissé, pas un clic
    openLightbox(src, "");
  };

  return (
    <div
      ref={ref}
      className="photo-carousel"
      onMouseEnter={() => { paused.current = true; }}
      onMouseLeave={() => { paused.current = false; endDrag(); }}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={endDrag}
      onPointerCancel={endDrag}
    >
      {items.map((src, i) => {
        const clone = i >= photos.length;
        return (
          <button
            key={i}
            type="button"
            className="photo-item"
            aria-hidden={clone ? "true" : undefined}
            tabIndex={clone ? -1 : 0}
            onClick={onItemClick(src)}
            aria-label={clone ? undefined : "Agrandir la photo"}
          >
            <img src={src} alt={clone ? "" : "Vilaine Pousse en images"} loading="lazy" draggable="false" />
          </button>
        );
      })}
    </div>
  );
};

const GaleriePhotos = () => (
  <section id="galerie" data-screen-label="03b Galerie" className="bg-sand-soft paper py-12 relative overflow-hidden">
    <div className="text-center mb-6 px-6">
      <span className="font-script text-pink-vp" style={{ fontSize: "clamp(26px, 8vw, 34px)", lineHeight: 1 }}>Vilaine Pousse en images</span>
    </div>
    <PhotoCarousel photos={GALLERY_PHOTOS} />
  </section>
);

const StatCard = ({ num, label, sub, tone, img }) => {
  const toneClass = tone === "sage" ? "bg-sage" : tone === "coral" ? "bg-coral" : "bg-lime-vp";
  const textTone = (tone === "lime" && !img) ? "text-olive" : "text-white";
  const bgStyle = img ? { backgroundImage: `url('${img}')`, backgroundSize: "cover", backgroundPosition: "center" } : {};
  return (
    <div className={`${toneClass} ${textTone} rounded-3xl p-6 relative overflow-hidden hover-lift`} style={bgStyle}>
      <div className="absolute -top-4 -right-4 opacity-30">
        {tone === "sage" ? <Leaf color="white" size={90} rotate={20} /> : tone === "coral" ? <Flower color="white" size={90} /> : <Sprig color="white" size={90} rotate={10} />}
      </div>
      <div className="font-brush leading-none" style={{ fontSize: 72 }}>{num}</div>
      <div className="font-bold text-lg mt-1">{label}</div>
      <div className="text-sm opacity-90 mt-1">{sub}</div>
    </div>
  );
};

/* ───────────────────────────  CARTE INTERACTIVE  ─────────────────────────── */

// Jardins partagés (vraies données publiques, cf. data-jardins.js + docs/)
const JARDINS = ((typeof window !== "undefined" && window.JARDINS_DATA) || []).map(j => ({
  id: j.id,
  type: "jardin",
  name: j.name,
  quartier: null,
  address: j.adresse || null,
  referent: null,
  phone: j.contactType === "tel" ? j.contact : null,
  email: j.contactType === "email" ? j.contact : null,
  horaires: null,
  lat: j.lat,
  lng: j.lng,
}));

// Composteurs partagés (vraies données publiques, cf. data-composteurs.js + docs/)
const COMPOSTEURS = ((typeof window !== "undefined" && window.COMPOSTEURS_DATA) || []).map(c => ({
  id: c.id,
  type: "composteur",
  name: "Composteur partagé",
  quartier: c.commune || "Rennes Métropole",
  commune: c.commune,
  address: c.adresse || null,
  referent: c.referent || null,
  phone: null,
  email: "biodechets@rennesmetropole.fr",
  horaires: null,
  lat: c.lat,
  lng: c.lng,
}));

const MAP_PLACES = [...JARDINS, ...COMPOSTEURS];

const makePinIcon = (isJardin) => L.divIcon({
  className: "vp-pin-wrap",
  html: `<div class="vp-pin ${isJardin ? "" : "composteur"}">
    <div class="pin-body"><span class="pin-icon">${isJardin ? "🌱" : "♻"}</span></div>
  </div>`,
  iconSize: [38, 50],
  iconAnchor: [19, 50],
  popupAnchor: [0, -44],
});

const CarteInteractive = () => {
  const [filter, setFilter] = useState("all"); // all | jardin | composteur
  const mapRef = useRef(null);
  const mapInstance = useRef(null);
  const jardinLayer = useRef(null);
  const composteurLayer = useRef(null);

  // Init map (once)
  useEffect(() => {
    if (!mapRef.current || mapInstance.current || typeof L === "undefined") return;
    const map = L.map(mapRef.current, {
      center: [48.1147, -1.6794],
      zoom: 12,
      zoomControl: true,
      scrollWheelZoom: false, // friendlier UX
    });
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      maxZoom: 19,
    }).addTo(map);
    mapInstance.current = map;

    // Groupe de clusters coloré par type (fallback layerGroup si plugin absent)
    const makeCluster = (cls) => (typeof L.markerClusterGroup === "function")
      ? L.markerClusterGroup({
          maxClusterRadius: 55, showCoverageOnHover: false, chunkedLoading: true, spiderfyOnMaxZoom: true,
          iconCreateFunction: (c) => L.divIcon({
            html: `<div class="vp-cluster ${cls}">${c.getChildCount()}</div>`,
            className: "vp-cluster-wrap", iconSize: [40, 40],
          }),
        })
      : L.layerGroup();

    const addPlaces = (places, isJardin, layer) => {
      places.forEach(p => {
        const m = L.marker([p.lat, p.lng], { icon: makePinIcon(isJardin) });
        m.bindPopup(buildPopupHTML(p), { closeButton: true, autoPanPadding: [40, 60] });
        layer.addLayer(m);
      });
    };

    const jLayer = makeCluster("jardin");
    addPlaces(JARDINS, true, jLayer);
    jardinLayer.current = jLayer;
    map.addLayer(jLayer);

    const cLayer = makeCluster("composteur");
    addPlaces(COMPOSTEURS, false, cLayer);
    composteurLayer.current = cLayer;
    map.addLayer(cLayer);

    setTimeout(() => map.invalidateSize(), 200);
    const onResize = () => map.invalidateSize();
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  // Toggle visibility based on filter
  useEffect(() => {
    const map = mapInstance.current;
    if (!map) return;
    const toggle = (layer, show) => {
      if (!layer) return;
      if (show) { if (!map.hasLayer(layer)) map.addLayer(layer); }
      else { if (map.hasLayer(layer)) map.removeLayer(layer); }
    };
    toggle(jardinLayer.current, filter === "all" || filter === "jardin");
    toggle(composteurLayer.current, filter === "all" || filter === "composteur");
  }, [filter]);

  return (
    <section id="carte" data-screen-label="06 Carte" className="bg-sand paper pt-10 pb-20 relative overflow-hidden">
      {/* Illustrations d'ambiance (feuille, papillon, abeille) supprimées : consigne client 2026-07 */}
      <div className="max-w-7xl mx-auto px-6">
        {/* Banner heading */}
        <h2 className="font-brush text-pink-vp text-center" style={{ fontSize: "clamp(38px, 5vw, 60px)", lineHeight: 1, letterSpacing: "0.01em" }}>
          TROUVER UN JARDIN OU UN COMPOSTEUR
        </h2>
        <div className="text-center mt-2 mb-10">
          <span className="font-script text-olive text-2xl">la carte des espaces partagés à Rennes et ses alentours</span>
        </div>

        {/* Filter pills */}
        <div className="flex flex-wrap justify-center gap-3 mb-6">
          <button
            className={`filter-pill ${filter === "all" ? "active" : ""}`}
            onClick={() => setFilter("all")}
          >
            Tout afficher
            <span className="bg-white/30 text-xs px-2 py-0.5 rounded-full">{MAP_PLACES.length}</span>
          </button>
          <button
            className={`filter-pill jardins ${filter === "jardin" ? "active" : ""}`}
            onClick={() => setFilter("jardin")}
          >
            Jardins partagés
            <span className={`text-xs px-2 py-0.5 rounded-full ${filter === "jardin" ? "bg-white/30" : "bg-sage/15"}`}>
              {MAP_PLACES.filter(p => p.type === "jardin").length}
            </span>
          </button>
          <button
            className={`filter-pill ${filter === "composteur" ? "active composteurs" : ""}`}
            style={filter === "composteur" ? {} : { color: "var(--vp-coral)", borderColor: "var(--vp-coral)" }}
            onClick={() => setFilter("composteur")}
          >
            Composteurs
            <span className={`text-xs px-2 py-0.5 rounded-full ${filter === "composteur" ? "bg-white/30" : "bg-coral/15"}`}>
              {MAP_PLACES.filter(p => p.type === "composteur").length}
            </span>
          </button>
        </div>

        {/* Map */}
        <div className="vp-card overflow-hidden relative" style={{ height: 480 }}>
          <div ref={mapRef} style={{ width: "100%", height: "100%" }} />
          {/* Map legend overlay */}
          <div className="absolute bottom-4 left-4 bg-white rounded-2xl px-4 py-3 text-xs shadow-lg z-[400]">
            <div className="flex items-center gap-2 mb-1.5">
              <span className="inline-block w-3 h-3 rounded-full bg-sage" /> Jardins partagés
            </div>
            <div className="flex items-center gap-2">
              <span className="inline-block w-3 h-3 rounded-full bg-coral" /> Composteurs partagés
            </div>
          </div>
        </div>

        <p className="text-center text-xs text-gray-500 mt-6 italic">
          Jardins et composteurs partagés du territoire rennais. Cliquez sur un point pour les infos et l'itinéraire.
        </p>
      </div>
    </section>
  );
};

const fmtPhone = (t) => (t ? String(t).replace(/\D/g, "").match(/.{1,2}/g)?.join(" ") || t : "");

const buildPopupHTML = (p) => {
  const isJardin = p.type === "jardin";
  const tag = isJardin ? "Jardin partagé" : "Composteur partagé";
  const tagColor = isJardin ? "#84BF9E" : "#F27D52";
  const gMaps = `https://www.google.com/maps/dir/?api=1&destination=${p.lat},${p.lng}`;
  const phone = fmtPhone(p.phone);

  const lines = [];
  if (p.address) lines.push(`<div style="margin-bottom:4px;">📍 ${p.address}</div>`);
  if (p.referent) {
    const label = isJardin ? "Référent" : "Référent de secteur";
    lines.push(`<div style="margin-bottom:4px;">👤 <span style="color:#888;font-size:11px;">${label}</span><br>${p.referent}${phone ? ` · <a href="tel:${String(p.phone).replace(/\D/g, "")}" style="color:#84BF9E;text-decoration:none;">${phone}</a>` : ""}</div>`);
  } else if (phone) {
    lines.push(`<div style="margin-bottom:4px;">📞 ${phone}</div>`);
  }
  if (p.email) lines.push(`<div style="margin-bottom:4px;">✉️ <a href="mailto:${p.email}" style="color:#84BF9E;">${p.email}</a></div>`);
  if (p.horaires) lines.push(`<div style="margin-bottom:4px;">🕒 ${p.horaires}</div>`);

  return `
    <div style="padding:16px;font-family:'Open Sans',sans-serif;min-width:200px;">
      <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
        <span style="font-size:18px;">${isJardin ? "🌱" : "♻"}</span>
        <span style="background:${tagColor};color:white;font-size:10px;padding:3px 9px;border-radius:999px;font-weight:700;letter-spacing:0.06em;">${tag.toUpperCase()}</span>
      </div>
      <h4 style="margin:0 0 4px;font-weight:700;font-size:16px;color:#2B2B2B;line-height:1.2;">${p.name}</h4>
      ${p.quartier ? `<div style="color:#666;font-size:12px;margin-bottom:10px;">${p.quartier}</div>` : '<div style="margin-bottom:10px;"></div>'}
      <div style="font-size:13px;color:#444;line-height:1.5;margin-bottom:10px;">
        ${lines.join("")}
      </div>
      <a href="${gMaps}" target="_blank" rel="noopener" style="display:inline-block;background:#84BF9E;color:white;padding:8px 14px;border-radius:10px;font-weight:700;font-size:13px;text-decoration:none;">Itinéraire →</a>
    </div>
  `;
};

const PlaceCard = ({ place: p, active, onClick }) => {
  const isJardin = p.type === "jardin";
  const tagColor = isJardin ? "var(--vp-sage)" : "var(--vp-coral)";
  return (
    <div
      className={`vp-card p-5 hover-lift cursor-pointer relative ${active ? "ring-2 ring-pink-vp" : ""}`}
      style={active ? { boxShadow: "0 0 0 3px var(--vp-pink), 0 14px 36px -16px rgba(60,50,30,0.3)" } : {}}
      onClick={onClick}
    >
      <div className="flex items-start justify-between mb-3">
        <div
          className="text-white text-[10px] font-bold tracking-wider px-2.5 py-1 rounded-full"
          style={{ background: tagColor }}
        >
          {isJardin ? "🌱 JARDIN PARTAGÉ" : "♻ COMPOSTEUR"}
        </div>
        <span className="text-xs text-gray-500">{p.quartier}</span>
      </div>
      <h4 className="font-bold text-lg leading-tight mb-2">{p.name}</h4>
      <div className="text-sm text-gray-700 space-y-1">
        <div>📍 {p.address}</div>
        <div>🕒 {p.horaires}</div>
        <div className="text-xs text-gray-500 pt-1">{p.referent} · {p.phone}</div>
      </div>
      <div className="mt-4 flex items-center justify-between">
        <span className="text-sage font-bold text-sm">Voir sur la carte →</span>
        <a
          href={`https://www.google.com/maps/dir/?api=1&destination=${p.lat},${p.lng}`}
          target="_blank"
          rel="noopener noreferrer"
          onClick={(e) => e.stopPropagation()}
          className="text-xs text-coral font-bold hover:underline"
        >
          Itinéraire ↗
        </a>
      </div>
    </div>
  );
};

const EmptyState = ({ onReset }) => (
  <div className="vp-card-soft p-12 text-center max-w-md mx-auto">
    <div className="flex justify-center mb-4 opacity-60">
      <Sprig color="#7a8246" size={80} rotate={0} />
    </div>
    <h4 className="font-bold text-lg mb-2">Aucun lieu ne correspond.</h4>
    <p className="text-gray-600 text-sm mb-4">Essayez un autre filtre pour découvrir nos espaces partagés.</p>
    <button onClick={onReset} className="btn-sage">
      Réinitialiser le filtre
    </button>
  </div>
);

window.SectionsMid = { NosActions, CarteInteractive, ChiffresCles, GaleriePhotos };
