import type { Metadata } from "next";
import { Suspense } from "react";
import { notFound } from "next/navigation";
import { api } from "@/lib/api";
import { buildMetadata } from "@/lib/seo";
import { StoreDetailClient } from "./store-detail-client";

interface StorePageProps {
  params: Promise<{ id: string }>;
}

export async function generateMetadata({ params }: StorePageProps): Promise<Metadata> {
  const { id } = await params;

  try {
    const res = await api.stores.getPublic(id);
    const store = res.data;
    const locationParts = [store.city, store.state].filter(Boolean);
    const titleParts = [store.name];
    if (locationParts.length > 0) titleParts.push(locationParts.join(", "));

    return buildMetadata({
      title: titleParts.join(" — "),
      description: `Shop curated resale items from ${store.name}. Verified store on Alqove.`,
      canonical: `https://alqove.com/stores/${id}`,
    });
  } catch {
    return buildMetadata({
      title: "Store not found",
      description: "This store may no longer be available.",
      noindex: true,
    });
  }
}

export default async function StorePage({ params }: StorePageProps) {
  const { id } = await params;

  let store;
  try {
    const res = await api.stores.getPublic(id);
    store = res.data;
  } catch {
    notFound();
  }

  const catRes = await api.categories.list();
  const categoryTree = catRes.data;

  return (
    <Suspense fallback={<StoreSkeleton />}>
      <StoreDetailClient store={store} categoryTree={categoryTree} />
    </Suspense>
  );
}

function StoreSkeleton() {
  return (
    <div className="mx-auto max-w-7xl px-4 py-8">
      <div className="flex items-center gap-4 mb-8">
        <div className="w-14 h-14 rounded bg-slate-200 animate-pulse" />
        <div className="space-y-2">
          <div className="h-6 w-48 rounded bg-slate-200 animate-pulse" />
          <div className="h-4 w-32 rounded bg-slate-200 animate-pulse" />
        </div>
      </div>
      <div className="mt-6 flex gap-8">
        <div className="w-64 shrink-0 space-y-4">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="h-6 animate-pulse rounded bg-slate-200" />
          ))}
        </div>
        <div className="flex-1">
          <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
            {Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="space-y-2">
                <div className="aspect-square w-full animate-pulse rounded bg-slate-200" />
                <div className="h-4 w-3/4 animate-pulse rounded bg-slate-200" />
                <div className="h-4 w-1/2 animate-pulse rounded bg-slate-200" />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
