<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import type { HudColorMapOption, PressureColorMapPreset } from "$lib/types/hud";

  export let title = "";
  export let hint = "";
  export let matrixSizeLabel = "";
  export let matrixRowsLabel = "";
  export let matrixColsLabel = "";
  export let rangeLabel = "";
  export let rangeMinLabel = "";
  export let rangeMaxLabel = "";
  export let colorMapLabel = "";
  export let resetLabel = "";
  export let applyLiveHint = "";
  export let matrixRows = 12;
  export let matrixCols = 7;
  export let rangeMin = 0;
  export let rangeMax = 5000;
  export let colorMapPreset: PressureColorMapPreset = "emerald";
  export let colorMapOptions: HudColorMapOption[] = [];

  const dispatch = createEventDispatcher<{
    close: void;
  }>();

  const presetSizes = [12, 24, 32, 48, 64];
  const gridMin = 1;
  const gridMax = 128;
  const gridStep = 1;
  const rangeFloor = -9999;
  const rangeCeiling = 99999;

  function clamp(value: number, min: number, max: number): number {
    return Math.min(max, Math.max(min, value));
  }

  function normalizeGridValue(value: number): number {
    const numericValue = Number.isFinite(value) ? value : 12;
    return clamp(Math.round(numericValue), gridMin, gridMax);
  }

  function normalizeRangeValue(value: number): number {
    return clamp(Math.round(Number.isFinite(value) ? value : 0), rangeFloor, rangeCeiling);
  }

  function handleRowsInput(event: Event): void {
    const target = event.currentTarget as HTMLInputElement;
    matrixRows = normalizeGridValue(target.valueAsNumber);
  }

  function handleColsInput(event: Event): void {
    const target = event.currentTarget as HTMLInputElement;
    matrixCols = normalizeGridValue(target.valueAsNumber);
  }

  function handleRangeMinInput(event: Event): void {
    const target = event.currentTarget as HTMLInputElement;
    rangeMin = normalizeRangeValue(target.valueAsNumber);

    if (rangeMin >= rangeMax) {
      rangeMax = rangeMin + 1;
    }
  }

  function handleRangeMaxInput(event: Event): void {
    const target = event.currentTarget as HTMLInputElement;
    rangeMax = normalizeRangeValue(target.valueAsNumber);

    if (rangeMax <= rangeMin) {
      rangeMin = rangeMax - 1;
    }
  }

  function applyPreset(size: number): void {
    matrixRows = size;
    matrixCols = size;
  }

  function applyColorMapPreset(id: PressureColorMapPreset): void {
    colorMapPreset = id;
  }

  function resetDefaults(): void {
    matrixRows = 12;
    matrixCols = 7;
    rangeMin = 0;
    rangeMax = 5000;
    colorMapPreset = "emerald";
  }

  $: selectedColorMap = colorMapOptions.find((option) => option.id === colorMapPreset) ?? colorMapOptions[0];

  $: {
    const nextRows = normalizeGridValue(matrixRows);
    if (nextRows !== matrixRows) {
      matrixRows = nextRows;
    }
  }

  $: {
    const nextCols = normalizeGridValue(matrixCols);
    if (nextCols !== matrixCols) {
      matrixCols = nextCols;
    }
  }

  $: {
    const nextRangeMin = normalizeRangeValue(rangeMin);
    if (nextRangeMin !== rangeMin) {
      rangeMin = nextRangeMin;
    }
  }

  $: {
    const nextRangeMax = Math.max(normalizeRangeValue(rangeMax), rangeMin + 1);
    if (nextRangeMax !== rangeMax) {
      rangeMax = nextRangeMax;
    }
  }
</script>

<section class="config-panel" aria-label={title}>
  <header class="config-head">
    <div class="config-copy">
      <p class="config-label">Stage Config</p>
      <h3>{title}</h3>
      <p class="config-hint">{hint}</p>
    </div>

    <button type="button" class="close-btn" on:click={() => dispatch("close")} aria-label="Close config panel">
      <span></span>
      <span></span>
    </button>
  </header>

  <div class="config-section">
    <div class="section-head">
      <p class="section-title">{matrixSizeLabel}</p>
      <p class="section-note">{matrixRows} x {matrixCols}</p>
    </div>

    <div class="preset-row" role="group" aria-label={matrixSizeLabel}>
      {#each presetSizes as size}
        <button
          type="button"
          class="preset-btn"
          class:is-active={matrixRows === size && matrixCols === size}
          on:click={() => applyPreset(size)}
        >
          {size}x{size}
        </button>
      {/each}
    </div>

    <div class="field-grid">
      <label class="field-card">
        <span class="field-label">{matrixRowsLabel}</span>
        <input type="number" min={gridMin} max={gridMax} step={gridStep} value={matrixRows} on:input={handleRowsInput} />
      </label>

      <label class="field-card">
        <span class="field-label">{matrixColsLabel}</span>
        <input type="number" min={gridMin} max={gridMax} step={gridStep} value={matrixCols} on:input={handleColsInput} />
      </label>
    </div>
  </div>

  <div class="config-section">
    <div class="section-head">
      <p class="section-title">{rangeLabel}</p>
      <p class="section-note">{rangeMin} - {rangeMax}</p>
    </div>

    <div class="field-grid">
      <label class="field-card">
        <span class="field-label">{rangeMinLabel}</span>
        <input type="number" min={rangeFloor} max={rangeCeiling} step="100" value={rangeMin} on:input={handleRangeMinInput} />
      </label>

      <label class="field-card">
        <span class="field-label">{rangeMaxLabel}</span>
        <input type="number" min={rangeFloor} max={rangeCeiling} step="100" value={rangeMax} on:input={handleRangeMaxInput} />
      </label>
    </div>
  </div>

  <div class="config-section">
    <div class="section-head">
      <p class="section-title">{colorMapLabel}</p>
      <p class="section-note">{selectedColorMap?.label ?? colorMapPreset}</p>
    </div>

    <div class="palette-row" role="group" aria-label={colorMapLabel}>
      {#each colorMapOptions as option}
        <button
          type="button"
          class="palette-btn"
          class:is-active={colorMapPreset === option.id}
          on:click={() => applyColorMapPreset(option.id)}
        >
          <span
            class="palette-preview"
            style={`--palette-stop-0: ${option.previewStops[0]}; --palette-stop-1: ${option.previewStops[1]}; --palette-stop-2: ${option.previewStops[2]};`}
            aria-hidden="true"
          ></span>
          <span class="palette-name">{option.label}</span>
        </button>
      {/each}
    </div>
  </div>

  <footer class="config-foot">
    <p class="live-note">{applyLiveHint}</p>
    <button type="button" class="reset-btn" on:click={resetDefaults}>{resetLabel}</button>
  </footer>
</section>

<style>
  .config-panel {
    display: grid;
    gap: 0.9rem;
    inline-size: min(23rem, 100%);
    padding: 0.92rem 0.96rem 1rem;
    border: 1px solid rgb(88 132 116 / 0.3);
    border-radius: 0.82rem;
    background:
      linear-gradient(180deg, rgb(6 18 14 / 0.92), rgb(4 10 9 / 0.88)),
      radial-gradient(circle at 100% 0, rgb(97 146 255 / 0.07), transparent 38%);
    box-shadow:
      inset 0 1px 0 rgb(184 236 206 / 0.08),
      0 18px 46px rgb(0 0 0 / 0.28);
    backdrop-filter: blur(10px);
  }

  .config-head {
    display: flex;
    justify-content: space-between;
    gap: 0.9rem;
    align-items: flex-start;
  }

  .config-copy {
    min-width: 0;
  }

  .config-label,
  .section-title,
  .field-label,
  .live-note {
    margin: 0;
    color: rgb(157 206 181 / 0.8);
    font-size: 0.58rem;
    letter-spacing: 0.12em;
    text-transform: uppercase;
  }

  h3 {
    margin: 0.12rem 0 0;
    color: rgb(237 248 241 / 0.98);
    font-size: 1rem;
    line-height: 1.2;
    font-weight: 600;
  }

  .config-hint,
  .section-note {
    margin: 0.14rem 0 0;
    color: rgb(142 182 164 / 0.78);
    font-size: 0.7rem;
    line-height: 1.25;
  }

  .close-btn {
    position: relative;
    inline-size: 2rem;
    block-size: 2rem;
    border: 1px solid rgb(82 122 106 / 0.32);
    border-radius: 999px;
    background: rgb(4 12 9 / 0.72);
    cursor: pointer;
    flex: 0 0 auto;
  }

  .close-btn span {
    position: absolute;
    top: 50%;
    left: 50%;
    inline-size: 0.8rem;
    block-size: 1px;
    background: rgb(182 210 195 / 0.9);
    transform-origin: center;
  }

  .close-btn span:first-child {
    transform: translate(-50%, -50%) rotate(45deg);
  }

  .close-btn span:last-child {
    transform: translate(-50%, -50%) rotate(-45deg);
  }

  .config-section {
    display: grid;
    gap: 0.62rem;
    padding: 0.76rem 0.8rem;
    border: 1px solid rgb(72 116 96 / 0.22);
    border-radius: 0.72rem;
    background: linear-gradient(180deg, rgb(7 15 12 / 0.76), rgb(5 10 8 / 0.64));
  }

  .section-head {
    display: flex;
    justify-content: space-between;
    gap: 0.75rem;
    align-items: baseline;
  }

  .preset-row {
    display: flex;
    flex-wrap: wrap;
    gap: 0.42rem;
  }

  .palette-row {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 0.48rem;
  }

  .preset-btn,
  .reset-btn,
  .palette-btn {
    border: 1px solid rgb(80 126 105 / 0.28);
    border-radius: 999px;
    padding: 0.38rem 0.72rem;
    background: rgb(8 19 15 / 0.76);
    color: rgb(191 219 206 / 0.92);
    font: inherit;
    font-size: 0.72rem;
    cursor: pointer;
    transition:
      border-color 160ms ease,
      box-shadow 160ms ease,
      color 160ms ease,
      background-color 160ms ease;
  }

  .preset-btn.is-active {
    border-color: rgb(98 201 149 / 0.48);
    background: linear-gradient(180deg, rgb(18 54 37 / 0.96), rgb(10 32 23 / 0.92));
    color: rgb(233 247 240 / 0.98);
    box-shadow: inset 0 1px 0 rgb(198 246 222 / 0.14), 0 0 16px rgb(63 184 120 / 0.14);
  }

  .palette-btn {
    display: grid;
    gap: 0.34rem;
    min-height: 4rem;
    padding: 0.52rem 0.56rem 0.58rem;
    border-radius: 0.74rem;
    text-align: left;
  }

  .palette-btn.is-active {
    border-color: rgb(98 201 149 / 0.48);
    background: linear-gradient(180deg, rgb(18 54 37 / 0.96), rgb(10 32 23 / 0.92));
    color: rgb(233 247 240 / 0.98);
    box-shadow: inset 0 1px 0 rgb(198 246 222 / 0.14), 0 0 16px rgb(63 184 120 / 0.14);
  }

  .palette-preview {
    display: block;
    inline-size: 100%;
    block-size: 0.74rem;
    border-radius: 999px;
    border: 1px solid rgb(255 255 255 / 0.08);
    background:
      linear-gradient(
        90deg,
        var(--palette-stop-0) 0%,
        var(--palette-stop-1) 52%,
        var(--palette-stop-2) 100%
      ),
      linear-gradient(180deg, rgb(255 255 255 / 0.08), transparent 55%);
    box-shadow:
      inset 0 1px 0 rgb(255 255 255 / 0.1),
      0 0 12px rgb(0 0 0 / 0.14);
  }

  .palette-name {
    color: inherit;
    font-size: 0.74rem;
    line-height: 1.1;
    letter-spacing: 0.04em;
  }

  .field-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.58rem;
  }

  .field-card {
    display: grid;
    gap: 0.38rem;
    padding: 0.58rem 0.64rem 0.66rem;
    border: 1px solid rgb(68 106 89 / 0.26);
    border-radius: 0.58rem;
    background: linear-gradient(180deg, rgb(6 14 11 / 0.86), rgb(3 8 6 / 0.82));
  }

  .field-card input {
    inline-size: 100%;
    border: 1px solid rgb(82 131 109 / 0.28);
    border-radius: 0.46rem;
    padding: 0.55rem 0.62rem;
    background: rgb(7 16 12 / 0.92);
    color: rgb(238 246 241 / 0.98);
    font: inherit;
    font-size: 0.86rem;
    outline: none;
  }

  .field-card input:focus {
    border-color: rgb(97 201 147 / 0.54);
    box-shadow: 0 0 0 1px rgb(97 201 147 / 0.24);
  }

  .config-foot {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.75rem;
  }

  .live-note {
    color: rgb(142 182 164 / 0.8);
  }

  .reset-btn {
    background: linear-gradient(180deg, rgb(10 21 17 / 0.88), rgb(6 12 10 / 0.84));
    white-space: nowrap;
  }

  @media (max-width: 960px) {
    .config-panel {
      inline-size: min(20rem, 100%);
      padding: 0.86rem 0.88rem 0.94rem;
    }

    .field-grid {
      grid-template-columns: 1fr;
    }

    .palette-row {
      grid-template-columns: 1fr;
    }
  }
</style>
