<script lang="ts">
  import { _ } from "svelte-i18n";
  import { goto } from "$app/navigation";
  import { page } from "$app/state";
  import { SvelteURLSearchParams } from "svelte/reactivity";
  import { Button } from "$lib/components/ui/button";
  import { Card, CardContent } from "$lib/components/ui/card";
  import { Input } from "$lib/components/ui/input";
  import { FilterPills } from "$lib/components/ui/filter-pills";
  import TimeAgo from "javascript-time-ago";
  import { getAssetUrl } from "$lib/api";
  import { calcReadingTime } from "$lib/utils.js";
  import Meta from "$lib/components/meta/meta.svelte";
  import SexyBackground from "$lib/components/background/background.svelte";
  import PageHero from "$lib/components/page-hero/page-hero.svelte";
  import Pagination from "$lib/components/pagination/pagination.svelte";

  const timeAgo = new TimeAgo("en");
  const { data } = $props();

  let searchValue = $derived(data.search ?? "");
  let searchTimeout: ReturnType<typeof setTimeout>;

  const featuredArticle = $derived(
    data.page === 1 && !data.search && !data.category ? data.items.find((a) => a.featured) : null,
  );

  function debounceSearch(value: string) {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
      const params = new SvelteURLSearchParams(page.url.searchParams.toString());
      if (value) params.set("search", value);
      else params.delete("search");
      params.delete("page");
      goto(`?${params.toString()}`, { keepFocus: true });
    }, 400);
  }

  function setParam(key: string, value: string) {
    const params = new SvelteURLSearchParams(page.url.searchParams.toString());
    if (value && value !== "all" && value !== "recent") params.set(key, value);
    else params.delete(key);
    params.delete("page");
    goto(`?${params.toString()}`);
  }

  function goToPage(p: number) {
    const params = new SvelteURLSearchParams(page.url.searchParams.toString());
    if (p > 1) params.set("page", String(p));
    else params.delete("page");
    goto(`?${params.toString()}`);
  }
</script>

<Meta title={$_("magazine.title")} description={$_("magazine.description")} />

<div
  class="relative min-h-screen bg-gradient-to-br from-background via-primary/5 to-accent/5 overflow-hidden"
>
  <SexyBackground />

  <PageHero title={$_("magazine.title")} description={$_("magazine.description")}>
    <div class="flex flex-col gap-5 max-w-2xl mx-auto">
      <!-- Search -->
      <div class="relative">
        <span
          class="icon-[ri--search-line] absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground"
        ></span>
        <Input
          placeholder={$_("magazine.search_placeholder")}
          value={searchValue}
          oninput={(e) => {
            searchValue = (e.target as HTMLInputElement).value;
            debounceSearch(searchValue);
          }}
          class="pl-12 h-14 text-lg bg-card/50 border-primary/20 focus:border-primary"
        />
      </div>

      <!-- Category -->
      <FilterPills
        value={data.category ?? "all"}
        options={[
          { value: "all", label: $_("magazine.categories.all") },
          ...data.categories.map((c) => ({
            value: c,
            label: $_(`magazine.categories.${c}`, { default: c }),
          })),
        ]}
        onchange={(v) => setParam("category", v)}
      />

      <!-- Sort -->
      <FilterPills
        value={data.sort ?? "recent"}
        options={[
          { value: "recent", label: $_("magazine.sort.recent") },
          { value: "featured", label: $_("magazine.sort.featured") },
          { value: "name", label: $_("magazine.sort.name") },
        ]}
        onchange={(v) => setParam("sort", v)}
      />
    </div>
  </PageHero>

  <div class="container mx-auto px-4 pt-6 pb-12">
    <!-- Featured Article -->
    {#if featuredArticle}
      <Card
        class="py-0 mb-12 overflow-hidden bg-gradient-to-br from-card/90 via-card/95 to-card/85 backdrop-blur-xl shadow-2xl shadow-primary/20"
      >
        <div class="grid grid-cols-1 lg:grid-cols-2">
          <div class="relative">
            <img
              src={getAssetUrl(featuredArticle.image, "medium")}
              alt={featuredArticle.title}
              class="w-full h-96 object-cover"
            />
            <div
              class="absolute top-4 left-4 bg-gradient-to-r from-primary to-accent text-white px-3 py-1 rounded-full text-sm font-medium"
            >
              {$_("magazine.featured")}
            </div>
          </div>
          <CardContent class="p-8 flex flex-col justify-center">
            <div class="mb-4">
              <span
                class="text-sm text-primary font-medium capitalize bg-primary/10 px-2 py-1 rounded-full"
              >
                {featuredArticle.category}
              </span>
            </div>
            <h2 class="text-2xl md:text-3xl font-bold mb-4 hover:text-primary transition-colors">
              <a href="/magazine/{featuredArticle.slug}">{featuredArticle.title}</a>
            </h2>
            <p class="text-muted-foreground mb-6 text-lg leading-relaxed">
              {featuredArticle.excerpt}
            </p>
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-3">
                <img
                  src={getAssetUrl(featuredArticle.author?.avatar, "mini")}
                  alt={featuredArticle.author?.artist_name}
                  class="w-10 h-10 rounded-full object-cover"
                />
                <div>
                  <p class="font-medium">{featuredArticle.author?.artist_name}</p>
                  <div class="flex items-center gap-3 text-sm text-muted-foreground">
                    <span>{timeAgo.format(new Date(featuredArticle.publish_date))}</span>
                    <span>•</span>
                    <span
                      >{$_("magazine.read_time", {
                        values: {
                          time: calcReadingTime(featuredArticle.content),
                        },
                      })}
                    </span>
                  </div>
                </div>
              </div>
              <Button
                class="bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90"
                href="/magazine/{featuredArticle.slug}">{$_("magazine.read_article")}</Button
              >
            </div>
          </CardContent>
        </div>
      </Card>
    {/if}

    <!-- Articles Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
      {#each data.items as article (article.slug)}
        <a href="/magazine/{article.slug}" class="block group">
          <Card
            class="p-0 h-full hover:shadow-2xl hover:shadow-primary/25 transition-all duration-300 hover:-translate-y-3 bg-gradient-to-br from-card/90 via-card/95 to-card/85 backdrop-blur-xl shadow-lg shadow-primary/10 overflow-hidden"
          >
            <div class="relative">
              <img
                src={getAssetUrl(article.image, "preview")}
                alt={article.title}
                class="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300 bg-muted"
              />
              <div
                class="absolute group-hover:scale-105 transition-transform inset-0 bg-gradient-to-t from-black/40 to-transparent duration-300"
              ></div>

              <!-- Category Badge -->
              <div
                class="absolute top-3 left-3 bg-primary/90 text-white text-xs px-2 py-1 rounded-full capitalize"
              >
                {article.category}
              </div>

              <!-- Featured Badge -->
              {#if article.featured}
                <div
                  class="absolute top-3 right-3 bg-gradient-to-r from-primary to-accent text-white text-xs px-2 py-1 rounded-full"
                >
                  {$_("magazine.featured")}
                </div>
              {/if}
            </div>

            <CardContent class="p-6">
              <div class="mb-4">
                <h3
                  class="font-semibold text-lg mb-2 group-hover:text-primary transition-colors line-clamp-2"
                >
                  {article.title}
                </h3>
                <p class="text-muted-foreground text-sm line-clamp-3 leading-relaxed">
                  {article.excerpt}
                </p>
              </div>

              <!-- Tags -->
              <div class="flex flex-wrap gap-2 mb-4">
                {#each (article.tags ?? []).slice(0, 3) as tag (tag)}
                  <span class="text-xs bg-primary/10 text-primary px-2 py-1 rounded-full">
                    #{tag}
                  </span>
                {/each}
              </div>

              <!-- Author & Meta -->
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <img
                    src={getAssetUrl(article.author?.avatar, "mini")}
                    alt={article.author?.artist_name}
                    class="w-8 h-8 rounded-full object-cover bg-muted"
                  />
                  <div>
                    <p class="text-sm font-medium">{article.author?.artist_name}</p>
                    <div class="flex items-center gap-2 text-xs text-muted-foreground">
                      <span class="icon-[ri--calendar-line] w-4 h-4"></span>
                      {timeAgo.format(new Date(article.publish_date))}
                    </div>
                  </div>
                </div>
                <div class="text-xs text-muted-foreground">
                  {$_("magazine.read_time", {
                    values: { time: calcReadingTime(article.content) },
                  })}
                </div>
              </div>
            </CardContent>
          </Card>
        </a>
      {/each}
    </div>

    {#if data.items.length === 0}
      <div class="text-center py-12">
        <p class="text-muted-foreground text-lg mb-4">
          {$_("magazine.no_results")}
        </p>
        <Button variant="outline" href="/magazine" class="border-primary/20 hover:bg-primary/10">
          {$_("magazine.clear_filters")}
        </Button>
      </div>
    {/if}

    <!-- Pagination -->
    {#if Math.ceil(data.total / data.limit) > 1}
      <div class="flex flex-col items-center gap-3 mt-10">
        <Pagination
          currentPage={data.page}
          totalPages={Math.ceil(data.total / data.limit)}
          onPageChange={goToPage}
        />
        <p class="text-sm text-muted-foreground">
          {$_("common.total_results", { values: { total: data.total } })}
        </p>
      </div>
    {/if}
  </div>
</div>
