import { CtaBand } from "@/components/public/cta-band";
import { FaqSection } from "@/components/public/faq";
import { PublicFooter } from "@/components/public/footer";
import { LandingHero } from "@/components/public/hero";
import { HowItWorks } from "@/components/public/how-it-works";
import { LandingStyles } from "@/components/public/landing-styles";
import { PublicNavbar } from "@/components/public/navbar";
import {
  PopularServices,
  type PopularService,
} from "@/components/public/popular-services";
import { StatsBand, type LandingStats } from "@/components/public/stats-band";
import { db } from "@/lib/db";
import { money } from "@/lib/serialize";
import { getGeneralSettings } from "@/lib/settings";

type LandingData = {
  stats: LandingStats;
  platformsCount: number;
  services: PopularService[];
};

const EMPTY: LandingData = {
  stats: {
    totalOrders: 0,
    completedOrders: 0,
    servicesCount: 0,
    avgMinutes: 0,
  },
  platformsCount: 0,
  services: [],
};

/** Coarse rounding so the hero stat reads "18h" instead of "17h 43m". */
function roundMinutes(minutes: number): number {
  if (!Number.isFinite(minutes) || minutes <= 0) return 0;
  if (minutes >= 120) return Math.round(minutes / 60) * 60;
  return Math.max(5, Math.round(minutes / 5) * 5);
}

async function loadLandingData(): Promise<LandingData> {
  try {
    const [
      general,
      totalOrders,
      completedOrders,
      servicesCount,
      platformRows,
      serviceTiming,
      topServices,
      recentCompleted,
    ] = await Promise.all([
      getGeneralSettings(),
      db.order.count(),
      db.order.count({ where: { status: "COMPLETED" } }),
      db.service.count({ where: { active: true } }),
      db.category.findMany({
        where: { active: true },
        select: { platform: true },
      }),
      db.service.aggregate({
        where: { active: true },
        _avg: { averageTimeMinutes: true },
      }),
      db.service.findMany({
        where: { active: true, category: { active: true } },
        orderBy: { orders: { _count: "desc" } },
        take: 6,
        select: {
          id: true,
          name: true,
          rate: true,
          min: true,
          max: true,
          averageTimeMinutes: true,
          category: { select: { name: true, platform: true } },
        },
      }),
      db.order.findMany({
        where: { status: "COMPLETED" },
        orderBy: { updatedAt: "desc" },
        take: 200,
        select: { createdAt: true, updatedAt: true },
      }),
    ]);

    const symbol = general.currencySymbol || "$";

    let measured = 0;
    if (recentCompleted.length > 0) {
      const total = recentCompleted.reduce(
        (sum, order) =>
          sum +
          Math.max(0, order.updatedAt.getTime() - order.createdAt.getTime()),
        0,
      );
      measured = total / recentCompleted.length / 60_000;
    }
    const avgMinutes =
      roundMinutes(measured) ||
      roundMinutes(serviceTiming._avg.averageTimeMinutes ?? 0);

    return {
      stats: {
        totalOrders,
        completedOrders,
        servicesCount,
        avgMinutes,
      },
      platformsCount: new Set(platformRows.map((row) => row.platform)).size,
      services: topServices.map((service) => ({
        id: service.id,
        name: service.name,
        platform: service.category.platform,
        categoryName: service.category.name,
        rate: money(service.rate, symbol),
        min: service.min,
        max: service.max,
        averageTimeMinutes: service.averageTimeMinutes,
      })),
    };
  } catch {
    // The landing page must render even if the database is unreachable.
    return EMPTY;
  }
}

/** Public marketing page shown at `/` to signed-out visitors. */
export async function LandingPage() {
  const data = await loadLandingData();

  return (
    <div className="flex min-h-screen flex-col bg-background">
      <LandingStyles />
      <PublicNavbar overlay />
      <main className="flex-1">
        <LandingHero
          servicesCount={data.stats.servicesCount}
          platformsCount={data.platformsCount}
        />
        <StatsBand stats={data.stats} />
        <HowItWorks />
        <PopularServices services={data.services} />
        <FaqSection />
        <CtaBand />
      </main>
      <PublicFooter />
    </div>
  );
}

export default LandingPage;
