<script>
  import { app } from '../lib/stores/app.svelte.js'
  import { getWeatherInfo } from '../lib/api/weather-codes.js'
  import { deleteLocation, setCurrentLocation } from '../lib/storage/db.js'
  import { autofocus } from '../lib/autofocus.js'

  let searchQuery = $state('')
  let searchTimer = null

  function handleSearch(e) {
    const val = e.target.value
    searchQuery = val
    clearTimeout(searchTimer)
    if (val.length >= 2) {
      searchTimer = setTimeout(() => app.searchGeocoding(val), 300)
    } else {
      app.geocodingResults = []
    }
  }

  async function handleDeleteLocation(id) {
    try {
      await deleteLocation(id)
      // If deleting the selected location, select the first remaining
      const locations = await import('../lib/storage/db.js').then(m => m.getLocations())
      if (id === app.selectedLocationId) {
        if (locations.length > 0) {
          await app.selectLocation(locations[0].id)
        } else {
          app.selectedLocationId = null
          app.forecastData = null
        }
      }
      await app.refreshLocations()
    } catch (e) {
      console.error('Failed to delete location:', e)
    }
  }

  function handleSetCurrent(id) {
    if (app.selectedLocation?.isCurrent) return
    setCurrentLocation(id).then(() => app.refreshLocations())
  }

  function openAddLocation() {
    searchQuery = ''
    app.geocodingResults = []
    app.showAddLocation = true
  }

  async function handleSelectGeocoding(result) {
    searchQuery = ''
    app.geocodingResults = []

    const { addLocation } = await import('../lib/storage/db.js')
    await addLocation({
      name: `${result.name}${result.country ? ', ' + result.country : ''}`,
      lat: result.latitude,
      lon: result.longitude,
      isCurrent: false,
    })

    await app.refreshLocations()

    // Select the newly added location
    const locations = await import('../lib/storage/db.js').then(m => m.getLocations())
    const newest = locations[locations.length - 1]
    if (newest) {
      app.selectLocation(newest.id)
    }
  }
</script>

<div class="sidebar-content">
  <div class="sidebar-header">
    <h2>🌤️ WeatherLens</h2>
  </div>

  <!-- Quick geocoding search -->
  <div class="search-box">
    <input
      type="search"
      placeholder="Search locations..."
      value={searchQuery}
      oninput={handleSearch}
      autocomplete="off"
    />
    {#if app.geocodingLoading}
      <span class="search-spinner">⏳</span>
    {/if}

    {#if app.geocodingResults.length > 0}
      <div class="geocoding-dropdown">
        {#each app.geocodingResults as result}
          <button
            class="geocoding-item"
            onclick={() => handleSelectGeocoding(result)}
          >
            <span class="geo-name">{result.name}</span>
            <span class="geo-detail">
              {result.admin1 || ''}{result.country ? ', ' + result.country : ''}
            </span>
          </button>
        {/each}
      </div>
    {/if}
  </div>

  <!-- Saved locations -->
  <nav class="locations-nav">
    {#each app.locations as location}
      {#if location.isCurrent}
        <!-- Current location pinned -->
        <div class="location-row current-row">
          <button
            class="location-item"
            class:active={app.selectedLocationId === location.id}
            onclick={() => app.selectLocation(location.id)}
          >
            <span class="loc-icon">📍</span>
            <span class="loc-name truncate">{location.name}</span>
          </button>
        </div>
      {/if}
    {/each}

    {#each app.locations as location}
      {#if !location.isCurrent}
        <div class="location-row">
          <button
            class="location-item"
            class:active={app.selectedLocationId === location.id}
            onclick={() => app.selectLocation(location.id)}
          >
            <span class="loc-icon">🏙️</span>
            <span class="loc-name truncate">{location.name}</span>
          </button>
          <div class="loc-actions">
            <button
              class="loc-action-btn"
              onclick={() => handleSetCurrent(location.id)}
              title="Set as current location"
            >📍</button>
            <button
              class="loc-action-btn"
              onclick={() => handleDeleteLocation(location.id)}
              title="Remove location"
            >✕</button>
          </div>
        </div>
      {/if}
    {/each}

    {#if app.locations.length === 0}
      <div class="empty-locations">
        <p class="text-muted text-sm">No saved locations.</p>
        <p class="text-muted text-xs mt-1">Enable location access or add one below.</p>
      </div>
    {/if}
  </nav>

  <!-- Footer -->
  <div class="sidebar-footer">
    <button class="btn btn-ghost btn-sm w-full" onclick={() => app.showSettings = true}>
      ⚙️ Settings
    </button>
    <button class="btn btn-primary btn-sm w-full mt-2" onclick={openAddLocation}>
      + Add Location
    </button>
  </div>
</div>

<style>
  .sidebar-content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid var(--color-border);
  }

  .sidebar-header h2 {
    font-size: 1rem;
    font-weight: 700;
  }

  /* Search box */
  .search-box {
    padding: 12px 12px 0;
    position: relative;
  }

  .search-box input {
    padding: 8px 12px;
    font-size: 0.85rem;
    border-radius: var(--radius-md);
  }

  .search-spinner {
    position: absolute;
    right: 22px;
    top: 20px;
    font-size: 0.85rem;
    animation: spin 1s linear infinite;
    pointer-events: none;
  }

  @keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }

  .geocoding-dropdown {
    position: absolute;
    left: 12px;
    right: 12px;
    top: calc(100% - 4px);
    background: var(--color-surface-card);
    border: 1px solid var(--color-border-light);
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-lg);
    z-index: 70;
    max-height: 260px;
    overflow-y: auto;
    margin-top: 4px;
  }

  .geocoding-item {
    display: flex;
    flex-direction: column;
    align-items: stretch;
    width: 100%;
    padding: 10px 14px;
    border: none;
    background: transparent;
    color: var(--color-text);
    text-align: left;
    cursor: pointer;
    transition: background-color var(--transition);
    border-bottom: 1px solid var(--color-border);
  }

  .geocoding-item:last-child {
    border-bottom: none;
  }

  .geocoding-item:hover {
    background: var(--color-surface-hover);
  }

  .geo-name {
    font-size: 0.85rem;
    font-weight: 500;
  }

  .geo-detail {
    font-size: 0.75rem;
    color: var(--color-text-muted);
    margin-top: 2px;
  }

  /* Locations nav */
  .locations-nav {
    flex: 1;
    overflow-y: auto;
    padding: 12px 8px;
  }

  .location-row {
    display: flex;
    align-items: center;
    margin-bottom: 2px;
  }

  .current-row {
    border-bottom: 1px solid var(--color-border);
    padding-bottom: 8px;
    margin-bottom: 8px;
  }

  .location-item {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    min-width: 0;
    padding: 9px 12px;
    border: none;
    border-radius: var(--radius-md);
    background: transparent;
    color: var(--color-text-secondary);
    font-size: 0.88rem;
    cursor: pointer;
    transition: background-color var(--transition), color var(--transition);
    text-align: left;
  }

  .location-item:hover {
    background: var(--color-surface-hover);
    color: var(--color-text);
  }

  .location-item.active {
    background: rgba(56, 189, 248, 0.12);
    color: var(--color-primary);
  }

  .loc-icon {
    font-size: 0.95rem;
    flex-shrink: 0;
  }

  .loc-name {
    flex: 1;
  }

  .loc-actions {
    display: flex;
    gap: 2px;
    padding-right: 4px;
    opacity: 0;
    transition: opacity 150ms;
  }

  .location-row:hover .loc-actions {
    opacity: 1;
  }

  .loc-action-btn {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 0.75rem;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background-color 150ms;
  }

  .loc-action-btn:hover {
    background: var(--color-surface-hover);
  }

  /* Empty state */
  .empty-locations {
    padding: 24px 12px;
    text-align: center;
  }

  /* Footer */
  .sidebar-footer {
    padding: 12px;
    border-top: 1px solid var(--color-border);
  }
</style>
