import { prisma, getOrCreateSettings } from "@/lib/db";
import { REGIONS } from "@/lib/regions";
import { TIERS, priceForRegion, formatUSD } from "@/lib/tiers";
import { sanitizeForDisplay, safeUrl } from "@/lib/sanitize";
import HouseInteractive from "@/components/HouseInteractive";
import type { PublicDonation, PublicRegion } from "@/types/public";

export const dynamic = "force-dynamic";
export const metadata = { title: "Donate — PIFF" };

export default async function DonatePage() {
  const [approved, settings] = await Promise.all([
    prisma.donation.findMany({
      where: { status: "APPROVED" },
      select: {
        id: true,
        regionId: true,
        tierId: true,
        amountCents: true,
        donorName: true,
        message: true,
        websiteUrl: true,
        isAnonymous: true,
      },
    }),
    getOrCreateSettings(),
  ]);

  // Regions, scrubbed for client.
  const publicRegions: PublicRegion[] = REGIONS.map((r) => ({
    id: r.id,
    tier: r.tier,
    polygon: r.polygon,
    priceCents: priceForRegion(r.id, r.tier),
  }));

  const publicDonations: PublicDonation[] = approved.map((d) => ({
    id: d.id,
    regionId: d.regionId,
    tierId: d.tierId,
    amountCents: d.amountCents,
    displayName: d.isAnonymous ? null : d.donorName ?? null,
    message: sanitizeForDisplay(d.message),
    websiteUrl: d.isAnonymous ? null : safeUrl(d.websiteUrl),
  }));

  const goalCents = settings.goalCents || 25_000_000;
  const raisedCents = settings.totalRaisedCents || 0;

  const tiersForClient = Object.fromEntries(
    Object.entries(TIERS).map(([k, v]) => [
      k,
      { id: v.id, label: v.label, priceCents: v.priceCents, description: v.description },
    ]),
  );

  return (
    <section className="px-2 py-10 md:px-6">
      <div className="mx-auto max-w-3xl text-center">
        <h1 className="font-display text-3xl font-bold text-text md:text-4xl">
          Pick a piece. Leave your mark.
        </h1>
        <p className="mt-3 text-textmuted">
          Hover the house to see what each piece costs. Click to dedicate it.
        </p>
      </div>

      <HouseInteractive
        regions={publicRegions}
        donations={publicDonations}
        tiers={tiersForClient}
        namingRights={{
          claimed: settings.namingRightsClaimed,
          by: settings.namingRightsBy,
        }}
      />

      <div className="mx-auto mt-10 max-w-3xl rounded-2xl border border-border bg-surface p-6">
        <div className="flex items-baseline justify-between">
          <div className="text-sm text-textmuted">Raised toward the first home</div>
          <div className="font-display text-2xl font-bold text-primary">
            {formatUSD(raisedCents)}
          </div>
        </div>
        <div className="mt-2 h-2 overflow-hidden rounded-full bg-border">
          <div
            className="h-full bg-primary"
            style={{
              width: `${Math.min(100, (raisedCents / goalCents) * 100)}%`,
            }}
          />
        </div>
        <div className="mt-2 text-xs text-textmuted">
          Goal: {formatUSD(goalCents)}
        </div>
      </div>
    </section>
  );
}
