<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import { DEFAULT_PRESSURE_RANGE_MAX, DEFAULT_PRESSURE_RANGE_MIN } from "$lib/config/pressure-range";

  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 resetLabel = "";
  export let applyLiveHint = "";
  export let matrixRows = 12;
  export let matrixCols = 7;
  export let rangeMin = DEFAULT_PRESSURE_RANGE_MIN;
  export let rangeMax = DEFAULT_PRESSURE_RANGE_MAX;

  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 resetDefaults(): void {
    matrixRows = 12;
    matrixCols = 7;
    rangeMin = DEFAULT_PRESSURE_RANGE_MIN;
    rangeMax = DEFAULT_PRESSURE_RANGE_MAX;
  }

  function handleSubmit(): void {
    dispatch("close");
  }

  $: {
    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>

<form class="config-panel" aria-label={title} on:submit|preventDefault={handleSubmit}>
  <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>

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

<style>
  .config-panel {
    display: grid;
    gap: 0.9rem;
    inline-size: min(23rem, 100%);
    padding: 0.92rem 0.96rem 1rem;
    border: 1px solid rgb(var(--hud-border-rgb) / 0.3);
    border-radius: 0.82rem;
    background:
      linear-gradient(180deg, rgb(var(--hud-surface-alt-rgb) / 0.92), rgb(var(--hud-surface-deep-rgb) / 0.88)),
      radial-gradient(circle at 100% 0, rgb(var(--hud-info-rgb) / 0.07), transparent 38%);
    box-shadow:
      inset 0 1px 0 rgb(var(--hud-border-strong-rgb) / 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(var(--hud-text-dim-rgb) / 0.8);
    font-size: 0.58rem;
    letter-spacing: 0.12em;
    text-transform: uppercase;
  }

  h3 {
    margin: 0.12rem 0 0;
    color: rgb(var(--hud-text-main-rgb) / 0.98);
    font-size: 1rem;
    line-height: 1.2;
    font-weight: 600;
  }

  .config-hint,
  .section-note {
    margin: 0.14rem 0 0;
    color: rgb(var(--hud-text-dim-rgb) / 0.78);
    font-size: 0.7rem;
    line-height: 1.25;
  }

  .close-btn {
    position: relative;
    inline-size: 2rem;
    block-size: 2rem;
    border: 1px solid rgb(var(--hud-border-rgb) / 0.32);
    border-radius: 999px;
    background: rgb(var(--hud-surface-deep-rgb) / 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(var(--hud-text-main-rgb) / 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(var(--hud-border-rgb) / 0.22);
    border-radius: 0.72rem;
    background: linear-gradient(180deg, rgb(var(--hud-surface-rgb) / 0.76), rgb(var(--hud-surface-deep-rgb) / 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;
  }

  .preset-btn,
  .reset-btn {
    border: 1px solid rgb(var(--hud-border-rgb) / 0.28);
    border-radius: 999px;
    padding: 0.38rem 0.72rem;
    background: rgb(var(--hud-surface-rgb) / 0.76);
    color: rgb(var(--hud-text-main-rgb) / 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(var(--hud-lime-rgb) / 0.48);
    background: linear-gradient(180deg, rgb(var(--hud-surface-alt-rgb) / 0.96), rgb(var(--hud-surface-rgb) / 0.92));
    color: rgb(var(--hud-text-main-rgb) / 0.98);
    box-shadow: inset 0 1px 0 rgb(var(--hud-border-strong-rgb) / 0.14), 0 0 16px rgb(var(--hud-glow-alt-rgb) / 0.14);
  }

  .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(var(--hud-border-rgb) / 0.26);
    border-radius: 0.58rem;
    background: linear-gradient(180deg, rgb(var(--hud-surface-rgb) / 0.86), rgb(var(--hud-surface-deep-rgb) / 0.82));
  }

  .field-card input {
    inline-size: 100%;
    border: 1px solid rgb(var(--hud-border-rgb) / 0.28);
    border-radius: 0.46rem;
    padding: 0.55rem 0.62rem;
    background: rgb(var(--hud-surface-rgb) / 0.92);
    color: rgb(var(--hud-text-main-rgb) / 0.98);
    font: inherit;
    font-size: 0.86rem;
    outline: none;
  }

  .field-card input:focus {
    border-color: rgb(var(--hud-lime-rgb) / 0.54);
    box-shadow: 0 0 0 1px rgb(var(--hud-lime-rgb) / 0.24);
  }

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

  .live-note {
    color: rgb(var(--hud-text-dim-rgb) / 0.8);
  }

  .reset-btn {
    background: linear-gradient(180deg, rgb(var(--hud-surface-alt-rgb) / 0.88), rgb(var(--hud-surface-deep-rgb) / 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;
    }
  }
</style>