<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 { Select, SelectContent, SelectItem, SelectTrigger } from "$lib/components/ui/select";
  import { getAssetUrl } from "$lib/api";
  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";

  const { data } = $props();

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

  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 !== "name") 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()}`);
  }

  const totalPages = $derived(Math.ceil(data.total / data.limit));

  const pageNumbers = $derived(() => {
    const pages: (number | -1)[] = [];
    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      pages.push(1);
      if (data.page > 3) pages.push(-1);
      for (let i = Math.max(2, data.page - 1); i <= Math.min(totalPages - 1, data.page + 1); i++)
        pages.push(i);
      if (data.page < totalPages - 2) pages.push(-1);
      pages.push(totalPages);
    }
    return pages;
  });
</script>

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

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

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

      <!-- Sort -->
      <Select type="single" value={data.sort} onValueChange={(v) => v && setParam("sort", v)}>
        <SelectTrigger
          class="w-full md:w-48 bg-background/50 border-primary/20 focus:border-primary"
        >
          {data.sort === "recent" ? $_("models.sort.recent") : $_("models.sort.name")}
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="name">{$_("models.sort.name")}</SelectItem>
          <SelectItem value="recent">{$_("models.sort.recent")}</SelectItem>
        </SelectContent>
      </Select>
    </div>
  </PageHero>
  <!-- Models Grid -->
  <div class="container mx-auto px-4 py-12">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
      {#each data.items as model (model.slug)}
        <a href="/models/{model.slug}" class="block group">
          <Card
            class="py-0 h-full hover:shadow-2xl hover:shadow-primary/25 transition-all duration-500 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(model.photo ?? model.avatar, "preview")}
                alt={model.artist_name}
                class="w-full aspect-square object-cover group-hover:scale-105 transition-transform duration-300 bg-muted"
              />

              <!-- Online Status -->
              <!-- {#if model.isOnline}
              <div
                class="absolute top-3 left-3 bg-green-500 text-white text-xs px-2 py-1 rounded-full flex items-center gap-1"
              >
                <div class="w-2 h-2 bg-white rounded-full animate-pulse"></div>
                {$_("models.online")}
              </div>
            {/if} -->

              <!-- Heart Button -->
              <!-- <button
              class="absolute top-3 right-3 w-10 h-10 bg-black/50 hover:bg-primary/80 rounded-full flex items-center justify-center transition-colors group/heart"
            >
              <HeartIcon
                class="w-5 h-5 text-white group-hover/heart:fill-current"
              />
            </button> -->

              <!-- Hover Overlay -->
              <div
                aria-hidden="true"
                class="absolute inset-0 group-hover:scale-105 transition bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 flex items-center justify-center"
              >
                <div class="w-16 h-16 bg-primary/90 rounded-full flex items-center justify-center">
                  <span class="icon-[ri--play-large-fill] w-8 h-8 text-white ml-1"></span>
                </div>
              </div>
            </div>

            <CardContent class="p-6">
              <div class="flex items-start justify-between mb-3">
                <div>
                  <h3 class="font-semibold text-lg mb-1 group-hover:text-primary transition-colors">
                    {model.artist_name}
                  </h3>
                  <!-- <div
                  class="flex items-center gap-4 text-sm text-muted-foreground"
                >
                  <div class="flex items-center gap-1">
                    <StarIcon class="w-4 h-4 text-yellow-500 fill-current" />
                    {model.rating}
                  </div>
                  <div>{model.subscribers} followers</div>
                </div> -->
                </div>
              </div>

              <!-- Tags -->
              <div class="flex flex-wrap gap-2 mb-4">
                {#each model.tags as tag (tag)}
                  <a
                    class="text-xs bg-primary/10 text-primary px-2 py-1 rounded-full"
                    href="/tags/{tag}"
                  >
                    {tag}
                  </a>
                {/each}
              </div>

              <!-- Stats -->
              <div class="flex items-center justify-between text-sm text-muted-foreground mb-4">
                <!-- <span>{model.videos} videos</span> -->
                <!-- category not available -->
              </div>
            </CardContent>
          </Card>
        </a>
      {/each}
    </div>

    {#if data.items.length === 0}
      <div class="text-center py-12">
        <p class="text-muted-foreground text-lg">{$_("models.no_results")}</p>
        <Button variant="outline" href="/models" class="mt-4">
          {$_("models.clear_filters")}
        </Button>
      </div>
    {/if}

    <!-- Pagination -->
    {#if totalPages > 1}
      <div class="flex flex-col items-center gap-3 mt-10">
        <div class="flex items-center gap-1">
          <Button
            variant="outline"
            size="sm"
            disabled={data.page <= 1}
            onclick={() => goToPage(data.page - 1)}
            class="border-primary/20 hover:bg-primary/10">{$_("common.previous")}</Button
          >
          {#each pageNumbers() as p, i (i)}
            {#if p === -1}
              <span class="px-2 text-muted-foreground select-none">…</span>
            {:else}
              <Button
                variant={p === data.page ? "default" : "outline"}
                size="sm"
                onclick={() => goToPage(p)}
                class={p === data.page
                  ? "bg-gradient-to-r from-primary to-accent min-w-9"
                  : "border-primary/20 hover:bg-primary/10 min-w-9"}>{p}</Button
              >
            {/if}
          {/each}
          <Button
            variant="outline"
            size="sm"
            disabled={data.page >= totalPages}
            onclick={() => goToPage(data.page + 1)}
            class="border-primary/20 hover:bg-primary/10">{$_("common.next")}</Button
          >
        </div>
        <p class="text-sm text-muted-foreground">
          {$_("common.total_results", { values: { total: data.total } })}
        </p>
      </div>
    {/if}
  </div>
</div>
