<script>
  import { get } from 'svelte/store';
  import { journals } from '../stores/journalStore.js';
  import TimelineToolbar from './TimelineToolbar.svelte';
  import TimelineCard from './TimelineCard.svelte';
  import JournalDetail from './JournalDetail.svelte';
  import JournalSummary from './JournalSummary.svelte';

  /** @type {import('../stores/journalStore.js').JournalEntry|null} */
  let { onDetailChange = () => {} } = $props();
  let selected = $state(null);

  let entries = $state(get(journals));
  $effect(() => {
    const unsub = journals.subscribe((v) => { entries = v; });
    return unsub;
  });

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

  let sortedEntries = $state(/** @type {typeof entries} */([]));
  $effect(() => {
    const key = sortKey;
    sortedEntries = [...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.location.country.localeCompare(b.location.country) || b.date.localeCompare(a.date);
      if (key === 'country-desc') return b.location.country.localeCompare(a.location.country) || b.date.localeCompare(a.date);
      return 0;
    });
  });

  function getYear(iso) {
    return new Date(iso).getFullYear();
  }
</script>

<div class="journal-page">

  {#if selected}
    <div class="detail-scroll">
      <JournalDetail entry={selected} onBack={() => { selected = null; onDetailChange(false); }} />
    </div>
  {:else}
    <div class="right-panel">
      <div class="right-inner">
        <h1 class="page-title">My Journey</h1>

        <JournalSummary entries={sortedEntries} />

        <TimelineToolbar {sortKey} onSort={(k) => (sortKey = k)} />

        {#if sortedEntries.length === 0}
          <p class="empty">No journal entries yet.</p>
        {:else}
          <div class="sort-row">
            <span class="sort-label">Sort by</span>
            <select class="sort-select" onchange={(e) => (sortKey = e.currentTarget.value)}>
              <option value="date-desc" selected={sortKey === 'date-desc'}>Newest first</option>
              <option value="date-asc"  selected={sortKey === 'date-asc'}>Oldest first</option>
              <option value="country-asc"  selected={sortKey === 'country-asc'}>Country A → Z</option>
              <option value="country-desc" selected={sortKey === 'country-desc'}>Country Z → A</option>
            </select>
          </div>
          <ol class="v-list">
            {#each sortedEntries as entry, i (entry.id)}
              {#if i === 0 || getYear(entry.date) !== getYear(sortedEntries[i - 1].date)}
                <li class="year-marker" aria-hidden="true">
                  <span class="year-label">{getYear(entry.date)}</span>
                </li>
              {/if}
              <TimelineCard {entry} onClick={() => { selected = entry; onDetailChange(true); }} />
            {/each}
          </ol>
        {/if}

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

</div>

<style>
  .journal-page {
    flex: 1;
    display: flex;
    flex-direction: row;
    min-width: 0;
    height: 100%;
    overflow: hidden;
  }

  /* ── Left panel ── */
  .left-panel {
    width: 260px;
    flex-shrink: 0;
    overflow-y: auto;
    border-right: 1px solid var(--border);
    background: var(--bg-raised);
    padding: 40px 28px;
  }

  /* ── Right panel ── */
  .right-panel {
    flex: 1;
    min-width: 0;
    overflow-y: auto;
    background: var(--bg);
  }

  /* Inner container with max-width + generous side padding */
  .right-inner {
    max-width: 640px;
    margin: 0 auto;
    padding: 40px 48px 80px;
  }

  /* ── Responsive: narrow viewport ── */
  @media (max-width: 700px) {
    .journal-page { flex-direction: column; overflow-y: auto; overflow-x: hidden; }
    .left-panel {
      width: 100%;
      border-right: none;
      border-bottom: 1px solid var(--border);
      padding: 24px 20px;
    }
    .right-panel { overflow-y: unset; }
    .right-inner { padding: 24px 20px 60px; }
  }

  /* ── Detail view ── */
  .detail-scroll {
    flex: 1;
    overflow-y: auto;
    background: var(--bg);
  }

  /* ── Timeline list ── */
  .v-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 0;
  }

  /* Year marker */
  .year-marker {
    padding: 24px 0 14px;
  }
  .year-label {
    font-size: 18px;
    font-weight: 600;
    letter-spacing: 0.04em;
    color: #7c3aed;
    border-left: 3px solid #7c3aed;
    padding-left: 12px;
  }

  .page-footer {
    margin-top: 56px;
    text-align: center;
    font-size: 11px;
    font-weight: 300;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    color: var(--text-sub);
    padding-top: 24px;
    border-top: 1px solid var(--border);
  }

  .empty { text-align: center; color: var(--text-sub); padding: 80px 0; }

  .sort-row {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 8px;
    margin-bottom: 8px;
    padding-top: 20px;
  }
  .sort-label {
    font-size: 11px;
    font-weight: 400;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: var(--text-sub);
  }
  .sort-select {
    font-family: var(--sans);
    font-size: 11px;
    font-weight: 300;
    letter-spacing: 0.04em;
    padding: 4px 24px 4px 10px;
    border: 1px solid var(--border);
    border-radius: 6px;
    background: var(--bg-subtle);
    color: var(--text);
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' fill='none'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%2352525b' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 8px center;
  }
  .sort-select:hover { border-color: var(--border-bright); color: var(--text-h); }

  .page-title {
    font-size: var(--text-xl);
    font-weight: 400;
    color: var(--text-h);
    letter-spacing: -0.5px;
    margin: 0 0 16px;
  }
</style>
