<script lang="ts">
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import CreateTripModal from '$lib/components/trips/CreateTripModal.svelte';

  let createOpen = $state(false);

  interface Trip {
    id: string;
    name: string;
    dates: string;
    daysAway: string;
    status: 'active' | 'upcoming' | 'completed';
    cover: string;
    duration: string;
    cities: string[];
    points?: number;
    cash?: number;
    shareToken?: string;
    sortDate: string;
  }

  let searchQuery = $state('');
  let upcoming = $state<Trip[]>([]);
  let past = $state<Trip[]>([]);
  let stats = $state({ trips: 0, cities: 0, countries: 0, points: 0 });
  let loading = $state(true);

  const allTrips = $derived([...upcoming, ...past]);

  const filteredTrips = $derived(
    searchQuery.trim()
      ? allTrips.filter((t) =>
          t.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          t.cities.some((c) => c.toLowerCase().includes(searchQuery.toLowerCase()))
        )
      : null
  );

  function formatPoints(n: number): string {
    if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
    if (n >= 1000) return Math.round(n / 1000) + 'K';
    return n.toString();
  }

  function formatDateRange(start: string, end: string): string {
    if (!start) return '';
    const s = new Date(start + 'T00:00:00');
    const e = new Date(end + 'T00:00:00');
    const sMonth = s.toLocaleDateString('en-US', { month: 'short' });
    const eMonth = e.toLocaleDateString('en-US', { month: 'short' });
    const sYear = s.getFullYear();
    const eYear = e.getFullYear();
    if (sMonth === eMonth && sYear === eYear) {
      return `${sMonth} ${s.getDate()} – ${e.getDate()}, ${sYear}`;
    }
    if (sYear === eYear) {
      return `${sMonth} ${s.getDate()} – ${eMonth} ${e.getDate()}, ${sYear}`;
    }
    return `${sMonth} ${s.getDate()}, ${sYear} – ${eMonth} ${e.getDate()}, ${eYear}`;
  }

  function daysBetween(dateStr: string): string {
    const d = new Date(dateStr + 'T00:00:00');
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const diff = Math.ceil((d.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
    if (diff <= 0) return '';
    if (diff === 1) return '1 day';
    return `${diff} days`;
  }

  function durationDays(start: string, end: string): string {
    if (!start || !end) return '';
    const s = new Date(start + 'T00:00:00');
    const e = new Date(end + 'T00:00:00');
    const days = Math.ceil((e.getTime() - s.getTime()) / (1000 * 60 * 60 * 24)) + 1;
    return `${days} days`;
  }

  function coverUrl(trip: any): string {
    if (trip.cover_image) return trip.cover_image;
    return '';
  }

  function mapTrip(raw: any): Trip {
    const now = new Date().toISOString().slice(0, 10);
    const isActive = raw.start_date <= now && raw.end_date >= now;
    const isUpcoming = raw.start_date > now;
    return {
      id: raw.id,
      name: raw.name,
      dates: formatDateRange(raw.start_date, raw.end_date),
      daysAway: isUpcoming ? daysBetween(raw.start_date) : '',
      status: isActive ? 'active' : isUpcoming ? 'upcoming' : 'completed',
      cover: coverUrl(raw),
      duration: durationDays(raw.start_date, raw.end_date),
      cities: [],
      points: 0,
      cash: 0,
      shareToken: raw.share_token || '',
      sortDate: raw.start_date || ''
    };
  }

  onMount(async () => {
    try {
      const [tripsRes, statsRes] = await Promise.all([
        fetch('/api/trips/trips', { credentials: 'include' }),
        fetch('/api/trips/stats', { credentials: 'include' })
      ]);

      if (tripsRes.ok) {
        const data = await tripsRes.json();
        const all = (data.trips || []).map(mapTrip);
        upcoming = all
          .filter((t) => t.status === 'active' || t.status === 'upcoming')
          .sort((a, b) => a.sortDate.localeCompare(b.sortDate));
        past = all
          .filter((t) => t.status === 'completed')
          .sort((a, b) => b.sortDate.localeCompare(a.sortDate));
      }

      if (statsRes.ok) {
        const data = await statsRes.json();
        stats = {
          trips: data.total_trips || 0,
          cities: data.cities_visited || 0,
          countries: data.countries_visited || 0,
          points: data.total_points_redeemed || 0
        };
      }
    } catch {
      // keep route stable
    } finally {
      loading = false;
    }
  });
</script>

<div class="page">
  <div class="app-surface">
    <div class="header-row">
      <div>
        <div class="page-title">TRIPS</div>
        <div class="page-subtitle">Your Adventures</div>
      </div>
      <button class="btn-primary" onclick={() => (createOpen = true)}>+ Plan Trip</button>
    </div>

    <div class="stats-bar">
      <div class="stat-box">
        <div class="stat-value">{stats.trips}</div>
        <div class="stat-label">Trips</div>
      </div>
      <div class="stat-box">
        <div class="stat-value">{stats.cities}</div>
        <div class="stat-label">Cities</div>
      </div>
      <div class="stat-box">
        <div class="stat-value">{stats.countries}</div>
        <div class="stat-label">Countries</div>
      </div>
      <div class="stat-box">
        <div class="stat-value">{formatPoints(stats.points)}</div>
        <div class="stat-label">Points Used</div>
      </div>
    </div>

    <div class="search-wrap">
      <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
      <input class="input search-input" type="text" placeholder="Search trips, cities, hotels, flights..." bind:value={searchQuery} />
      {#if searchQuery}
        <button class="search-clear" onclick={() => (searchQuery = '')}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
      {/if}
    </div>

    {#if filteredTrips}
      <div class="search-results-label">{filteredTrips.length} result{filteredTrips.length !== 1 ? 's' : ''}</div>
      <div class="trip-grid">
        {#each filteredTrips as trip (trip.id)}
          <a href="/trips/trip?id={trip.id}" class="trip-card" class:muted={trip.status === 'completed'}>
            <div class="trip-photo" style={trip.cover ? `background-image:url('${trip.cover}')` : ''}>
              {#if !trip.cover}
                <div class="photo-empty">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
                </div>
              {/if}
            </div>
            <div class="trip-body">
              <div class="trip-name">{trip.name}</div>
              {#if trip.dates}<div class="trip-dates">{trip.dates}</div>{/if}
              {#if trip.cities.length > 0}<div class="trip-cities">{trip.cities.join(' · ')}</div>{/if}
              <div class="trip-footer">
                {#if trip.status === 'active'}<span class="badge active">Active</span>{/if}
                {#if trip.status === 'completed'}<span class="badge completed">Completed</span>{/if}
                {#if trip.daysAway}<span class="trip-countdown">{trip.daysAway}</span>{/if}
                {#if trip.points}<span class="trip-points">{formatPoints(trip.points)} pts</span>{/if}
              </div>
            </div>
          </a>
        {/each}
      </div>
    {:else}
      <section class="section">
        <div class="section-title">UPCOMING</div>
        <div class="trip-grid">
          {#each upcoming as trip (trip.id)}
            <a href="/trips/trip?id={trip.id}" class="trip-card">
              <div class="trip-photo" style="background-image:url('{trip.cover}')">
                {#if trip.shareToken}
                  <button class="share-btn" title="Share trip">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
                  </button>
                {/if}
              </div>
              <div class="trip-body">
                <div class="trip-name">{trip.name}</div>
                <div class="trip-dates">{trip.dates} · {trip.duration}</div>
                <div class="trip-cities">{trip.cities.join(' · ')}</div>
                <div class="trip-footer">
                  {#if trip.status === 'active'}<span class="badge active">Active</span>{/if}
                  <span class="trip-countdown">{trip.daysAway}</span>
                  {#if trip.points}<span class="trip-points">{formatPoints(trip.points)} pts</span>{/if}
                </div>
              </div>
            </a>
          {/each}
        </div>
      </section>

      <section class="section">
        <div class="section-title">PAST ADVENTURES</div>
        <div class="trip-grid">
          {#each past as trip (trip.id)}
            <a href="/trips/trip?id={trip.id}" class="trip-card muted">
              <div class="trip-photo" style={trip.cover ? `background-image:url('${trip.cover}')` : ''}>
                {#if !trip.cover}
                  <div class="photo-empty">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
                  </div>
                {/if}
                {#if trip.shareToken}
                  <button class="share-btn" title="Share trip">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
                  </button>
                {/if}
              </div>
              <div class="trip-body">
                <div class="trip-name">{trip.name}</div>
                {#if trip.dates}<div class="trip-dates">{trip.dates} · {trip.duration}</div>{/if}
                {#if trip.cities.length > 0}<div class="trip-cities">{trip.cities.join(' · ')}</div>{/if}
                <div class="trip-footer">
                  <span class="badge completed">Completed</span>
                  {#if trip.points}<span class="trip-points">{formatPoints(trip.points)} pts</span>{/if}
                  {#if trip.cash}<span class="trip-cash">${trip.cash.toLocaleString()}</span>{/if}
                </div>
              </div>
            </a>
          {/each}
        </div>
      </section>
    {/if}
  </div>
</div>

<CreateTripModal bind:open={createOpen} onCreated={(id) => goto(`/trips/trip?id=${id}`)} />

<style>
  .stats-bar { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--sp-2); margin-bottom: 14px; }
  .stat-box { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: var(--sp-2) 6px; text-align: center; }
  .stat-value { font-size: var(--text-md); font-weight: 700; font-family: var(--mono); color: var(--text-1); line-height: 1.1; }
  .stat-label { font-size: var(--text-xs); color: var(--text-3); margin-top: var(--sp-0.5); text-transform: uppercase; letter-spacing: 0.05em; }

  .header-row { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--sp-4); margin-bottom: var(--sp-3); }
  .page-subtitle { font-size: var(--text-2xl); font-weight: 300; color: var(--text-1); line-height: 1.15; margin-top: -1px; }
  .btn-primary { padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-md); background: var(--accent); color: white; border: none; font-size: var(--text-sm); font-weight: 600; cursor: pointer; font-family: var(--font); transition: opacity var(--transition); }
  .btn-primary:hover { opacity: 0.9; }

  .search-wrap { position: relative; margin-bottom: var(--sp-4); }
  .search-icon { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); width: 16px; height: 16px; color: var(--text-4); pointer-events: none; }
  .search-input { padding-left: 40px; font-size: var(--text-md); }
  .search-clear { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: var(--text-4); padding: var(--sp-1); }
  .search-clear svg { width: 16px; height: 16px; }
  .search-results-label { font-size: var(--text-sm); color: var(--text-3); margin-bottom: var(--sp-3); }

  .section { margin-bottom: var(--section-gap); }
  .section-title { font-size: var(--text-xs); font-weight: 600; color: var(--text-3); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: var(--sp-3); }

  .trip-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--sp-5); }

  .trip-card {
    background: var(--card); border-radius: var(--radius); border: 1px solid var(--border);
    box-shadow: var(--card-shadow-sm); overflow: hidden; transition: all var(--transition);
    text-decoration: none; color: inherit; display: block;
  }
  .trip-card:hover { transform: translateY(-2px); box-shadow: var(--card-shadow); }
  .trip-card.muted { opacity: 0.6; }
  .trip-card.muted:hover { opacity: 0.85; }

  .trip-photo {
    width: 100%; height: 180px; background: var(--card-hover) center/cover no-repeat;
    position: relative;
  }
  .photo-empty {
    width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;
    color: var(--text-4);
  }
  .photo-empty svg { width: 28px; height: 28px; opacity: 0.3; }

  .share-btn {
    position: absolute; top: var(--sp-2); right: var(--sp-2);
    width: 28px; height: 28px; border-radius: 50%;
    background: rgba(0,0,0,0.35); backdrop-filter: blur(6px);
    border: none; color: white; display: flex; align-items: center; justify-content: center;
    cursor: pointer; transition: all var(--transition); opacity: 0;
  }
  .trip-card:hover .share-btn { opacity: 1; }
  .share-btn:hover { background: rgba(0,0,0,0.55); }
  .share-btn svg { width: 13px; height: 13px; }

  .trip-body { padding: 8px 14px 10px; }
  .trip-name { font-size: var(--text-base); font-weight: 600; color: var(--text-1); line-height: 1.3; }
  .trip-dates { font-size: var(--text-xs); color: var(--text-3); margin-top: 3px; }
  .trip-cities { font-size: var(--text-xs); color: var(--text-3); margin-top: 1px; opacity: 0.7; }
  .trip-footer { display: flex; align-items: center; gap: var(--sp-1.5); margin-top: var(--sp-1.5); flex-wrap: wrap; border-top: 1px solid var(--border); padding-top: var(--sp-1.5); }
  .trip-countdown { font-size: var(--text-xs); color: var(--text-3); font-family: var(--mono); }
  .trip-points { font-size: var(--text-xs); font-family: var(--mono); color: var(--accent); font-weight: 500; }
  .trip-cash { font-size: var(--text-xs); font-family: var(--mono); color: var(--text-3); }

  .badge { font-size: var(--text-xs); font-weight: 600; padding: 2px var(--sp-2); border-radius: var(--radius-sm); line-height: 1.5; }
  .badge.active { background: var(--accent-bg); color: var(--accent); }
  .badge.completed { background: var(--surface-secondary); color: var(--text-3); }

  @media (max-width: 768px) {
    .stats-bar { grid-template-columns: repeat(2, 1fr); }
    .trip-grid { grid-template-columns: 1fr; }
    .page-subtitle { font-size: var(--text-xl); }
    .trip-photo { height: 160px; }
    .trip-body { padding: 10px 16px 12px; }
    .trip-name { font-size: var(--text-md); }
  }
</style>
