<script>
  import { getUser, getUserProfile, setHomeCountry } from './userStore.svelte.js';
  import worldData from 'world-atlas/countries-50m.json';

  let user = $derived(getUser());
  let profile = $derived(getUserProfile());

  const countries = $derived.by(() => {
    if (!worldData?.objects?.countries?.geometries) return [];
    return worldData.objects.countries.geometries
      .map(g => ({ name: g.properties?.name, code: g.id }))
      .filter(c => c.name && c.code)
      .sort((a, b) => a.name.localeCompare(b.name));
  });

  let search = $state('');
  let selectedCountry = $state(null);

  let filtered = $derived(
    search
      ? countries.filter(c => c.name.toLowerCase().includes(search.toLowerCase()))
      : countries
  );

  let open = $state(false);

  function select(c) {
    selectedCountry = c;
    search = c.name;
    open = false;
  }

  function handleSubmit() {
    if (selectedCountry) {
      setHomeCountry(selectedCountry.name, selectedCountry.code);
    }
  }

  function handleKeydown(e) {
    if (e.key === 'Enter' && selectedCountry) {
      handleSubmit();
    }
    if (e.key === 'Escape') {
      open = false;
    }
  }
</script>

<div class="overlay">
  <div class="card">
    <h1 class="heading">Welcome, {profile?.displayName || 'Traveler'}!</h1>
    <p class="subtitle">Select your home country to get started</p>

    <div class="dropdown" class:open>
      <input
        type="text"
        placeholder="Search for a country..."
        bind:value={search}
        onfocus={() => { open = true; }}
        oninput={() => { open = true; selectedCountry = null; }}
        onkeydown={handleKeydown}
        class="search-input"
      />
      {#if open}
        <ul class="list" role="listbox">
          {#each filtered as country}
            <li
              role="option"
              aria-selected={selectedCountry?.name === country.name}
              class:selected={selectedCountry?.name === country.name}
              onclick={() => select(country)}
              onkeydown={(e) => { if (e.key === 'Enter') select(country); }}
              tabindex="0"
            >
              {country.name}
            </li>
          {/each}
          {#if filtered.length === 0}
            <li class="no-results">No countries found</li>
          {/if}
        </ul>
      {/if}
    </div>

    <button
      class="continue-btn"
      disabled={!selectedCountry}
      onclick={handleSubmit}
    >
      Continue
    </button>
  </div>
</div>

<style>
  .overlay {
    position: fixed;
    inset: 0;
    background: rgba(15, 23, 42, 0.85);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
    backdrop-filter: blur(4px);
  }

  .card {
    background: #1e2937;
    border-radius: 16px;
    padding: 40px 36px;
    text-align: center;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
    max-width: 420px;
    width: 90%;
  }

  .heading {
    font: 700 24px/1.3 sans-serif;
    color: #f1f5f9;
    margin-bottom: 6px;
  }

  .subtitle {
    font: 400 15px/1.4 sans-serif;
    color: #94a3b8;
    margin-bottom: 28px;
  }

  .dropdown {
    position: relative;
    margin-bottom: 24px;
    text-align: left;
  }

  .search-input {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid #475569;
    border-radius: 8px;
    background: #0f172a;
    color: #f1f5f9;
    font: 400 15px/1.4 sans-serif;
    outline: none;
    transition: border-color 0.2s;
  }

  .search-input:focus {
    border-color: #3b82f6;
  }

  .search-input::placeholder {
    color: #64748b;
  }

  .list {
    position: absolute;
    top: calc(100% + 4px);
    left: 0;
    right: 0;
    max-height: 240px;
    overflow-y: auto;
    background: #0f172a;
    border: 1px solid #475569;
    border-radius: 8px;
    list-style: none;
    z-index: 10;
  }

  .list li {
    padding: 10px 16px;
    cursor: pointer;
    color: #cbd5e1;
    font: 400 14px/1.4 sans-serif;
    transition: background 0.15s;
  }

  .list li:hover,
  .list li.selected {
    background: #1e3a5f;
    color: #f1f5f9;
  }

  .no-results {
    color: #64748b;
    cursor: default;
  }

  .continue-btn {
    width: 100%;
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    background: #3b82f6;
    color: #fff;
    font: 600 16px/1.4 sans-serif;
    cursor: pointer;
    transition: background 0.2s, opacity 0.2s;
  }

  .continue-btn:hover:not(:disabled) {
    background: #2563eb;
  }

  .continue-btn:disabled {
    opacity: 0.4;
    cursor: default;
  }
</style>
