import { getArticles, getCategories, getSubCategories } from '@/lib/data';
import { getAllGames } from '@/lib/games';
import Link from 'next/link';
import { headers } from 'next/headers';
import { connection } from 'next/server';

function hashString(value: string) {
  let hash = 0;
  for (let i = 0; i < value.length; i += 1) {
    hash = (hash * 31 + value.charCodeAt(i)) >>> 0;
  }
  return hash;
}

function stableShuffle<T>(items: T[], seed: string, key: (item: T) => string = String) {
  return [...items].sort((a, b) => hashString(`${seed}:${key(a)}`) - hashString(`${seed}:${key(b)}`));
}

function titleCase(value: string) {
  return value
    .replace(/[-_]+/g, ' ')
    .toLowerCase()
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function pickTone(index: number) {
  const tones = [
    'from-sky-500 via-cyan-400 to-emerald-300',
    'from-orange-500 via-amber-300 to-lime-300',
    'from-fuchsia-500 via-pink-400 to-rose-300',
    'from-violet-500 via-indigo-400 to-sky-300',
    'from-emerald-500 via-teal-300 to-cyan-300',
    'from-red-500 via-orange-400 to-yellow-300',
  ];
  return tones[index % tones.length];
}

export default async function Home() {
  await connection();

  const headersList = await headers();
  const domain = headersList.get('host') || 'gamezones.local';
  const siteName = domain.split(':')[0];
  const brand = siteName === 'localhost' ? 'Gamezones' : titleCase(siteName.split('.')[0]);

  const categories = await getCategories();
  const games = await getAllGames();
  const gameSlice = games.slice(0, 12);
  const articles: Array<{
    slug: string;
    originalFileName: string;
    title: string;
    cat1: string;
    cat2: string;
  }> = [];

  const categoryStats: Array<{ cat: string; count: number }> = [];
  const shuffledCats = stableShuffle(categories, siteName).slice(0, 28);

  for (const cat1 of shuffledCats) {
    const subCategories = await getSubCategories(cat1);
    categoryStats.push({ cat: cat1, count: subCategories.length });
    if (!subCategories.length || articles.length >= 90) continue;

    const subPool = stableShuffle(subCategories, `${siteName}:${cat1}`).slice(0, 3);
    for (const cat2 of subPool) {
      if (articles.length >= 90) break;
      const rows = await getArticles(cat1, cat2);
      articles.push(
        ...stableShuffle(rows, `${siteName}:${cat1}:${cat2}`, (row) => row.originalFileName)
          .slice(0, 12)
          .map((article) => ({ ...article, cat1, cat2 }))
      );
    }
  }

  const nowPlaying = articles.slice(0, 12);
  const featured = articles.slice(12, 18);
  const topPicks = articles.slice(18, 36);
  const latest = articles.slice(36, 86);
  const topCategories = categoryStats.slice(0, 18);

  return (
    <main className="min-h-screen bg-[#08111f] text-slate-100">
      <div className="mx-auto w-full max-w-7xl px-4 py-4 sm:px-6 lg:px-8">
        <header className="mb-4 flex flex-col gap-3 rounded-md border border-white/10 bg-[#0e1728]/95 p-3 shadow-lg shadow-black/20 md:flex-row md:items-center md:justify-between">
          <Link href="/" className="min-w-0 truncate text-2xl font-black tracking-tight text-white">
            {brand}
          </Link>
          <nav className="flex gap-2 overflow-x-auto text-sm font-extrabold">
            <Link href="/" className="shrink-0 rounded-md bg-emerald-400 px-4 py-2 text-slate-950">
              Home
            </Link>
            <a href="#games" className="shrink-0 rounded-md bg-white/10 px-4 py-2 text-white hover:bg-white/20">
              Games
            </a>
            <a href="#categories" className="shrink-0 rounded-md bg-white/10 px-4 py-2 text-white hover:bg-white/20">
              Categories
            </a>
            <a href="#articles" className="shrink-0 rounded-md bg-white/10 px-4 py-2 text-white hover:bg-white/20">
              Articles
            </a>
          </nav>
        </header>

        <div className="grid gap-5 lg:grid-cols-[230px_minmax(0,1fr)] lg:items-start">
          <aside className="grid gap-4 sm:grid-cols-2 lg:sticky lg:top-4 lg:block lg:space-y-4">
            <section className="rounded-md border border-white/10 bg-[#0e1728] p-4">
              <h2 className="mb-3 text-xs font-black uppercase tracking-widest text-emerald-300">Main Menu</h2>
              <nav className="grid grid-cols-2 gap-2 text-sm font-black sm:grid-cols-1">
                <Link href="/" className="rounded-md bg-white/10 px-3 py-2 text-center text-white hover:bg-emerald-400 hover:text-slate-950 sm:text-left">
                  Home
                </Link>
                <a href="#games" className="rounded-md px-3 py-2 text-center text-white hover:bg-emerald-400 hover:text-slate-950 sm:text-left">
                  All Games
                </a>
                <a href="#categories" className="rounded-md px-3 py-2 text-center text-white hover:bg-emerald-400 hover:text-slate-950 sm:text-left">
                  Categories
                </a>
                <a href="#articles" className="rounded-md px-3 py-2 text-center text-white hover:bg-emerald-400 hover:text-slate-950 sm:text-left">
                  Articles
                </a>
              </nav>
            </section>

            <section id="categories" className="rounded-md border border-white/10 bg-[#0e1728] p-4">
              <h2 className="mb-3 text-xs font-black uppercase tracking-widest text-amber-300">Article Categories</h2>
              <div className="max-h-56 overflow-y-auto pr-1 lg:max-h-[calc(100vh-260px)]">
                <div className="grid gap-2">
                {topCategories.map((item) => (
                  <Link
                    href={`/${item.cat}`}
                    key={item.cat}
                    className="flex items-center justify-between gap-3 rounded-md bg-[#18243a] px-3 py-2 text-xs font-black uppercase text-slate-100 hover:bg-amber-300 hover:text-slate-950"
                  >
                    <span className="min-w-0 truncate">{titleCase(item.cat)}</span>
                    <span className="shrink-0 text-slate-400">{item.count}</span>
                  </Link>
                ))}
                </div>
              </div>
            </section>
          </aside>

          <div className="min-w-0">
            <section className="overflow-hidden rounded-md bg-white p-3 text-slate-950 shadow-2xl shadow-black/30 sm:p-4">
              <div className="mb-4 flex items-center gap-2 overflow-x-auto whitespace-nowrap text-xs font-black uppercase text-slate-600">
                <Link href="/" className="shrink-0 text-emerald-700">
                  Home
                </Link>
                <span className="shrink-0">Now Playing</span>
                {nowPlaying.map((article) => (
                  <Link
                    href={`/${article.cat1}/${article.cat2}/${article.slug}`}
                    key={`${article.cat1}-${article.cat2}-${article.slug}-now`}
                    className="max-w-[220px] shrink-0 truncate rounded bg-slate-100 px-2 py-1 hover:bg-emerald-100"
                  >
                    {titleCase(article.title)}
                  </Link>
                ))}
              </div>

              <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_300px]">
                <div className="rounded-md bg-[#111b2d] p-5 text-white sm:p-7">
                  <p className="mb-2 text-xs font-black uppercase tracking-[0.18em] text-emerald-300">
                    Fast browser games and article picks
                  </p>
                  <h1 className="max-w-3xl text-3xl font-black leading-tight sm:text-4xl">
                    Unblocked Games G+ play at {brand}
                  </h1>
                  <p className="mt-3 max-w-2xl text-sm font-bold leading-6 text-slate-300">
                    Fast loading game portal with featured picks, category discovery, and zero-install reading.
                  </p>
                </div>

                <div className="flex min-h-44 flex-col rounded-md bg-slate-100 p-4">
                  <label className="text-xs font-black uppercase tracking-widest text-slate-500">Search</label>
                  <div className="mt-2 min-h-12 truncate rounded-md border border-slate-300 bg-white px-3 py-3 text-sm font-bold text-slate-500">
                    {nowPlaying[0] ? titleCase(nowPlaying[0].title) : 'Search games'}
                  </div>
                  {nowPlaying[1] && (
                    <Link
                      href={`/${nowPlaying[1].cat1}/${nowPlaying[1].cat2}/${nowPlaying[1].slug}`}
                      className="mt-3 line-clamp-2 rounded-md bg-emerald-400 px-4 py-3 text-sm font-black text-slate-950 hover:bg-amber-300"
                    >
                      {titleCase(nowPlaying[1].title)}
                    </Link>
                  )}
                </div>
              </div>
            </section>

            <div id="games" className="mt-5 grid gap-5">
              <section>
                <div className="mb-3 flex items-center justify-between gap-3">
                  <h2 className="text-xl font-black text-white">Featured Games</h2>
                  <span className="rounded-md bg-white/10 px-3 py-1 text-xs font-black text-emerald-200">{featured.length}</span>
                </div>
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
                  {featured.map((article, idx) => (
                    <Link
                      href={`/${article.cat1}/${article.cat2}/${article.slug}`}
                      key={`${article.cat1}-${article.cat2}-${article.slug}-featured`}
                      className="group overflow-hidden rounded-md bg-white p-2 text-slate-950 shadow-md shadow-black/20"
                    >
                      <div className={`relative mb-2 aspect-[4/3] overflow-hidden rounded bg-gradient-to-br ${pickTone(idx)} p-3`}>
                        <span className="rounded bg-slate-950/90 px-2 py-1 text-[10px] font-black uppercase text-white">
                          {idx % 2 ? 'Popular' : 'New'}
                        </span>
                        <div className="absolute bottom-2 right-2 text-4xl font-black text-white/80 sm:text-5xl">
                          {titleCase(article.title).charAt(0)}
                        </div>
                      </div>
                      <h3 className="line-clamp-2 min-h-10 text-sm font-black leading-snug group-hover:text-emerald-700">
                        {titleCase(article.title)}
                      </h3>
                    </Link>
                  ))}
                </div>
              </section>

              <section>
                <div className="mb-3 flex items-center justify-between gap-3">
                  <h2 className="text-xl font-black text-white">Top Picks</h2>
                  <span className="rounded-md bg-white/10 px-3 py-1 text-xs font-black text-amber-200">{topPicks.length}</span>
                </div>
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
                  {topPicks.map((article, idx) => (
                    <Link
                      href={`/${article.cat1}/${article.cat2}/${article.slug}`}
                      key={`${article.cat1}-${article.cat2}-${article.slug}-top`}
                      className="group overflow-hidden rounded-md bg-white text-slate-950 shadow-md shadow-black/20"
                    >
                      <div className={`relative aspect-[4/3] bg-gradient-to-br ${pickTone(idx + 3)} p-2`}>
                        <span className="rounded bg-white/90 px-2 py-1 text-[10px] font-black uppercase text-slate-950">
                          {idx % 3 === 0 ? 'Popular' : 'New'}
                        </span>
                        <div className="absolute bottom-2 right-2 text-3xl font-black text-white/80">
                          {titleCase(article.title).charAt(0)}
                        </div>
                      </div>
                      <div className="p-2">
                        <h3 className="line-clamp-2 min-h-8 text-xs font-black leading-snug group-hover:text-emerald-700">
                          {titleCase(article.title)}
                        </h3>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            </div>

            <section id="articles" className="mt-6">
              <div className="mb-3 flex items-center justify-between gap-3">
                <h2 className="text-xl font-black text-white">Latest Articles</h2>
                <span className="rounded-md bg-white/10 px-3 py-1 text-xs font-black text-slate-200">{latest.length}</span>
              </div>
              <div className="grid gap-2 md:grid-cols-2">
                {latest.map((article, idx) => (
                  <Link
                    href={`/${article.cat1}/${article.cat2}/${article.slug}`}
                    key={`${article.cat1}-${article.cat2}-${article.slug}-latest`}
                    className="grid grid-cols-[48px_minmax(0,1fr)] items-center gap-3 rounded-md bg-white p-2.5 text-slate-950 shadow-sm hover:bg-emerald-50 sm:grid-cols-[54px_minmax(0,1fr)_auto]"
                  >
                    <span className={`flex h-12 w-12 items-center justify-center rounded bg-gradient-to-br ${pickTone(idx)} text-sm font-black text-white`}>
                      {String(hashString(article.originalFileName) % 999).padStart(3, '0')}
                    </span>
                    <span className="line-clamp-2 text-sm font-black leading-snug">
                      {titleCase(article.title)}
                    </span>
                    <span className="hidden rounded bg-slate-100 px-3 py-2 text-xs font-black text-slate-500 sm:inline">Read More</span>
                  </Link>
                ))}
              </div>
            </section>

            <section id="games" className="mt-12">
              <div className="mb-3 flex items-center justify-between gap-3">
                <h2 className="text-xl font-black text-white">Popular Games</h2>
                <Link href="/game" className="text-xs font-black text-emerald-400 hover:text-emerald-300">
                  View All →
                </Link>
              </div>
              <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                {gameSlice.map((game, idx) => (
                  <Link
                    href={`/game/${game.slug}`}
                    key={`game-${game.id}`}
                    className="group overflow-hidden rounded-md bg-white text-slate-950 shadow-md shadow-black/20 transition hover:shadow-lg"
                  >
                    <div className="relative aspect-square overflow-hidden bg-slate-200">
                      <img
                        src={`/img/class-${game.id}.webp`}
                        alt={game.title}
                        className="h-full w-full object-cover transition group-hover:scale-110"
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent opacity-0 transition group-hover:opacity-100" />
                    </div>
                    <div className="p-3">
                      <h3 className="line-clamp-2 text-sm font-black leading-snug">
                        {titleCase(game.title)}
                      </h3>
                      <div className="mt-2 flex flex-wrap gap-1">
                        {game.cat.slice(0, 2).map((cat) => (
                          <span
                            key={cat}
                            className="inline-block rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-bold text-emerald-800"
                          >
                            {cat}
                          </span>
                        ))}
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            </section>
          </div>
        </div>
      </div>
    </main>
  );
}
