<script lang="ts">
  import { get } from "svelte/store";
  import { getLigaSlug } from "../stores/getLigaSlug";
  import {
    ligabereicheState,
    ligabereichSelection,
  } from "../stores/LigabereicheStore";
  import { outlinesBundesland, scale } from "./Deutschland";
  import { configuration } from "../stores/configuration";

  const colors: Record<string, string[]> = {
    stdlat: ["#c955be", "#993192", "#551B50", "#521a4d"],
    jmc: ["#e86d3c", "#ba4618", "#963914", "#6b280e"],
  };

  const ligaColors = $derived.by(() => {
    const lb = get(ligabereicheState);
    if (!lb?.ligabereiche.length) return;

    return lb.ligabereiche.map((_, idx) => {
      return (
        colors[configuration.sparte]?.[
          idx % colors[configuration.sparte].length
        ] || "#888"
      );
    });
  });

  function setSelection(name: string) {
    const slug = getLigaSlug(name);
    ligabereichSelection.set($ligabereichSelection === slug ? undefined : slug);
  }

  const viewBox = [0, 0, 590 * scale, 800 * scale];
</script>

<svg
  version="1.1"
  id="Bundesrepublik_Deutschland"
  width={viewBox[2] - viewBox[0]}
  height={viewBox[3] - viewBox[1]}
  viewBox={viewBox.join(" ")}
  overflow="visible"
  class={$ligabereichSelection ? "selected" : ""}
>
  {#if !$ligabereicheState}
    {#each Object.values(outlinesBundesland) as outline}
      <path d={outline} fill="#eee" stroke="#ccc" stroke-width="6" />
    {/each}
  {/if}
  {#each $ligabereicheState?.ligabereiche || [] as bereich, index}
    <g
      class={$ligabereichSelection == getLigaSlug(bereich.bezeichnung)
        ? "selected"
        : ""}
      style="cursor: pointer"
      onclick={() => setSelection(bereich.bezeichnung)}
      onkeydown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          setSelection(bereich.bezeichnung);
        }
      }}
      tabindex={index}
      role="button"
    >
      {#each bereich.zuordnung as zuordnung}
        <path
          d={outlinesBundesland[zuordnung.ltv]}
          fill={ligaColors?.[index]}
        />
      {/each}
    </g>
  {/each}
</svg>

<style lang="scss">
  svg {
    width: 100%;
    max-width: 100%;
    height: auto;
    max-width: 400px;

    &.selected g path {
      opacity: 0.5;
    }

    g {
      outline: none;
      transition: filter 0.3s ease-out;
      path {
        stroke: white;
        stroke-width: 6;
        // 50% saturation
        opacity: 0.7;

        cursor: pointer;
        transition: opacity 0.3s ease-out;
      }
      &:hover path,
      &:focus path,
      &.selected path {
        opacity: 1;
      }
      &.selected {
        filter: drop-shadow(5px 5px 40px black);
      }
    }
  }
</style>
