// src/components/billing/public-pricing.tsx — PUBLIC pricing UI for /pricing.
// Marketing sibling of plan-grid.tsx: same visual language, but ZERO auth
// coupling — every CTA is a plain Link whose target the server page decided
// (signup vs settings/billing). Adds what the in-app grid doesn't have: a
// USD/EUR toggle (nominal parity — same number, different currency symbol)
// and the full limits comparison table, Enterprise included.
"use client";

import { CheckIcon, MailIcon, SparklesIcon } from "lucide-react";
import Link from "next/link";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { PLANS, type PlanLimits, type PlanName } from "@/lib/billing/plans";
import { cn } from "@/lib/utils";

const PLAN_LABELS: Record<PlanName, string> = {
  solo: "Solo",
  starter: "Starter",
  pro: "Pro",
  agency: "Agency",
};

const PLAN_DESC_KEYS = {
  solo: "planSoloDesc",
  starter: "planStarterDesc",
  pro: "planProDesc",
  agency: "planAgencyDesc",
} as const;

type Currency = "USD" | "EUR";

/** Comparison-table rows: i18n column key + the limit it reads. */
const COMPARE_ROWS = [
  { key: "colKeywords", limit: "keywords" },
  { key: "colProjects", limit: "projects" },
  { key: "colSeats", limit: "seats" },
  { key: "colIntegrations", limit: "integrations" },
  { key: "colBacklinks", limit: "backlinkRows" },
  { key: "colMcp", limit: "mcpMonthly" },
] as const satisfies readonly { key: string; limit: keyof PlanLimits }[];

export function PublicPricing({
  ctaHref,
  ctaLabel,
}: {
  ctaHref: string;
  ctaLabel: string;
}) {
  const t = useTranslations("Pricing");
  const tBilling = useTranslations("Billing");
  const locale = useLocale();
  const [annual, setAnnual] = useState(false);
  const [currency, setCurrency] = useState<Currency>("USD");

  // Nominal parity: the SAME number in both currencies ($49 ⇄ 49 €) — only
  // the Intl currency changes. The active locale drives symbol placement
  // (en → "€49", fr/es/de → "49 €") and thousands separators.
  const price = (cents: number) =>
    new Intl.NumberFormat(locale, {
      style: "currency",
      currency,
      minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
      maximumFractionDigits: 2,
    }).format(cents / 100);

  const num = (n: number) => new Intl.NumberFormat(locale).format(n);

  return (
    <div className="flex flex-col gap-10">
      {/* ── Hero ─────────────────────────────────────────────────────── */}
      <div className="flex flex-col items-center gap-3 text-center">
        <Badge
          variant="secondary"
          className="border-primary/30 bg-primary/15 text-primary"
        >
          <SparklesIcon className="size-3" />
          {t("trialBanner")}
        </Badge>
        <h1 className="font-heading font-semibold text-4xl tracking-tight">
          {t("heroTitle")}
        </h1>
        <p className="max-w-2xl text-balance text-muted-foreground">
          {t("heroSubtitle")}
        </p>
      </div>

      {/* ── Toggles: interval + currency ─────────────────────────────── */}
      <div className="flex flex-wrap items-center justify-center gap-3">
        <div className="inline-flex items-center rounded-lg border bg-muted/40 p-1">
          <ToggleButton active={!annual} onClick={() => setAnnual(false)}>
            {tBilling("monthly")}
          </ToggleButton>
          <ToggleButton active={annual} onClick={() => setAnnual(true)}>
            {tBilling("annual")}
            <Badge
              variant="secondary"
              className="border-primary/30 bg-primary/15 text-primary"
            >
              {tBilling("annualSavings")}
            </Badge>
          </ToggleButton>
        </div>
        <div className="inline-flex items-center rounded-lg border bg-muted/40 p-1">
          <ToggleButton
            active={currency === "USD"}
            onClick={() => setCurrency("USD")}
          >
            USD $
          </ToggleButton>
          <ToggleButton
            active={currency === "EUR"}
            onClick={() => setCurrency("EUR")}
          >
            EUR €
          </ToggleButton>
        </div>
      </div>

      {/* ── Plan cards ───────────────────────────────────────────────── */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {PLANS.map((plan) => {
          const isPro = plan.name === "pro";
          const monthlyEquivalent = annual
            ? Math.round(plan.annualUsd / 12)
            : plan.monthlyUsd;
          return (
            <Card
              key={plan.name}
              className={cn(
                "flex flex-col",
                isPro &&
                  "border-primary/50 bg-primary/[0.03] shadow-lg ring-1 ring-primary/30",
              )}
            >
              <CardHeader>
                <CardTitle>{PLAN_LABELS[plan.name]}</CardTitle>
                <CardDescription>
                  {tBilling(PLAN_DESC_KEYS[plan.name])}
                </CardDescription>
                <div className="flex items-baseline gap-1 pt-1">
                  <span className="font-heading font-semibold text-3xl tracking-tight">
                    {price(monthlyEquivalent)}
                  </span>
                  <span className="text-muted-foreground text-sm">
                    {tBilling("perMonth")}
                  </span>
                </div>
                {annual ? (
                  <p className="text-muted-foreground text-xs">
                    {t("perMonthEq")} —{" "}
                    {tBilling("billedAnnually", {
                      price: price(plan.annualUsd),
                    })}
                  </p>
                ) : null}
              </CardHeader>
              <CardContent className="flex-1">
                <ul className="flex flex-col gap-2 text-sm">
                  <FeatureItem
                    label={tBilling("featKeywords", {
                      count: plan.limits.keywords,
                    })}
                  />
                  <FeatureItem
                    label={tBilling("featProjects", {
                      count: plan.limits.projects,
                    })}
                  />
                  <FeatureItem
                    label={tBilling("featSeats", { count: plan.limits.seats })}
                  />
                  <FeatureItem
                    label={tBilling("featMcp", {
                      count: plan.limits.mcpMonthly,
                    })}
                  />
                </ul>
              </CardContent>
              <CardFooter>
                <Button
                  className="w-full"
                  variant={isPro ? "default" : "outline"}
                  asChild
                >
                  <Link href={ctaHref}>{ctaLabel}</Link>
                </Button>
              </CardFooter>
            </Card>
          );
        })}
      </div>

      {/* ── Enterprise ───────────────────────────────────────────────── */}
      <Card>
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <CardHeader className="flex-1">
            <CardTitle>{t("enterprise")}</CardTitle>
            <CardDescription>{tBilling("enterpriseDesc")}</CardDescription>
          </CardHeader>
          <CardFooter className="flex items-center gap-4 sm:pt-6">
            <span className="font-heading font-semibold text-xl tracking-tight">
              {t("onQuote")}
            </span>
            <Button variant="outline" asChild>
              <a href="mailto:contact@elevaseo.com">
                <MailIcon className="size-4" />
                {tBilling("contactUs")}
              </a>
            </Button>
          </CardFooter>
        </div>
      </Card>

      {/* ── Comparison table ─────────────────────────────────────────── */}
      <section className="flex flex-col gap-4">
        <h2 className="text-center font-heading font-semibold text-2xl tracking-tight">
          {t("compare")}
        </h2>
        <div className="overflow-x-auto rounded-lg border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="min-w-44" />
                {PLANS.map((plan) => (
                  <TableHead
                    key={plan.name}
                    className={cn(
                      "text-center font-medium",
                      plan.name === "pro" && "text-primary",
                    )}
                  >
                    {PLAN_LABELS[plan.name]}
                  </TableHead>
                ))}
                <TableHead className="text-center font-medium">
                  {t("enterprise")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {COMPARE_ROWS.map((row) => (
                <TableRow key={row.key}>
                  <TableCell className="font-medium text-muted-foreground">
                    {t(row.key)}
                  </TableCell>
                  {PLANS.map((plan) => {
                    const value = plan.limits[row.limit];
                    return (
                      <TableCell
                        key={plan.name}
                        className={cn(
                          "text-center tabular-nums",
                          plan.name === "pro" && "bg-primary/[0.03]",
                        )}
                      >
                        {value === -1 ? t("unlimited") : num(value)}
                      </TableCell>
                    );
                  })}
                  <TableCell className="text-center text-muted-foreground">
                    {t("onQuote")}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
        <p className="text-center text-muted-foreground text-sm">
          {t("packsNote")}
        </p>
      </section>
    </div>
  );
}

function ToggleButton({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-pressed={active}
      className={cn(
        "flex items-center gap-2 rounded-md px-3.5 py-1.5 font-medium text-sm transition-colors",
        active
          ? "bg-background text-foreground shadow-sm"
          : "text-muted-foreground hover:text-foreground",
      )}
    >
      {children}
    </button>
  );
}

function FeatureItem({ label }: { label: string }) {
  return (
    <li className="flex items-start gap-2">
      <CheckIcon className="mt-0.5 size-4 shrink-0 text-primary" />
      <span>{label}</span>
    </li>
  );
}
