<script lang="ts">
  interface Props {
    value: number; // 0-1
    onchange?: (value: number) => void;
  }

  let { value = $bindable(0.75), onchange }: Props = $props();

  let volume = $state(value * 100); // Internal state as 0-100
  let isDragging = $state(false);
  let dragOffset = $state(0);
  let triangleContainer: HTMLDivElement;
  let volumeThumb: HTMLDivElement;

  const triangleWidth = 60;

  // Sync external value (0-1) with internal volume (0-100)
  $effect(() => {
    volume = value * 100;
  });

  function updateVolume(percentage: number) {
    volume = Math.max(0, Math.min(100, percentage));
    const newValue = volume / 100;
    value = newValue;
    if (onchange) {
      onchange(newValue);
    }
  }

  function getVolumeFromPosition(clientX: number, useOffset: boolean = false): number {
    const rect = triangleContainer.getBoundingClientRect();
    let x = clientX - rect.left;

    if (useOffset) {
      x = x - dragOffset;
    }

    const percentage = (x / rect.width) * 100;
    return percentage;
  }

  function handleThumbMouseDown(e: MouseEvent) {
    isDragging = true;

    const rect = triangleContainer.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const currentThumbPosition = (volume / 100) * rect.width;

    dragOffset = clickX - currentThumbPosition;

    e.stopPropagation();
    e.preventDefault();
  }

  function handleContainerMouseDown(e: MouseEvent) {
    if (e.target !== volumeThumb) {
      dragOffset = 0;
      const newVolume = getVolumeFromPosition(e.clientX);
      updateVolume(newVolume);
      isDragging = true;
    }
  }

  function handleMouseMove(e: MouseEvent) {
    if (isDragging) {
      const newVolume = getVolumeFromPosition(e.clientX, true);
      updateVolume(newVolume);
    }
  }

  function handleMouseUp() {
    isDragging = false;
    dragOffset = 0;
  }

  function handleThumbTouchStart(e: TouchEvent) {
    isDragging = true;

    const touch = e.touches[0];
    const rect = triangleContainer.getBoundingClientRect();
    const currentThumbPosition = (volume / 100) * rect.width;
    dragOffset = (touch.clientX - rect.left) - currentThumbPosition;

    e.preventDefault();
  }

  function handleContainerTouchStart(e: TouchEvent) {
    if (e.target !== volumeThumb) {
      const touch = e.touches[0];
      dragOffset = 0;
      const newVolume = getVolumeFromPosition(touch.clientX, false);
      updateVolume(newVolume);
      isDragging = true;
    }
    e.preventDefault();
  }

  function handleTouchMove(e: TouchEvent) {
    if (isDragging) {
      const touch = e.touches[0];
      const newVolume = getVolumeFromPosition(touch.clientX, true);
      updateVolume(newVolume);
    }
  }

  function handleTouchEnd() {
    isDragging = false;
  }

  function handleDecrease() {
    updateVolume(volume - 5);
  }

  function handleIncrease() {
    updateVolume(volume + 5);
  }

  const position = $derived((volume / 100) * triangleWidth);
  const rightEdge = $derived(volume);
</script>

<svelte:window onmousemove={handleMouseMove} onmouseup={handleMouseUp} ontouchmove={handleTouchMove} ontouchend={handleTouchEnd} />

<div class="volume-container">
  <button class="volume-icons" onclick={handleDecrease} aria-label="Decrease volume">−</button>

  <div class="triangle-wrapper">
    <div
      class="triangle-container"
      bind:this={triangleContainer}
      onmousedown={handleContainerMouseDown}
      ontouchstart={handleContainerTouchStart}
      role="slider"
      aria-valuemin="0"
      aria-valuemax="100"
      aria-valuenow={Math.round(value * 100)}
      tabindex="0"
    >
      <div class="triangle-bg"></div>
      <div
        class="triangle-fill"
        style="clip-path: inset(0 {100 - rightEdge}% 0 0);"
      ></div>
      <div
        class="volume-thumb"
        style="left: {position}px;"
        bind:this={volumeThumb}
        onmousedown={handleThumbMouseDown}
        ontouchstart={handleThumbTouchStart}
        role="button"
        tabindex="-1"
        aria-label="Volume slider thumb"
      >
        <div class="volume-thumb-inner"></div>
      </div>
    </div>
  </div>

  <button class="volume-icons" onclick={handleIncrease} aria-label="Increase volume">+</button>
</div>

<style>
  .volume-container {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .volume-icons {
    font-size: 12px;
    color: light-dark(#000, #fff);
    user-select: none;
    padding: 2px 6px;
    min-width: auto;
    min-height: auto;
    font-weight: bold;
  }

  .triangle-wrapper {
    position: relative;
    width: 60px;
    height: 16px;
    flex: 1;
    max-width: 60px;
  }

  .triangle-container {
    position: relative;
    width: 60px;
    height: 100%;
    cursor: pointer;
  }

  .triangle-bg {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 0;
    height: 0;
    border-left: 60px solid transparent;
    border-right: 0 solid transparent;
    border-bottom: 16px solid light-dark(#808080, #525252);
  }

  .triangle-fill {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 0;
    height: 0;
    border-left: 60px solid transparent;
    border-right: 0 solid transparent;
    border-bottom: 16px solid light-dark(#000080, #0066cc);
    transition: clip-path 0.05s ease-out;
  }

  .volume-thumb {
    position: absolute;
    bottom: -2px;
    width: 8px;
    height: 16px;
    background: light-dark(#c0c0c0, #2b2b2b);
    border-top: 1px solid light-dark(#ffffff, #525252);
    border-left: 1px solid light-dark(#ffffff, #525252);
    border-right: 1px solid light-dark(#000000, #000);
    border-bottom: 1px solid light-dark(#000000, #000);
    box-shadow: inset 1px 1px 0 light-dark(#dfdfdf, #363636),
                inset -1px -1px 0 light-dark(#808080, #232323);
    cursor: grab;
    transform: translateX(-4px);
    z-index: 10;
  }

  .volume-thumb:active {
    cursor: grabbing;
    border-top: 1px solid light-dark(#000000, #000);
    border-left: 1px solid light-dark(#000000, #000);
    border-right: 1px solid light-dark(#ffffff, #525252);
    border-bottom: 1px solid light-dark(#ffffff, #525252);
  }

  .volume-thumb-inner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 4px;
    height: 10px;
    background: linear-gradient(
      to right,
      light-dark(#dfdfdf, #363636) 0%,
      light-dark(#c0c0c0, #2b2b2b) 50%,
      light-dark(#808080, #232323) 100%
    );
  }
</style>
