import prisma from "@/lib/prisma";
import Link from "next/link";
import { SidebarCountryList } from "./sidebar-country-list";

export async function Sidebar() {
  let topCountries: { id: number; name: string; slug: string; count: number }[] = [];
  let otherCountries: { id: number; name: string; slug: string; count: number }[] = [];

  try {
    const countries = await prisma.country.findMany({
      where: { active: true },
      select: {
        id: true,
        name: true,
        slug: true,
        _count: { select: { users: true } },
      },
    });

    const sorted = countries
      .map((c) => ({ id: c.id, name: c.name, slug: c.slug, count: c._count.users }))
      .sort((a, b) => b.count - a.count);

    topCountries = sorted.filter((c) => c.count > 0).slice(0, 10);
    otherCountries = sorted.filter((c) => !topCountries.includes(c));
  } catch (error) {
    console.error("Sidebar query failed:", error);
    // Sidebar renders empty if DB query fails — page still loads
  }

  return (
    <aside className="hidden w-64 shrink-0 border-r border-surface-light bg-surface p-4 lg:block">
      <div className="sticky top-20">
        <h3 className="font-semibold text-sm uppercase text-text-muted mb-3">
          Browse by Country
        </h3>

        {/* Top countries with profile counts */}
        <ul className="space-y-0.5">
          {topCountries.map((country) => (
            <li key={country.id}>
              <Link
                href={`/escorts/${country.slug}`}
                className="text-sm text-text-muted hover:text-white transition-colors flex items-center justify-between py-1.5 px-2 rounded hover:bg-surface-light"
              >
                <span>{country.name}</span>
                <span className="text-xs text-text-muted bg-surface-light px-1.5 py-0.5 rounded">
                  {country.count.toLocaleString()}
                </span>
              </Link>
            </li>
          ))}
        </ul>

        {/* Searchable dropdown for all other countries */}
        {otherCountries.length > 0 && (
          <SidebarCountryList countries={otherCountries} />
        )}

        <Link
          href="/escorts-cities"
          className="text-sm text-primary hover:text-primary-light mt-3 block"
        >
          View all cities &rarr;
        </Link>
      </div>
    </aside>
  );
}
