"use client";

import { useRef, useEffect, useState } from "react";
import dynamic from "next/dynamic";
import gsap from "gsap";
import { useLanguage } from "@/lib/i18n/context";

const Map = dynamic(() => import("./Map"), { ssr: false });

interface Point {
  id: number;
  name: string;
  address: string;
  city: string;
  phone: string;
  lat: number;
  lng: number;
}

export default function MapSection() {
  const { t } = useLanguage();
  const badgeRef = useRef<HTMLSpanElement>(null);
  const line1Ref = useRef<HTMLDivElement>(null);
  const line2Ref = useRef<HTMLDivElement>(null);
  const mapRef   = useRef<HTMLDivElement>(null);

  const [points,    setPoints]    = useState<Point[]>([]);
  const [mapLoaded, setMapLoaded] = useState(false);

  useEffect(() => {
    fetch("/api/points-de-vente")
      .then((r) => r.json())
      .then((d) => setPoints(Array.isArray(d) ? d : []));
  }, []);

  useEffect(() => {
    const badge = badgeRef.current;
    const line1 = line1Ref.current;
    const line2 = line2Ref.current;
    const map   = mapRef.current;
    if (!badge) return;

    gsap.set(badge,          { opacity: 0, y: 16 });
    gsap.set([line1, line2], { y: "108%" });
    gsap.set(map,            { opacity: 0, y: 40 });

    const obs = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      setMapLoaded(true);
      const tl = gsap.timeline();
      tl.to(badge, { opacity: 1, y: 0, duration: 0.7,  ease: "power3.out" }, 0);
      tl.to(line1, { y: "0%",          duration: 0.9,  ease: "power4.out" }, 0.18);
      tl.to(line2, { y: "0%",          duration: 0.9,  ease: "power4.out" }, 0.32);
      tl.to(map,   { opacity: 1, y: 0, duration: 0.85, ease: "power3.out" }, 0.48);
      obs.disconnect();
    }, { rootMargin: "0px 0px -25% 0px", threshold: 0 });

    obs.observe(badge);
    return () => obs.disconnect();
  }, []);

  return (
    <section id="boutiques" className="bg-brand-off-white">

      {/* Header */}
      <div className="max-w-7xl mx-auto px-6 lg:px-16 pt-10 lg:pt-20 pb-16 lg:pb-10">
        <div className="space-y-3">
          <span
            ref={badgeRef}
            className="inline-block bg-brand-yellow text-brand-dark px-4 py-1.5 rounded-full text-[11px] font-bold tracking-[0.22em] uppercase"
          >
            {t.map.badge}
          </span>
          <h2
            className="font-bold leading-none tracking-tight"
            style={{ fontFamily: "var(--font-space, sans-serif)", fontSize: "clamp(2.2rem, 4vw, 4rem)" }}
          >
            <span className="block overflow-hidden">
              <div ref={line1Ref} className="text-brand-dark">{t.map.line1}</div>
            </span>
            <span className="block overflow-hidden">
              <div ref={line2Ref} className="text-brand-dark/40">{t.map.line2}</div>
            </span>
          </h2>
          {points.length > 0 && (
            <p className="text-brand-dark/40 text-sm pt-1">{points.length} {points.length > 1 ? t.map.counts : t.map.count}</p>
          )}
        </div>
      </div>

      {/* Map */}
      <div ref={mapRef} style={{ height: 520, position: "relative" }}>
        <div
          className="absolute top-0 left-0 right-0 z-10 pointer-events-none"
          style={{ height: 48, background: "linear-gradient(to bottom, var(--color-brand-off-white), transparent)" }}
        />
        {mapLoaded && (
          <Map points={points} openInMaps={t.map.openInMaps} />
        )}
        <div
          className="absolute bottom-0 left-0 right-0 z-10 pointer-events-none"
          style={{ height: 48, background: "linear-gradient(to top, var(--color-brand-off-white), transparent)" }}
        />
      </div>

    </section>
  );
}
