<script>
  import { onMount } from 'svelte'
  import { slides } from '@state/slides.svelte'
  import { locale } from '@state/locale.svelte'
  import WhitePaper from '@views/WhitePaper.svelte'
  import { t } from '@i18n'
  import Footer from '@components/layout/Footer.svelte'

  let { data } = $props()

  const isActive = $derived(slides.active?.id === data?.uri)
  const items    = $derived(data?.items ?? [])
  const pageUri  = $derived(data?.uri ?? 'white-papers') // ex: "livres-blancs"

  let itemData = $state(null)
  let itemLoading = $state(false)
  let sectionEl = $state(null)

  function getSlugFromUrl() {
    const parts = window.location.pathname.replace(/^\/en/, '').split('/').filter(Boolean)
    return parts.length >= 2 && parts[0] === pageUri ? parts[1] : null
  }

  async function openItem(slug) {
    itemLoading = true
    try {
      const prefix = locale.current === 'en' ? '/en' : ''
      const res = await fetch(`${prefix}/${pageUri}/${slug}.json`)
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      itemData = await res.json()
      sectionEl?.scrollTo(0, 0)
    } catch (e) {
      console.error(`[${pageUri}] Failed to load:`, e)
      itemData = null
    } finally {
      itemLoading = false
    }
  }

  function backToList() {
    itemData = null
    const prefix = locale.current === 'en' ? '/en' : ''
    history.pushState({}, '', `${prefix}/${pageUri}`)
    document.title = `${data?.title ?? pageUri} — World Game`
    sectionEl?.scrollTo(0, 0)
  }

  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(new RegExp(`^(?:/en)?/${pageUri}/([^/]+)$`))
    if (match) {
      e.preventDefault()
      e.stopPropagation()
      const slug = match[1]
      const prefix = locale.current === 'en' ? '/en' : ''
      history.pushState({}, '', `${prefix}/${pageUri}/${slug}`)
      openItem(slug)
    }
  }

  function handlePopState() {
    if (!isActive) return
    const slug = getSlugFromUrl()
    if (slug && (!itemData || itemData.uri !== `${pageUri}/${slug}`)) {
      openItem(slug)
    } else if (!slug && itemData) {
      itemData = null
      sectionEl?.scrollTo(0, 0)
    }
  }

  onMount(() => {
    const slug = getSlugFromUrl() ?? (data?.singleSlug ?? null)
    if (slug) openItem(slug)

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

  $effect(() => {
    if (!isActive && itemData) itemData = null
  })
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<section
  class="collection white-papers page-scrollable"
  bind:this={sectionEl}
  onclick={handleClick}
>
  {#if itemData}
    <WhitePaper data={itemData} onBack={backToList} />
  {:else}
    <div class="page-container">

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

      {#each items as item, i}
        <article class="collection-card">
          <div class="collection-card-text">
            <time class="collection-card-date">{item.published}</time>
            <h2 class="collection-card-title">
              <a href="/{pageUri}/{item.slug}">{item.title}</a>
            </h2>
            {#if item.intro}
              <p class="collection-card-description">{item.intro}</p>
            {/if}
            <a href="/{pageUri}/{item.slug}" class="collection-card-readmore">
              {t('read_wp')} <span class="arrow">→</span>
            </a>
          </div>
          {#if item.cover}
            <div class="collection-card-image">
              <a href="/{pageUri}/{item.slug}">
                <img src={item.cover} alt={item.title} />
              </a>
            </div>
          {/if}
        </article>
        {#if i < items.length - 1}
          <hr class="collection-divider" />
        {/if}
      {/each}

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

      <Footer class="page-scrollable-footer" />
    </div>
  {/if}
</section>

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

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

  @media (max-width: 700px) {
    .white-papers {
      padding: 0 1.25rem;
    }
  }
</style>
