<script>
  import { onMount } from 'svelte'
  import { slides } from '@state/slides.svelte'
  import Footer from '@components/layout/Footer.svelte'
  import Article from '@views/Article.svelte'

  let { data } = $props()

  const isActive = $derived(slides.active?.id === 'blog')
  const featured = $derived(data?.featured ?? null)
  const articles = $derived(data?.articles ?? [])

  // --- Article sub-page state ---
  let articleData = $state(null)
  let articleLoading = $state(false)
  let sectionEl = $state(null)

  // Extract slug from current URL (for direct navigation to /blog/slug)
  function getSlugFromUrl() {
    const parts = window.location.pathname.split('/').filter(Boolean)
    // parts = ['blog', 'slug'] → slug = 'slug'
    return parts.length >= 2 && parts[0] === 'blog' ? parts[1] : null
  }

  async function openArticle(slug) {
    articleLoading = true
    try {
      const res = await fetch(`/blog/${slug}.json`)
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      articleData = await res.json()
      scrollToTop()
    } catch (e) {
      console.error('[blog] Failed to load article:', e)
      articleData = null
    } finally {
      articleLoading = false
    }
  }

  function backToList() {
    articleData = null
    history.pushState({}, '', '/blog')
    document.title = `${data?.title ?? 'Blog'} — World Game`
    scrollToTop()
  }

  function scrollToTop() {
    sectionEl?.scrollTo(0, 0)
  }

  // Handle article link clicks (intercepted BEFORE the router's document handler)
  function handleClick(e) {
    const link = e.target.closest('a[href]')
    if (!link) return

    const url = new URL(link.href, window.location.origin)
    if (url.origin !== window.location.origin) return

    const match = url.pathname.match(/^\/blog\/([^/]+)$/)
    if (match) {
      e.preventDefault()
      e.stopPropagation()
      const slug = match[1]
      history.pushState({}, '', `/blog/${slug}`)
      openArticle(slug)
    }
  }

  // Handle browser back/forward within blog
  function handlePopState() {
    if (!isActive) return
    const slug = getSlugFromUrl()
    if (slug && (!articleData || articleData.uri !== `blog/${slug}`)) {
      openArticle(slug)
    } else if (!slug && articleData) {
      articleData = null
      scrollToTop()
    }
  }

  // On mount: check if URL is /blog/slug (direct navigation)
  onMount(() => {
    const slug = getSlugFromUrl()
    if (slug) openArticle(slug)

    window.addEventListener('popstate', handlePopState)
    return () => {
      window.removeEventListener('popstate', handlePopState)
    }
  })

  // Reset article view when leaving the blog slide
  $effect(() => {
    if (!isActive && articleData) {
      articleData = null
    }
  })
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<section
  class="blog page-scrollable"
  class:golden-grid={!!articleData}
  bind:this={sectionEl}
  onclick={handleClick}
>
  {#if articleData}
    <!-- Article view -->
    <Article data={articleData} onBack={backToList} />
  {:else}
    <!-- Blog list -->
    <div class="page-container">

      {#if data?.intro}
        <header class="blog-header">
          {@html data.intro}
        </header>
      {/if}

      {#if featured}
        <article class="blog-card blog-card--featured">
          <div class="blog-card-text">
            <time class="blog-card-date">{featured.published}</time>
            <h2 class="blog-card-title">
              <a href="/blog/{featured.slug}">{featured.title}</a>
            </h2>
            {#if featured.intro}
              <p class="blog-card-description">{featured.intro}</p>
            {/if}
            <a href="/blog/{featured.slug}" class="blog-card-readmore">
              Lire l'article <span class="arrow">→</span>
            </a>
          </div>
          {#if featured.cover}
            <div class="blog-card-image blog-card-image--featured">
              <a href="/blog/{featured.slug}">
                <img src={featured.cover} alt={featured.title} />
              </a>
            </div>
          {/if}
        </article>
        <hr class="blog-divider" />
      {/if}

      {#each articles as article, i}
        <article class="blog-card">
          <div class="blog-card-text">
            <time class="blog-card-date">{article.date}</time>
            <h2 class="blog-card-title">
              <a href="/blog/{article.slug}">{article.title}</a>
            </h2>
            <a href="/blog/{article.slug}" class="blog-card-readmore">
              Lire l'article <span class="arrow">→</span>
            </a>
          </div>
          {#if article.cover}
            <div class="blog-card-image">
              <a href="/blog/{article.slug}">
                <img src={article.cover} alt={article.title} />
              </a>
            </div>
          {/if}
        </article>
        {#if i < articles.length - 1}
          <hr class="blog-divider" />
        {/if}
      {/each}

      {#if articleLoading}
        <p class="blog-loading">Chargement…</p>
      {/if}

    </div>

    <Footer />
  {/if}
</section>

<style>
  .blog {
    color: var(--color-text);
    padding: 0 50px;
  }

  /* --- Header / Intro --- */
  .blog-header {
    text-align: center;
    padding: 6rem 0 3rem;
  }

  .blog-header :global(h1) {
    font-family: "Terminal", sans-serif;
    font-size: var(--font-size-title-main);
    text-transform: uppercase;
    margin-bottom: 1.5rem;
  }

  .blog-header :global(p) {
    font-size: var(--font-size-subtitle);
    line-height: 1.6;
    max-width: 640px;
    margin: 0 auto;
    opacity: 0.9;
  }

  .page-container {
    max-width: none;
    margin: 0;
    padding: 0 10%;
  }

  /* --- Card (article item) --- */
  .blog-card {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 2rem;
    padding: 1.5rem 0;
  }

  .blog-card-text {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 1rem;
    max-width: 640px;
  }

  .blog-card-date {
    color: #d9d9d9;
    font-size: var(--font-size-paragraph);
  }

  .blog-card-title {
    font-family: "Danzza", sans-serif;
    font-size: 40px;
    max-width: 80%;
    font-weight: 700;
  }

  .blog-card-title a {
    transition: color 0.2s;
  }

  .blog-card-title a:hover {
    color: var(--color-primary);
  }

  .blog-card-description {
    color: #d9d9d9;
    font-family: "Danzza",sans-serif;
    font-size: var(--font-size-paragraph);
    font-weight: 400;
  }

  .blog-card-readmore {
    color: var(--color-primary);
    font-family: "Danzza", sans-serif;
    font-size: var(--font-size-paragraph);
    font-weight: 500;
    text-transform: uppercase;
  }

  .blog-card-readmore .arrow {
    margin-left: 5px;
  }

  .blog-card-readmore:hover {
    gap: 1rem;
  }

  /* --- Image --- */
  .blog-card-image img {
    width: 300px;
    height: 169px;
    object-fit: cover;
    transition: transform 0.3s;
  }

  .blog-card-image img:hover {
    transform: scale(1.05);
  }

  .blog-card-image--featured img {
    width: auto;
    height: 300px;
  }

  /* --- Divider --- */
  .blog-divider {
    border: none;
    border-top: 1px solid rgba(255, 255, 255, 0.15);
    margin: 0;
  }

  /* --- Featured --- */
  .blog-card--featured .blog-card-title {
    font-size: 36px;
    line-height: 1.3;
  }

  /* --- Loading --- */
  .blog-loading {
    text-align: center;
    padding: 4rem 0;
    opacity: 0.6;
  }

  /* --- Mobile --- */
  @media (max-width: 700px) {
    .blog-header {
      padding: 4rem 0 2rem;
    }

    .blog-header :global(h1) {
      font-size: var(--font-size-title-main-mobile);
    }

    .blog-header :global(p) {
      font-size: var(--font-size-subtitle-mobile);
    }

    .blog-card {
      flex-direction: column;
    }

    .blog-card-image img,
    .blog-card-image--featured img {
      width: 100%;
      height: auto;
      aspect-ratio: 16/9;
    }

    .blog-card--featured .blog-card-title {
      font-size: var(--font-size-title-section-mobile);
    }

    .blog-card-title {
      font-size: var(--font-size-title-section-mobile);
    }
  }

  /* --- Tablet --- */
  @media (min-width: 701px) and (max-width: 912px) {
    .blog-header :global(h1) {
      font-size: var(--font-size-title-main-tablet);
    }

    .blog-card {
      flex-direction: column;
    }

    .blog-card-image img,
    .blog-card-image--featured img {
      width: 100%;
      height: auto;
      aspect-ratio: 16/9;
    }
  }
</style>
