<script>
  import { onMount } from 'svelte'
  import { slides } from '@state/slides.svelte'
  import { locale } from '@state/locale.svelte'

  import Article from '@views/Article.svelte'
  import { t } from '@i18n'
  import Footer from '@components/layout/Footer.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 or /en/blog/slug)
  function getSlugFromUrl() {
    const parts = window.location.pathname.replace(/^\/en/, '').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 prefix = locale.current === 'en' ? '/en' : ''
      const res = await fetch(`${prefix}/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
    const prefix = locale.current === 'en' ? '/en' : ''
    history.pushState({}, '', `${prefix}/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(/^(?:\/en)?\/blog\/([^/]+)$/)
    if (match) {
      e.preventDefault()
      e.stopPropagation()
      const slug = match[1]
      const prefix = locale.current === 'en' ? '/en' : ''
      history.pushState({}, '', `${prefix}/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 après la fin de la transition de slide (1100ms) pour éviter le flash
  $effect(() => {
    if (!isActive && articleData) {
      const timer = setTimeout(() => { articleData = null }, 1100)
      return () => clearTimeout(timer)
    }
  })
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<section
  class="collection 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="collection-header">
          {@html data.intro}
        </header>
      {/if}

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

      {#each articles as article, i}
        <article class="collection-card">
          <div class="collection-card-text">
            <time class="collection-card-date">{article.published}</time>
            <h2 class="collection-card-title">
              <a href="/blog/{article.slug}">{article.title}</a>
            </h2>
            <a href="/blog/{article.slug}" class="collection-card-readmore desktop-only">
              {t('read_article')} <span class="arrow">→</span>
            </a>
          </div>
          {#if article.cover}
            <div class="collection-card-image">
              <a href="/blog/{article.slug}">
                <img src={article.cover} alt={article.title} />
              </a>
            </div>
          {/if}
          <a href="/blog/{article.slug}" class="collection-card-readmore mobile-only">
            {t('read_article')} <span class="arrow">→</span>
          </a>
        </article>
        {#if i < articles.length - 1}
          <hr class="collection-divider" />
        {/if}
      {/each}

      {#if articleLoading}
        <p class="collection-loading">{t('loading')}</p>
      {/if}

      <Footer />
    </div>

  {/if}
</section>

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

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

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

  @media (max-width: 700px) {
    .blog {
      padding: 0 1.25rem;
    }

    .page-container {
      padding: 0 .2rem;
    }
  }
</style>
