<script lang="ts">
  import { onMount } from "svelte";
  import { browser } from "$app/environment";
  import { env } from "$env/dynamic/public";
  import type { WindMapBlockData } from "$lib/block-types";
  import type { WindArea } from "$lib/windkarte";
  import WindAreaPanel from "$lib/components/WindAreaPanel.svelte";
  import { useTranslate, T } from "$lib/translations";

  const t = useTranslate();

  let { block }: { block: WindMapBlockData } = $props();

  const CMS_BASE = (
    env.PUBLIC_CMS_URL || "http://localhost:3000"
  ).replace(/\/$/, "");

let areas = $state<WindArea[]>([]);
  let selectedArea = $state<WindArea | null>(null);
  let selectedCenter = $state<[number, number] | null>(null);
  let mapReady = $state(false);
  let initialGebietsNr = $state<string | null>(null);
  let resetMap: (() => void) | null = null;

  const MapComponent = browser
    ? import("$lib/components/WindkarteMap.svelte").then((m) => m.default)
    : null;

  function handleSelect(area: WindArea | null, center: [number, number] | null = null) {
    selectedArea = area;
    selectedCenter = center;
    if (browser) {
      if (area) {
        history.replaceState(null, "", location.pathname + location.search + "#" + encodeURIComponent(area.gebiets_nr));
      } else {
        history.replaceState(null, "", location.pathname + location.search);
      }
    }
  }

  onMount(async () => {
    const hash = window.location.hash.slice(1);
    if (hash) initialGebietsNr = decodeURIComponent(hash);

    try {
      const slugs = (block.areas ?? [])
        .map((a) => (typeof a === "string" ? a : a._slug))
        .filter(Boolean);

      if (slugs.length > 0) {
        const results = await Promise.all(
          slugs.map((slug) =>
            fetch(`${CMS_BASE}/api/content/wind_area/${slug}`, {
              signal: AbortSignal.timeout(6_000),
            }).then((r) => (r.ok ? r.json() : null))
          )
        );
        areas = results.filter((r): r is WindArea => r !== null);
      } else {
        const res = await fetch(`${CMS_BASE}/api/content/wind_area?limit=100`, {
          signal: AbortSignal.timeout(6_000),
        });
        if (res.ok) {
          const data = await res.json();
          areas = data.items ?? [];
        }
      }
    } catch {
      // Map renders without CMS metadata — GeoJSON tooltips still work
    }
    mapReady = true;
  });
</script>

<div class="wind-map-block">
  {#if block.title || block.subtitle}
    <div class="mb-4">
      {#if block.title}
        <h2 class="text-xl font-semibold text-stein-800">{block.title}</h2>
      {/if}
      {#if block.subtitle}
        <p class="mt-0.5 text-sm text-stein-500">{block.subtitle}</p>
      {/if}
    </div>
  {/if}

  <div class="map-container relative overflow-hidden rounded-xl border border-stein-200 shadow-sm">
    <!-- Reset button -->
    {#if resetMap}
      <button
        onclick={() => { resetMap?.(); handleSelect(null); }}
        class="pointer-events-auto absolute top-2.5 right-2.5 z-[500] rounded-md bg-white/90 p-1.5 shadow-md text-stein-500 hover:text-stein-800 hover:bg-white transition-colors"
        aria-label={t(T.windkarte_reset_aria)}
        title={t(T.windkarte_reset_aria)}
      >
        <svg class="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/>
          <path d="M3 3v5h5"/>
        </svg>
      </button>
    {/if}

    {#if browser && MapComponent && mapReady}
      {#await MapComponent then Map}
        <Map
          {areas}
          {initialGebietsNr}
          onselect={handleSelect}
          onready={(ctrl) => { resetMap = ctrl.reset; }}
        />
      {/await}
    {:else}
      <div class="flex h-full items-center justify-center bg-stein-50 text-stein-400 text-sm">
        {t(T.windkarte_loading)}
      </div>
    {/if}

    <!-- Panel: bottom-sheet on mobile, side-panel on sm+ -->
    <div class="panel-slide {selectedArea ? 'open' : ''}" style="pointer-events: none; z-index: 1001;">
      <WindAreaPanel
        area={selectedArea}
        center={selectedCenter}
        onclose={() => handleSelect(null)}
      />
    </div>
  </div>

  <!-- Legend -->
  <div class="mt-2 flex flex-wrap gap-x-5 gap-y-1.5 text-xs text-stein-400">
    <span class="flex items-center gap-1.5">
      <span class="inline-block size-2.5 rounded-sm" style="background:#2d7a45; opacity:.7"></span>
      {t(T.windkarte_legend_rechtskraeftig)}
    </span>
    <span class="flex items-center gap-1.5">
      <span class="inline-block size-2.5 rounded-sm" style="background:#b08a52; opacity:.7"></span>
      {t(T.windkarte_legend_entwurf_2)}
    </span>
    <span class="flex items-center gap-1.5">
      <span class="inline-block size-2.5 rounded-sm" style="background:#d4752a; opacity:.7"></span>
      {t(T.windkarte_legend_entwurf_2_voraussichtlich)}
    </span>
    <span class="flex items-center gap-x-3 gap-y-1 flex-wrap text-stein-300">
      <span class="text-stein-400">{t(T.windkarte_legend_distances)}</span>
      {#each [{ color: "#e35651", label: "200 m" }, { color: "#b08a52", label: "600 m" }, { color: "#436e85", label: "1 km" }] as ring}
        <span class="flex items-center gap-1.5">
          <span class="dashed-line" style="border-color:{ring.color}"></span>
          {ring.label}
        </span>
      {/each}
    </span>
  </div>
</div>

<style>
  .map-container {
    height: clamp(460px, 75vh, 620px);
  }

  /* Panel: mobile = bottom sheet, sm+ = right side panel */
  .panel-slide {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 52%;
    transform: translateY(100%);
    transition: transform 300ms ease-in-out;
  }
  .panel-slide.open {
    transform: translateY(0);
    pointer-events: auto !important;
  }
  @media (min-width: 640px) {
    .panel-slide {
      top: 0;
      left: auto;
      right: 0;
      bottom: 0;
      height: auto;
      width: 18rem;
      transform: translateX(100%);
    }
    .panel-slide.open {
      transform: translateX(0);
    }
  }

  .dashed-line {
    display: inline-block;
    width: 18px;
    height: 0;
    border-top: 2px dashed;
    vertical-align: middle;
  }
</style>
