<script>
  import { getEntries } from './stores/entriesStore.svelte.js';
  import JournalDetail from './JournalDetail.svelte';

  /** @type {Record<string, number>} */
  let selected = $state(null);

  /** @type {Record<string, number>} */
  let photoIdx = $state({});

  let entries = $derived(getEntries());

  const sortOptions = [
    { value: 'date-desc', label: 'Newest First' },
    { value: 'date-asc',  label: 'Oldest First' },
    { value: 'country-asc',  label: 'Country A → Z' },
    { value: 'country-desc', label: 'Country Z → A' },
  ];

  let sortKey = $state('date-desc');

  let sortedEntries = $derived.by(() => {
    const key = sortKey;
    return [...entries].sort((a, b) => {
      if (key === 'date-asc')     return a.date.localeCompare(b.date);
      if (key === 'date-desc')    return b.date.localeCompare(a.date);
      if (key === 'country-asc')  return (a.countryName || '').localeCompare(b.countryName || '') || b.date.localeCompare(a.date);
      if (key === 'country-desc') return (b.countryName || '').localeCompare(a.countryName || '') || b.date.localeCompare(a.date);
      return 0;
    });
  });

  function formatDate(/** @type {string} */ iso) {
    return new Date(iso).toLocaleDateString('en-US', {
      year: 'numeric', month: 'short', day: 'numeric',
    });
  }

  function stepPhoto(/** @type {string} */ id, /** @type {number} */ total, /** @type {1|-1} */ dir, /** @type {Event} */ e) {
    e.stopPropagation();
    const cur = photoIdx[id] ?? 0;
    photoIdx = { ...photoIdx, [id]: (cur + dir + total) % total };
  }

  function setPhoto(/** @type {string} */ id, /** @type {number} */ i, /** @type {Event} */ e) {
    e.stopPropagation();
    photoIdx = { ...photoIdx, [id]: i };
  }

  function tripType(/** @type {string[] | undefined} */ companions) {
    if (!companions || companions.length === 0 || (companions.length === 1 && companions[0] === 'solo')) return 'solo';
    return 'friends';
  }

  function companionText(/** @type {string[] | undefined} */ companions) {
    if (!companions || companions.length === 0 || (companions.length === 1 && companions[0] === 'solo')) return 'Solo';
    return companions.join(', ');
  }

  const TRANSPORT_LABELS = {
    plane: '✈️ Plane',
    car: '🚗 Car',
    train: '🚆 Train',
    boat: '⛵ Boat',
    bus: '🚌 Bus',
    other: 'Other',
  };
</script>

{#if selected}
  <JournalDetail entry={selected} onBack={() => (selected = null)} />
{:else}
  <section class="timeline-view">

    <header class="toolbar">
      <div class="title-block">
        <p class="eyebrow">Travel Journal</p>
        <h1 class="page-title">My Journey</h1>
      </div>
      <div class="sort-control">
        <label for="sort-select">Sort</label>
        <select id="sort-select" onchange={(e) => (sortKey = e.currentTarget.value)}>
          {#each sortOptions as opt}
            <option value={opt.value} selected={opt.value === sortKey}>{opt.label}</option>
          {/each}
        </select>
      </div>
    </header>

    {#if sortedEntries.length === 0}
      <p class="empty">No journal entries yet.</p>
    {:else}
      <ol class="v-list">
        {#each sortedEntries as entry (entry.id)}
          {@const idx = photoIdx[entry.id] ?? 0}
          <li class="v-item">
            <div class="v-dot" aria-hidden="true"></div>
            <div class="v-entry-wrap">
              <div class="above-card">
                <time class="above-date" datetime={entry.date}>{formatDate(entry.date)}</time>
                <span class="above-sep">·</span>
                <span class="above-loc">{entry.city}, {entry.countryName}</span>
                <span class="above-sep">·</span>
                <span class="above-days">{entry.days} {entry.days === 1 ? 'day' : 'days'}</span>
              </div>
              <div class="entry-card" role="button" tabindex="0"
                onclick={() => (selected = entry)}
                onkeydown={(e) => e.key === 'Enter' && (selected = entry)}>

                {#if entry.photos?.length > 0}
                  <div class="gallery">
                    <img class="gallery-main" src={entry.photos[idx]}
                      alt="{entry.title} photo {idx + 1}" loading="lazy" />
                    {#if entry.photos.length > 1}
                      <button class="gallery-arrow left"
                        onclick={(e) => stepPhoto(entry.id, entry.photos.length, -1, e)}
                        aria-label="Previous photo">‹</button>
                      <button class="gallery-arrow right"
                        onclick={(e) => stepPhoto(entry.id, entry.photos.length, 1, e)}
                        aria-label="Next photo">›</button>
                      <div class="gallery-dots">
                        {#each entry.photos as _, i}
                          <button class="gallery-pip" class:active={i === idx}
                            onclick={(e) => setPhoto(entry.id, i, e)}
                            aria-label="Photo {i + 1}"></button>
                        {/each}
                      </div>
                    {/if}
                  </div>
                {/if}

                <div class="entry-body">
                  <h2 class="entry-title">{entry.title}</h2>
                  {#if entry.memo}
                    <p class="entry-memo">{entry.memo}</p>
                  {/if}
                  <div class="entry-song">
                    {#if entry.transportation && TRANSPORT_LABELS[entry.transportation]}
                      <span class="transport-badge">{TRANSPORT_LABELS[entry.transportation]}</span>
                    {/if}
                    <svg class="song-icon" width="13" height="13" viewBox="0 0 24 24" fill="none">
                      <path d="M9 18V5l12-2v13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                      <circle cx="6" cy="18" r="3" stroke="currentColor" stroke-width="2"/>
                      <circle cx="18" cy="16" r="3" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    <span class="song-title">{entry.song?.title || ''}</span>
                    <span class="song-sep">·</span>
                    <span class="song-artist">{entry.song?.artist || ''}</span>
                    <span class="trip-badge" class:trip-badge--solo={tripType(entry.companions) === 'solo'} class:trip-badge--friends={tripType(entry.companions) === 'friends'}>
                      {companionText(entry.companions)}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </li>
        {/each}
      </ol>
    {/if}

    <footer class="page-footer">
      {sortedEntries.length} {sortedEntries.length === 1 ? 'entry' : 'entries'}
    </footer>
  </section>
{/if}

<style>
  .timeline-view {
    max-width: 600px;
    margin: 0 auto;
    padding: 48px 24px 64px;
    font-family: var(--sans, system-ui, sans-serif);
  }

  .toolbar {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 48px;
    padding-bottom: 24px;
    border-bottom: 1px solid var(--border, #e5e4e7);
  }

  .eyebrow {
    font-size: 11px;
    letter-spacing: 3px;
    text-transform: uppercase;
    color: var(--accent, #aa3bff);
    margin: 0 0 6px;
  }

  .page-title {
    font-size: 32px;
    font-weight: 700;
    color: var(--text-h, #08060d);
    margin: 0;
    letter-spacing: -0.8px;
  }

  .sort-control { display: flex; align-items: center; gap: 8px; }
  .sort-control label { font-size: 13px; color: var(--text, #6b6375); }

  select {
    font-size: 13px;
    padding: 7px 28px 7px 10px;
    border: 1px solid var(--border, #e5e4e7);
    border-radius: 8px;
    background: var(--bg, #fff);
    color: var(--text-h, #08060d);
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' fill='none'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%236b6375' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 10px center;
  }
  select:focus { outline: 2px solid var(--accent, #aa3bff); outline-offset: 2px; }

  .above-card {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-wrap: wrap;
    margin-bottom: 8px;
  }
  .above-date { font-size: 12px; font-weight: 500; color: var(--text-h, #08060d); }
  .above-loc, .above-days { font-size: 12px; color: var(--text, #6b6375); }
  .above-sep { font-size: 11px; color: var(--border, #c8c6cc); user-select: none; }

  .entry-card {
    display: block;
    width: 100%;
    box-sizing: border-box;
    border: 1px solid var(--border, #e5e4e7);
    border-radius: 14px;
    overflow: hidden;
    background: var(--bg, #fff);
    cursor: pointer;
    transition: box-shadow 0.2s, transform 0.15s;
    text-align: left;
  }
  .entry-card:hover {
    box-shadow: 0 6px 24px rgba(0,0,0,0.1);
    transform: translateY(-2px);
  }

  .entry-body { padding: 14px 18px 18px; }

  .entry-song { gap: 5px; }
  .entry-song .trip-badge { margin-left: auto; flex-shrink: 0; }

  .trip-badge {
    display: inline-block;
    font-size: 11px;
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 20px;
  }
  .trip-badge--solo    { background: rgba(245,158,11,0.12); color: #b45309; }
  .trip-badge--friends { background: rgba(59,130,246,0.12); color: #1d4ed8; }

  .transport-badge {
    font-size: 11px;
    font-weight: 500;
    color: #6b6375;
    flex-shrink: 0;
  }

  .entry-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-h, #08060d);
    margin: 0 0 6px;
    letter-spacing: -0.2px;
  }

  .entry-memo {
    font-size: 13px;
    line-height: 1.6;
    color: var(--text, #6b6375);
    margin: 0 0 10px;
  }

  .entry-song {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
    color: var(--text, #6b6375);
    padding-top: 10px;
    border-top: 1px solid var(--border, #e5e4e7);
  }
  .song-icon { flex-shrink: 0; color: var(--accent, #aa3bff); }
  .song-title { font-weight: 500; color: var(--text-h, #08060d); }
  .song-sep { opacity: 0.35; }

  .gallery { position: relative; overflow: hidden; background: #000; }
  .gallery-main { width: 100%; height: 220px; object-fit: cover; display: block; }

  .gallery-arrow {
    position: absolute; top: 50%; transform: translateY(-50%);
    background: rgba(0,0,0,0.45); color: #fff;
    border: none; width: 32px; height: 32px; border-radius: 50%;
    font-size: 20px; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    transition: background 0.15s; z-index: 2;
  }
  .gallery-arrow:hover { background: rgba(0,0,0,0.7); }
  .gallery-arrow.left  { left: 10px; }
  .gallery-arrow.right { right: 10px; }

  .gallery-dots {
    position: absolute; bottom: 8px; left: 50%;
    transform: translateX(-50%);
    display: flex; gap: 5px; z-index: 2;
  }
  .gallery-pip {
    width: 6px; height: 6px; border-radius: 50%;
    border: none; background: rgba(255,255,255,0.5);
    cursor: pointer; padding: 0;
    transition: background 0.15s, transform 0.15s;
  }
  .gallery-pip.active { background: #fff; transform: scale(1.3); }

  .v-list { list-style: none; padding: 0; margin: 0; position: relative; }
  .v-list::before {
    content: '';
    position: absolute; left: 10px; top: 6px; bottom: 6px;
    width: 2px; background: var(--border, #e5e4e7); border-radius: 1px;
  }

  .v-item { display: flex; gap: 24px; align-items: flex-start; padding-bottom: 36px; }
  .v-item:last-child { padding-bottom: 0; }

  .v-dot {
    flex-shrink: 0; width: 22px; height: 22px; border-radius: 50%;
    background: var(--accent, #aa3bff);
    border: 3px solid var(--bg, #fff);
    box-shadow: 0 0 0 2px var(--accent, #aa3bff);
    margin-top: 28px; z-index: 1;
  }

  .v-entry-wrap { flex: 1; display: flex; flex-direction: column; }

  .page-footer {
    margin-top: 40px;
    text-align: center;
    font-size: 13px;
    color: var(--text, #6b6375);
    padding-top: 24px;
    border-top: 1px solid var(--border, #e5e4e7);
  }

  .empty { text-align: center; color: var(--text, #6b6375); padding: 80px 0; }

  @media (max-width: 600px) {
    .timeline-view { padding: 32px 16px 48px; }
    .page-title { font-size: 26px; }
    .v-list::before { left: 8px; }
    .v-dot { width: 18px; height: 18px; }
    .v-item { gap: 16px; }
    .gallery-main { height: 180px; }
  }
</style>
