<script lang="ts">
  import type { SpecialVisualizationState } from "../SpecialVisualization"
  import type { Feature } from "geojson"
  import { UIEventSource } from "../../Logic/UIEventSource"
  import type { OsmTags } from "../../Models/OsmFeature"
  import LayerConfig from "../../Models/ThemeConfig/LayerConfig"
  import AccordionSingle from "../Flowbite/AccordionSingle.svelte"
  import TagRenderingAnswer from "./TagRendering/TagRenderingAnswer.svelte"
  import TagRenderingEditableDynamic from "./TagRendering/TagRenderingEditableDynamic.svelte"
  import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig"

  export let state: SpecialVisualizationState
  export let selectedElement: Feature
  export let tags: UIEventSource<OsmTags>
  export let labels: string[]
  export let blacklist: string[]
  export let header: string
  export let layer: LayerConfig

  let headerTr = layer.tagRenderings.find((tr) => tr.id === header)
  if (headerTr === undefined) {
    console.error("Header tagRendering with ID", header, "was not found")
  }
  let tagRenderings: TagRenderingConfig[] = []
  let seenIds = new Set<string>()
  let blacklistSet = new Set(blacklist)
  for (const label of labels) {
    for (const tr of layer.tagRenderings) {
      if (seenIds.has(tr.id)) {
        continue
      }
      if (blacklistSet.has(tr.id) || tr.labels.some((l) => blacklistSet.has(l))) {
        continue
      }
      if (label === tr.id || tr.labels.some((l) => l === label)) {
        tagRenderings.push(tr)
        seenIds.add(tr.id)
      }
    }
  }
  let isTesting = state.featureSwitchIsTesting
</script>

{#if tagRenderings.length > 0}
  <div class="mb-8">
    <AccordionSingle>
      <div slot="header">
        {#if headerTr}
          <TagRenderingAnswer {tags} {layer} config={headerTr} {state} {selectedElement} />
        {:else}
          {header}
        {/if}
      </div>
      {#each tagRenderings as config (config.id)}
        {#if config.IsKnown($tags) && (config.condition === undefined || config.condition.matchesProperties($tags))}
          <TagRenderingEditableDynamic {tags} {config} {state} {selectedElement} {layer} />
        {/if}
      {/each}
    </AccordionSingle>
  </div>
{:else if $isTesting}
  <div class="alert">
    Group not loaded as no labels match {labels.join(", ")}
    {#if blacklist.length > 0}
      (with blacklist {blacklist.join(", ")})
    {/if}
  </div>
{/if}
