<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 EditForm from './EditForm.svelte';
  import ShareCard from './ShareCard.svelte';

  let { onDetailChange = () => {}, pendingCountry = '', onNewEntryClear = () => {} } = $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 = $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 view === 'new'}
    <div class="detail-scroll">
      <EditForm initialCountry={newEntryCountry} onBack={() => { view = 'list'; newEntryCountry = ''; onDetailChange(false); }} />
    </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="right-panel">
      <div class="right-inner">
        <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>
            New entry
          </button>
        </div>

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

        {#if sortedEntries.length > 0}
          <button class="share-nudge" onclick={() => (showShare = true)}>
            <span class="nudge-left">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
                <path d="m8.59 13.51 6.83 3.98M15.41 6.51l-6.82 3.98"/>
              </svg>
              Share your journey
            </span>
            <span class="nudge-right">
              {sortedEntries.length} {sortedEntries.length === 1 ? 'trip' : 'trips'} · save as PNG →
            </span>
          </button>
        {/if}

        {#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 ? 'entry' : 'entries'}
        </footer>
      </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;
  }

  /* ── 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-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); }

  .share-nudge {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 10px 14px;
    margin-bottom: 12px;
    border-radius: 10px;
    border: 1px dashed var(--border-bright);
    background: var(--bg-subtle);
    cursor: pointer;
    transition: border-color 0.15s, background 0.15s;
    font-family: var(--sans);
    text-align: left;
  }
  .share-nudge:hover {
    border-color: var(--accent-light);
    background: var(--accent-bg);
  }
  .nudge-left {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    font-size: 13px;
    font-weight: 400;
    color: var(--text-h);
  }
  .nudge-right {
    font-size: 11px;
    font-weight: 300;
    color: var(--text-sub);
    letter-spacing: 0.02em;
  }
  .share-nudge:hover .nudge-right { color: var(--accent); }
</style>
