<script lang="ts">
  import { onMount } from 'svelte';

  interface Post {
    title: string;
    description: string;
    link: string;
    pubDate: string;
  }

  let posts: Post[] = $state([]);
  let loading = $state(true);
  let error = $state(false);

  onMount(async () => {
    try {
      // Use production proxy in dev too (CORS)
      const url = import.meta.env.DEV
        ? 'https://build.valuecurve.co/api/rss'
        : '/api/rss';

      const response = await fetch(url);
      const xml = await response.text();

      // Parse RSS XML
      const items = xml.match(/<item>[\s\S]*?<\/item>/g) || [];
      posts = items.slice(0, 4).map(item => ({
        title: (item.match(/<title><!\[CDATA\[([\s\S]*?)\]\]><\/title>/)?.[1] ||
               item.match(/<title>([\s\S]*?)<\/title>/)?.[1] || '').trim(),
        description: (item.match(/<description><!\[CDATA\[([\s\S]*?)\]\]><\/description>/)?.[1] || '').trim(),
        link: item.match(/<link>(.*?)<\/link>/)?.[1] || '',
        pubDate: item.match(/<pubDate>(.*?)<\/pubDate>/)?.[1] || ''
      }));
    } catch (e) {
      error = true;
      console.error('Failed to fetch posts:', e);
    } finally {
      loading = false;
    }
  });

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

  function stripHtml(html: string): string {
    return html.replace(/<[^>]*>/g, '').substring(0, 150) + '...';
  }
</script>

<section class="py-20 px-6 bg-gray-50">
  <div class="max-w-6xl mx-auto">
    <div class="flex items-center justify-between mb-8">
      <h2 class="text-2xl font-bold text-gray-900">Latest from Newsletter</h2>
      <a href="https://www.valuecurve.ai"
         class="text-primary-600 hover:text-primary-700 text-sm font-medium"
         target="_blank" rel="noopener">
        View all &rarr;
      </a>
    </div>

    {#if loading}
      <!-- Skeleton loader -->
      <div class="grid md:grid-cols-2 gap-6">
        {#each [1, 2, 3, 4] as _}
          <div class="p-6 bg-white rounded-xl border border-gray-100 animate-pulse">
            <div class="h-3 bg-gray-200 rounded w-20 mb-3"></div>
            <div class="h-5 bg-gray-200 rounded w-3/4 mb-2"></div>
            <div class="h-4 bg-gray-200 rounded w-full"></div>
          </div>
        {/each}
      </div>
    {:else if error}
      <p class="text-gray-500 text-center py-8">
        Unable to load posts. <a href="https://www.valuecurve.ai" class="text-primary-600 hover:underline" target="_blank" rel="noopener">Visit newsletter &rarr;</a>
      </p>
    {:else}
      <div class="grid md:grid-cols-2 gap-6">
        {#each posts as post}
          <a href={post.link}
             class="block p-6 bg-white rounded-xl border border-gray-100 hover:shadow-lg transition-shadow"
             target="_blank" rel="noopener">
            <p class="text-xs text-gray-500 mb-2">{formatDate(post.pubDate)}</p>
            <h3 class="font-semibold text-gray-900 mb-2 line-clamp-2">{post.title}</h3>
            <p class="text-sm text-gray-600 line-clamp-2">{stripHtml(post.description)}</p>
          </a>
        {/each}
      </div>
    {/if}
  </div>
</section>
