"use client";

import { useMemo, useState, useCallback } from "react";
import type { PublicDonation, PublicRegion, PublicTier } from "@/types/public";
import type { TierId } from "@/lib/tiers";
import DonateModal from "./DonateModal";

interface Props {
  regions: PublicRegion[];
  donations: PublicDonation[];
  tiers: Record<string, PublicTier>;
  namingRights: { claimed: boolean; by: string | null };
}

// Image is 1536x1024
const VB_W = 1536;
const VB_H = 1024;

function formatUSDClient(cents: number): string {
  const dollars = cents / 100;
  if (Number.isInteger(dollars)) return `$${dollars.toLocaleString("en-US")}`;
  return `$${dollars.toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
}

export default function HouseInteractive({
  regions,
  donations,
  tiers,
  namingRights,
}: Props) {
  const [hovered, setHovered] = useState<string | null>(null);
  const [modalRegion, setModalRegion] = useState<PublicRegion | null>(null);

  const donationsByRegion = useMemo(() => {
    const m = new Map<string, PublicDonation>();
    for (const d of donations) m.set(d.regionId, d);
    return m;
  }, [donations]);

  const onRegionClick = useCallback(
    (r: PublicRegion) => {
      const existing = donationsByRegion.get(r.id);
      if (existing) {
        // If a website URL is set, open in new tab.
        if (existing.websiteUrl) {
          window.open(existing.websiteUrl, "_blank", "noopener,noreferrer");
        }
        return;
      }
      if (r.tier === "naming-rights" && namingRights.claimed) return;
      setModalRegion(r);
    },
    [donationsByRegion, namingRights.claimed],
  );

  const polyToPoints = (poly: [number, number][]) =>
    poly.map(([x, y]) => `${x * VB_W},${y * VB_H}`).join(" ");

  // Find hovered region info for tooltip.
  const hoveredRegion = hovered ? regions.find((r) => r.id === hovered) : null;
  const hoveredDonation = hoveredRegion
    ? donationsByRegion.get(hoveredRegion.id)
    : null;
  const hoveredTier = hoveredRegion ? tiers[hoveredRegion.tier] : null;

  // Naming rights button (entire house) — separate from polygon hotspot.
  const namingTier = tiers["naming-rights"];

  return (
    <div className="mx-auto mt-8 w-full max-w-[1100px]">
      <div className="relative w-full">
        <img
          src="/house.png"
          alt="A two-story brick house illustration"
          className="block w-full select-none rounded-lg shadow-lg"
          draggable={false}
        />
        {namingRights.claimed && namingRights.by && (
          <div className="naming-banner">
            The {namingRights.by} House
          </div>
        )}
        <svg
          viewBox={`0 0 ${VB_W} ${VB_H}`}
          className="pointer-events-none absolute inset-0 h-full w-full"
          preserveAspectRatio="none"
        >
          {regions.map((r) => {
            const filled = donationsByRegion.has(r.id);
            const isHovered = hovered === r.id;
            return (
              <polygon
                key={r.id}
                points={polyToPoints(r.polygon)}
                className={`hotspot pointer-events-auto tier-${r.tier} ${
                  filled ? "filled" : ""
                } ${isHovered ? "is-hover" : ""}`}
                onMouseEnter={() => setHovered(r.id)}
                onMouseLeave={() =>
                  setHovered((h) => (h === r.id ? null : h))
                }
                onClick={() => onRegionClick(r)}
              />
            );
          })}
        </svg>

        {hoveredRegion && hoveredTier && (
          <div className="pointer-events-none absolute left-1/2 top-2 -translate-x-1/2 rounded-md bg-text/90 px-3 py-1.5 text-xs text-white shadow">
            {hoveredDonation ? (
              <>
                <span className="font-semibold">
                  {hoveredDonation.displayName ?? "Anonymous"}
                </span>{" "}
                — &ldquo;{hoveredDonation.message}&rdquo;
              </>
            ) : (
              <>
                {hoveredTier.label} —{" "}
                <span className="font-semibold">
                  {formatUSDClient(hoveredRegion.priceCents)}
                </span>
              </>
            )}
          </div>
        )}
      </div>

      {/* Tier legend */}
      <div className="mx-auto mt-8 grid max-w-3xl grid-cols-2 gap-3 text-sm md:grid-cols-3">
        {Object.values(tiers)
          .filter((t) => t.id !== "naming-rights")
          .map((t) => (
            <div
              key={t.id}
              className="rounded-lg border border-border bg-surface p-3"
            >
              <div className="font-medium text-text">{t.label}</div>
              <div className="text-xs text-textmuted">
                {formatUSDClient(t.priceCents)}
              </div>
            </div>
          ))}
      </div>

      {/* Naming rights CTA */}
      {namingTier && (
        <div className="mx-auto mt-6 max-w-3xl">
          {namingRights.claimed ? (
            <div className="rounded-2xl border border-primary/30 bg-primary/5 p-5 text-center text-sm text-text">
              Naming rights have been claimed by{" "}
              <span className="font-semibold">{namingRights.by}</span>.
            </div>
          ) : (
            <button
              type="button"
              onClick={() =>
                setModalRegion({
                  id: "naming-rights",
                  tier: "naming-rights" as TierId,
                  polygon: [],
                  priceCents: namingTier.priceCents,
                })
              }
              className="block w-full rounded-2xl border border-primary bg-white p-5 text-center text-sm font-medium text-primary hover:bg-primary hover:text-white"
            >
              Claim naming rights for the entire house —{" "}
              {formatUSDClient(namingTier.priceCents)}
            </button>
          )}
        </div>
      )}

      {modalRegion && (
        <DonateModal
          region={modalRegion}
          tier={tiers[modalRegion.tier]}
          onClose={() => setModalRegion(null)}
        />
      )}
    </div>
  );
}
