/* global React, Splash, Btn, Reveal, SectionHead, useHolyEvents, L */
const { useState: useLocState, useEffect: useLocEffect, useRef: useLocRef } = React;

const BAMENOHL_COORDS = [51.1644358, 7.9818279];

function MapEmbed() {
  const mapRef = useLocRef(null);
  const mapInstanceRef = useLocRef(null);

  useLocEffect(() => {
    if (!mapRef.current || !window.L || mapInstanceRef.current) return;

    const map = L.map(mapRef.current, {
      center: BAMENOHL_COORDS,
      zoom: 16,
      zoomControl: false,
      scrollWheelZoom: false,
      attributionControl: true
    });

    L.control.zoom({ position: "bottomright" }).addTo(map);
    L.tileLayer("https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png", {
      maxZoom: 20,
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="https://carto.com/attributions">CARTO</a>'
    }).addTo(map);

    const holyIcon = L.divIcon({
      className: "holy-map-pin",
      html: '<span class="holy-map-pin__pulse"></span><span class="holy-map-pin__dot"></span>',
      iconSize: [72, 72],
      iconAnchor: [36, 36]
    });

    L.marker(BAMENOHL_COORDS, { icon: holyIcon })
      .addTo(map)
      .bindPopup('<strong>Holy Smash Truck</strong><br>Schützenhalle Bamenohl<br>Fr–So · 17:00–21:00 Uhr');

    mapInstanceRef.current = map;
    setTimeout(() => map.invalidateSize(), 250);

    return () => {
      map.remove();
      mapInstanceRef.current = null;
    };
  }, []);

  return (
    <div className="main-loc__map main-loc__map--live">
      <div ref={mapRef} className="holy-map" aria-label="Interaktive Karte zur Schützenhalle Bamenohl" />
      <div className="holy-map__shade" aria-hidden="true" />
      <div className="holy-map__badge">
        <span className="tape tape--teal">Hier sind wir.</span>
      </div>
    </div>);
}

function eventTitle(event) {
  if ((event.location || "").includes("Schützenhalle") || (event.location || "").includes("Bamenohl")) return "Schützenhalle Bamenohl";
  return event.title || "Holy Smash Truck";
}

function sameWeek(date) {
  const now = new Date();
  const d = new Date(date);
  const start = new Date(now);
  const day = (start.getDay() + 6) % 7;
  start.setHours(0, 0, 0, 0);
  start.setDate(start.getDate() - day);
  const end = new Date(start);
  end.setDate(start.getDate() + 7);
  return d >= start && d < end;
}

function sameMonth(date) {
  const now = new Date();
  const d = new Date(date);
  return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth();
}

function StandortePage() {
  const [filter, setFilter] = useLocState(0);
  const [visibleCount, setVisibleCount] = useLocState(9);
  const { events, loading, error } = useHolyEvents(36);
  const filtered = events.filter((e) => {
    if (filter === 1) return sameWeek(e.start);
    if (filter === 2) return sameMonth(e.start);
    return true;
  });
  const visibleEvents = filtered.slice(0, visibleCount);
  const hasMoreEvents = filtered.length > visibleCount;

  return (
    <>
      <header className="page-head">
        <Splash className="page-head__splash" />
        <div className="container">
          <Reveal>
            <div className="eyebrow page-head__eyebrow">Standorte & Termine</div>
            <h1 className="page-head__title display">
              Wo der
              <br />
              <span style={{ color: "var(--teal)" }}>Truck</span> heute
              <br />
              steht.
            </h1>
            <p className="page-head__sub">
              Stammplatz an der Schützenhalle Bamenohl. Plus Sondertermine, Stadtfeste
              und Events in NRW. Die Termine kommen live aus unserem Holy Smash Truck Kalender.
            </p>
          </Reveal>
        </div>
      </header>

      <section className="section section--tight" style={{ paddingTop: 20 }}>
        <div className="container">
          <Reveal>
            <div className="main-loc">
              <div>
                <div className="eyebrow" style={{ marginBottom: 12 }}>Stammplatz</div>
                <h2 className="display" style={{ fontSize: "clamp(36px, 5vw, 56px)", marginBottom: 14 }}>
                  Schützenhalle
                  <br />
                  <span style={{ color: "var(--teal)" }}>Bamenohl.</span>
                </h2>
                <p style={{ color: "var(--muted)", fontSize: 16, marginBottom: 8 }}>
                  Bamenohler Str. 55<br />
                  57413 Finnentrop Bamenohl<br />
                  Nordrhein-Westfalen
                </p>
                <ul className="hours">
                  <li><span className="day">Freitag</span><span className="time">17:00–21:00</span></li>
                  <li><span className="day">Samstag</span><span className="time">17:00–21:00</span></li>
                  <li><span className="day">Sonntag</span><span className="time">17:00–21:00</span></li>
                  <li><span className="day">Mo–Do</span><span className="time">Ruhetag</span></li>
                </ul>
                <div style={{ display: "flex", gap: 10, marginTop: 24, flexWrap: "wrap" }}>
                  <Btn variant="primary" href="https://maps.google.com/?q=Sch%C3%BCtzenhalle+Bamenohl">
                    Route starten <span className="arrow">→</span>
                  </Btn>
                  <Btn variant="ghost" href="https://app.ordering.sumup.com/holy-smash/bamenohl">
                    Vorbestellen
                  </Btn>
                </div>
              </div>
              <MapEmbed />
            </div>
          </Reveal>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <SectionHead
            eyebrow="Live-Terminkalender"
            title="Wo's als nächstes smasht."
            sub="Automatisch aus dem Holy Smash Truck Google Kalender geladen. Änderungen im Kalender erscheinen hier ohne Website-Update." />
          
          <Reveal className="menu-tabs" style={{ marginBottom: 32 }}>
            {[
            { v: 1, l: "Diese Woche" },
            { v: 2, l: "Diesen Monat" },
            { v: 0, l: "Alle Termine" }].
            map((opt) =>
            <div key={opt.v} className={`menu-tab ${filter === opt.v ? "active" : ""}`} onClick={() => { setFilter(opt.v); setVisibleCount(9); }}>
                {opt.l}
              </div>
            )}
          </Reveal>

          {error && <div className="form-error" style={{ marginBottom: 24 }}>{error}</div>}
          {loading && <p style={{ color: "var(--muted)", marginBottom: 24 }}>Termine werden geladen …</p>}
          {!loading && filtered.length === 0 && <p style={{ color: "var(--muted)", marginBottom: 24 }}>Für diesen Zeitraum sind gerade keine Termine eingetragen.</p>}

          <Reveal staggerChildren className="events-grid">
            {visibleEvents.map((e) =>
            <a key={e.id} className="event" href={e.mapsUrl} target="_blank" rel="noreferrer">
                <span className={`tape tape--${e.tag === "Sondertermin" ? "orange" : "ghost"} event__tag`}>
                  {e.tag}
                </span>
                <div className="event__date">
                  <span className="d">{e.dayNumber}</span>
                  <span className="m">
                    {e.month}
                    <br />
                    {e.weekday}
                  </span>
                </div>
                <h3 className="event__title display">{eventTitle(e)}</h3>
                <div className="event__meta">
                  <span>{e.startTime}–{e.endTime} Uhr</span>
                  <span>{e.meta}</span>
                </div>
              </a>
            )}
            {hasMoreEvents &&
            <button className="event event--load-more" type="button" onClick={() => setVisibleCount((count) => count + 9)}>
                <span className="tape tape--teal event__tag">Mehr</span>
                <div className="event__date">
                  <span className="d">+9</span>
                  <span className="m">
                    weitere<br />
                    Termine
                  </span>
                </div>
                <h3 className="event__title display">Weitere Termine laden</h3>
                <div className="event__meta">
                  <span>{filtered.length - visibleCount} Termine noch verfügbar</span>
                  <span>Klick zum Nachladen</span>
                </div>
              </button>
            }
          </Reveal>
        </div>
      </section>

      <section className="section section--tight">
        <div className="container">
          <Reveal>
            <div className="big-cta">
              <Splash className="big-cta__splash" color="#0a2a29" />
              <h2 className="big-cta__title display">
                Truck für
                <br />
                dein Event?
              </h2>
              <p className="big-cta__sub">
                Wir kommen auch zu dir. Hochzeiten, Firmenfeiern, Privatevents — wir bringen die Platte mit.
              </p>
              <Btn variant="orange" size="lg" onClick={() => window.location.hash = "#/catering"}>
                Catering anfragen <span className="arrow">→</span>
              </Btn>
            </div>
          </Reveal>
        </div>
      </section>
    </>);
}

window.StandortePage = StandortePage;
