<script>
  import { getEntries } from '../../stores/entriesStore.svelte.js';
  import TimelineCard from './TimelineCard.svelte';
  import JournalDetail from '../detail/JournalDetail.svelte';
  import EditForm from '../detail/EditForm.svelte';
  import NewEntryForm from '../detail/NewEntryForm.svelte';
  import ShareCard from './ShareCard.svelte';
  import SharePreview from './SharePreview.svelte';

  let { onDetailChange = () => {}, pendingCountry = '', onNewEntryClear = () => {}, onGoToMap = () => {} } = $props();
  let selectedId = $state(/** @type {string|null} */(null));
  let view = $state(/** @type {'list'|'detail'|'edit'|'new'} */('list'));
  let showShare = $state(false);
  let newEntryCountry = $state('');

  // When App passes a country from the map, capture it locally before clearing
  $effect(() => {
    if (pendingCountry) {
      newEntryCountry = pendingCountry;
      selectedId = null;
      view = 'new';
      onNewEntryClear();
    }
  });
  let selected = $derived(selectedId ? (entries.find(e => e.id === selectedId) ?? null) : null);

  let entries = $derived(getEntries());

  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 view === 'new'}
    <div class="detail-scroll">
      <NewEntryForm initialCountry={newEntryCountry} onBack={() => { view = 'list'; newEntryCountry = ''; onDetailChange(false); }} onSaved={() => { onGoToMap(); }} />
    </div>
  {:else if view === 'edit' && selected}
    <div class="detail-scroll">
      <EditForm entry={selected} onBack={() => { view = 'detail'; }} />
    </div>
  {:else if view === 'detail' && selected}
    <div class="detail-scroll">
      <JournalDetail
        entry={selected}
        onBack={() => { selectedId = null; view = 'list'; onDetailChange(false); }}
        onEdit={() => { view = 'edit'; }}
      />
    </div>
  {:else}
    <div class="list-view">
      <div class="page-header">
        <h1 class="page-title">My Journey</h1>
        <button class="new-btn" onclick={() => { view = 'new'; }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
            <path d="M12 5v14M5 12h14"/>
          </svg>
          Add trip
        </button>
      </div>

      <div class="two-col">
        <div class="left-col">
          {#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={() => { selectedId = entry.id; view = 'detail'; onDetailChange(true); }} />
              {/each}
            </ol>
          {/if}

          <footer class="page-footer">
            {sortedEntries.length} {sortedEntries.length === 1 ? 'trip' : 'trips'}
          </footer>
        </div>

        {#if sortedEntries.length > 0}
          <div class="right-col">
            <SharePreview entries={sortedEntries} onClick={() => (showShare = true)} />
          </div>
        {/if}
      </div>
    </div>
  {/if}

</div>

{#if showShare}
  <ShareCard entries={sortedEntries} onClose={() => (showShare = false)} />
{/if}

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

  /* ── List view wrapper (scrollable) ── */
  .list-view {
    flex: 1;
    overflow-y: auto;
    padding: 48px 0 80px;
    box-sizing: border-box;
    min-width: 0;
  }

  .page-header,
  .two-col {
    max-width: 960px;
    margin-left: auto;
    margin-right: auto;
    padding-left: 48px;
    padding-right: 48px;
  }

  /* ── Two-column below header ── */
  .two-col {
    display: flex;
    flex-direction: row;
    gap: 32px;
    align-items: flex-start;
    margin-top: 24px;
  }

  .left-col {
    flex: 1;
    min-width: 0;
  }

  .right-col {
    width: 260px;
    flex-shrink: 0;
    position: sticky;
    top: 0;
  }

  @media (max-width: 900px) {
    .right-col { display: none; }
  }

  @media (max-width: 760px) {
    .list-view { padding: 32px 24px 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-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
  }

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

  .new-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-family: var(--sans);
    font-size: 13px;
    font-weight: 300;
    color: #fff;
    background: var(--accent);
    border: 1px solid var(--accent);
    border-radius: 8px;
    padding: 7px 14px;
    cursor: pointer;
    transition: background 0.15s;
    white-space: nowrap;
    flex-shrink: 0;
  }
  .new-btn:hover { background: var(--accent-dark); border-color: var(--accent-dark); }

</style>
