<script lang="ts">
  import { prefs, setPref, syncPrefsToRemote } from "$lib/prefs.svelte";
  import { auth } from "$lib/auth.svelte";

  let { open = $bindable(false) } = $props();

  const ACCENT_PRESETS = [
    { name: "indigo", color: "#6366f1" },
    { name: "emerald", color: "#10b981" },
    { name: "amber", color: "#f59e0b" },
    { name: "rose", color: "#f43f5e" },
    { name: "cyan", color: "#06b6d4" },
    { name: "violet", color: "#8b5cf6" },
  ];

  const FONT_PRESETS = [
    { name: "system", value: "system-ui" },
    { name: "mono", value: "ui-monospace, monospace" },
    { name: "serif", value: "ui-serif, serif" },
    { name: "sans", value: "ui-sans-serif, sans-serif" },
  ];

  const handleAccentChange = (color: string) => {
    setPref("accentColor", color);
  };

  const handleFontChange = (font: string) => {
    setPref("font", font);
  };

  let syncStatus = $state<"idle" | "saving" | "saved" | "error">("idle");

  const handleSync = async () => {
    syncStatus = "saving";
    try {
      await syncPrefsToRemote();
      syncStatus = "saved";
      setTimeout(() => syncStatus = "idle", 2000);
    } catch (e) {
      console.error("sync failed:", e);
      syncStatus = "error";
      setTimeout(() => syncStatus = "idle", 2000);
    }
  };

  const handleClose = () => {
    open = false;
  };

  const handleKeydown = (e: KeyboardEvent) => {
    if (!open) return;
    if (e.key === "Escape") {
      e.preventDefault();
      handleClose();
    }
  };
</script>

<svelte:window onkeydown={handleKeydown} />

{#if open}
  <div
    class="overlay"
    onclick={handleClose}
    onkeydown={handleKeydown}
    role="dialog"
    aria-modal="true"
    tabindex="-1"
  >
    <!-- svelte-ignore a11y_click_events_have_key_events a11y_no_noninteractive_element_interactions -->
    <div class="panel" onclick={(e) => e.stopPropagation()} role="document">
      <div class="header">
        <h3>settings</h3>
        <button class="close-btn" onclick={handleClose}>×</button>
      </div>

      <div class="section">
        <span class="label">accent color</span>
        <div class="swatches">
          {#each ACCENT_PRESETS as preset (preset.color)}
            <button
              class="swatch"
              class:active={prefs.accentColor === preset.color}
              style="background: {preset.color}"
              onclick={() => handleAccentChange(preset.color)}
              title={preset.name}
            ></button>
          {/each}
          <input
            type="color"
            class="color-picker"
            value={prefs.accentColor}
            oninput={(e) => handleAccentChange((e.target as HTMLInputElement).value)}
          />
        </div>
      </div>

      <div class="section">
        <span class="label">font</span>
        <div class="font-options">
          {#each FONT_PRESETS as preset (preset.value)}
            <button
              class="font-btn"
              class:active={prefs.font === preset.value}
              style="font-family: {preset.value}"
              onclick={() => handleFontChange(preset.value)}
            >
              {preset.name}
            </button>
          {/each}
        </div>
      </div>

      {#if auth.loggedIn}
        <div class="section">
          <button class="sync-btn" onclick={handleSync} disabled={syncStatus === "saving"}>
            {#if syncStatus === "saving"}
              saving...
            {:else if syncStatus === "saved"}
              saved!
            {:else if syncStatus === "error"}
              failed
            {:else}
              save preferences
            {/if}
          </button>
          <p class="hint">synced across your devices</p>
        </div>
      {/if}
    </div>
  </div>
{/if}

<style>
  .overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }

  .panel {
    background: #141414;
    border: 1px solid #333;
    border-radius: 12px;
    padding: 20px;
    min-width: 280px;
    max-width: 360px;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
    color: #fff;
  }

  .close-btn {
    background: transparent;
    border: none;
    color: #666;
    font-size: 24px;
    cursor: pointer;
    padding: 0;
    line-height: 1;
  }

  .close-btn:hover {
    color: #fff;
  }

  .section {
    margin-bottom: 20px;
  }

  .section:last-child {
    margin-bottom: 0;
  }

  .label {
    display: block;
    font-size: 12px;
    color: #888;
    margin-bottom: 8px;
    text-transform: lowercase;
  }

  .swatches {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
  }

  .swatch {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    border: 2px solid transparent;
    cursor: pointer;
    transition: all 0.15s ease;
  }

  .swatch:hover {
    transform: scale(1.1);
  }

  .swatch.active {
    border-color: #fff;
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.2);
  }

  .color-picker {
    width: 28px;
    height: 28px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    background: transparent;
    padding: 0;
  }

  .color-picker::-webkit-color-swatch-wrapper {
    padding: 0;
  }

  .color-picker::-webkit-color-swatch {
    border: 2px dashed #444;
    border-radius: 6px;
  }

  .font-options {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .font-btn {
    padding: 6px 12px;
    background: #1a1a1a;
    border: 1px solid #333;
    border-radius: 6px;
    color: #ccc;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.15s ease;
  }

  .font-btn:hover {
    background: #252525;
    border-color: #444;
  }

  .font-btn.active {
    border-color: var(--accent, #6366f1);
    color: var(--accent, #6366f1);
  }

  .sync-btn {
    width: 100%;
    padding: 10px;
    background: var(--accent, #6366f1);
    border: none;
    border-radius: 6px;
    color: #fff;
    font-size: 13px;
    cursor: pointer;
    transition: opacity 0.15s ease;
  }

  .sync-btn:hover {
    opacity: 0.9;
  }

  .hint {
    margin: 8px 0 0;
    font-size: 11px;
    color: #666;
    text-align: center;
  }
</style>
