import Head from "next/head";
import Link from "next/link";
import { query } from "../lib/db";
import CategoryCard from "../components/CategoryCard";
import ProductCard from "../components/products/ProductCard";
import ContactGrid from "../components/ContactGrid";
import CategoryBanner from "../components/CategoryBanner";
import HorizontalCarousel from "../components/HorizontalCarousel";

// Interfaces for DB results
interface Category {
  id: number;
  name: string;
  image_url: string;
  description: string;
}

interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  original_price?: number;
  primary_image?: string;
  images: string[];
  stock_status: 'in_stock' | 'out_of_stock';
  product_condition: string;
  badge_text?: string;
  badge_color?: string;
  created_at: string;
}

async function getCategories() {
  // Only show categories marked for homepage display (max 8)
  const rows = await query("SELECT * FROM categories WHERE show_on_homepage = 1 LIMIT 8") as Category[];
  return rows;
}

async function getPopularProducts() {
  // Select products marked for homepage display (max 8)
  const rows = await query(`
    SELECT p.*, 
    (SELECT pi.image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.display_order ASC LIMIT 1) as primary_image
    FROM products p 
    WHERE p.show_on_homepage = 1 
    ORDER BY p.created_at DESC 
    LIMIT 8
  `) as Product[];
  return rows.map(p => ({ ...p, images: p.primary_image ? [p.primary_image] : [] }));
}

async function getNewProducts() {
  // New products are the latest uploaded ones
  const rows = await query(`
    SELECT p.*, 
    (SELECT pi.image_url FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.is_primary DESC, pi.display_order ASC LIMIT 1) as primary_image
    FROM products p 
    ORDER BY p.created_at DESC 
    LIMIT 8
  `) as Product[];
  return rows.map(p => ({ ...p, images: p.primary_image ? [p.primary_image] : [] }));
}

export const dynamic = "force-dynamic";

export default async function Home() {
  const categories = await getCategories();
  const popularProducts = await getPopularProducts();
  const newProducts = await getNewProducts();

  return (
    <>
      <Head>
        <title>Nordic Storium – Kvalitetsmöbler till konkurspriser</title>
        <meta
          name="description"
          content="Vi säljer kontorsmöbler, stolar och inredning från konkursbon och företag. Hög kvalitet till låga priser. Fri frakt nära Stockholm."
        />
        <link rel="canonical" href="https://www.nordicstorium.se/" />
      </Head>

      {/* Categories Section */}
      <div className="container mx-auto px-4 py-8">
        <section>
          <div className="flex flex-row justify-between items-end mb-4 px-2">
            <h2 className="text-xl md:text-3xl font-bold text-gray-900 dark:text-white leading-tight">Populära Kategorier</h2>
            <Link href="/products" className="text-blue-600 font-semibold hover:underline text-sm md:text-base whitespace-nowrap">
              Se alla &rarr;
            </Link>
          </div>
          {/* Persistent Horizontal Scroll - Centered if possible */}
          <HorizontalCarousel>
            {categories.map((category) => (
              <div key={category.id} className="flex-shrink-0 w-36 md:w-48 lg:w-56 snap-start">
                <CategoryCard category={category} />
              </div>
            ))}
          </HorizontalCarousel>
        </section>
      </div>

      {/* Combined Banner with Info */}
      <CategoryBanner />

      {/* Products Section */}
      <div className="container mx-auto px-4 py-12 space-y-16">

        {/* Popular Products */}
        <section>
          <div className="flex flex-row justify-between items-end mb-4 px-2">
            <h2 className="text-xl md:text-3xl font-bold text-gray-900 dark:text-white leading-tight">Populära Produkter</h2>
            <Link href="/products" className="text-blue-600 font-semibold hover:underline text-sm md:text-base whitespace-nowrap">
              Visa alla &rarr;
            </Link>
          </div>
          <HorizontalCarousel>
            {popularProducts.map((product) => (
              <div key={product.id} className="flex-shrink-0 w-64 md:w-72 lg:w-80 snap-start">
                <ProductCard product={product} />
              </div>
            ))}
          </HorizontalCarousel>
        </section>

        {/* New Products */}
        <section>
          <div className="flex flex-row justify-between items-end mb-4 px-2">
            <h2 className="text-xl md:text-3xl font-bold text-gray-900 dark:text-white leading-tight">Nyinkommet</h2>
            <Link href="/products" className="text-blue-600 font-semibold hover:underline text-sm md:text-base whitespace-nowrap">
              Se alla &rarr;
            </Link>
          </div>
          <HorizontalCarousel>
            {newProducts.map((product) => (
              <div key={product.id} className="flex-shrink-0 w-64 md:w-72 lg:w-80 snap-start">
                <ProductCard product={product} />
              </div>
            ))}
          </HorizontalCarousel>
        </section>

      </div>

      {/* Contact Grid */}
      <ContactGrid />
    </>
  );
}