"use client";

import {
  useState,
  useCallback,
  useEffect,
  useMemo,
  type FormEvent,
} from "react";
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";
import {
  Calculator,
  TrendingUp,
  DollarSign,
  Users,
  Building2,
  Share2,
  Download,
  ArrowRight,
  CheckCircle,
  Loader2,
  AlertCircle,
} from "lucide-react";
import Link from "next/link";
import type { Lang } from "@/lib/config";

// ---------------------------------------------------------------------------
// CSRF helper (matches InlineEmailForm pattern)
// ---------------------------------------------------------------------------
function getCSRFToken(): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(/csrf-token=([^;]+)/);
  return match ? decodeURIComponent(match[1]) : null;
}

// ---------------------------------------------------------------------------
// GCC country / currency config
// ---------------------------------------------------------------------------
const GCC_COUNTRIES = {
  SA: {
    nameEn: "Saudi Arabia",
    nameAr: "المملكة العربية السعودية",
    currency: "SAR",
    symbol: "﷼",
    defaultSalary: 5000,
    exchangeRate: 4.69,
  },
  AE: {
    nameEn: "UAE",
    nameAr: "الإمارات",
    currency: "AED",
    symbol: "د.إ",
    defaultSalary: 5500,
    exchangeRate: 4.59,
  },
  QA: {
    nameEn: "Qatar",
    nameAr: "قطر",
    currency: "QAR",
    symbol: "ر.ق",
    defaultSalary: 5000,
    exchangeRate: 4.56,
  },
  KW: {
    nameEn: "Kuwait",
    nameAr: "الكويت",
    currency: "KWD",
    symbol: "د.ك",
    defaultSalary: 400,
    exchangeRate: 0.39,
  },
  BH: {
    nameEn: "Bahrain",
    nameAr: "البحرين",
    currency: "BHD",
    symbol: "د.ب",
    defaultSalary: 500,
    exchangeRate: 0.47,
  },
  OM: {
    nameEn: "Oman",
    nameAr: "عمان",
    currency: "OMR",
    symbol: "ر.ع",
    defaultSalary: 500,
    exchangeRate: 0.48,
  },
} as const;

type CountryCode = keyof typeof GCC_COUNTRIES;

// ---------------------------------------------------------------------------
// Bilingual content
// ---------------------------------------------------------------------------
const content = {
  en: {
    title: "How Much Are No-Shows Costing You?",
    subtitle: "Free ROI Calculator for GCC Clinics & Service Businesses",
    countryLabel: "Country",
    appointmentsLabel: "Monthly Appointments",
    appointmentValueLabel: "Avg. Appointment Value",
    noShowRateLabel: "Current No-Show Rate",
    receptionistSalaryLabel: "Receptionist Monthly Salary",
    receptionistCountLabel: "Number of Receptionists",
    resultsTitle: "Your Annual Impact",
    losingLabel: "You're losing to no-shows",
    receptionistCostLabel: "Receptionist costs",
    savingsLabel: "With Mawidi: saved in Year 1",
    roiLabel: "ROI",
    paybackLabel: "Pays for itself in",
    days: "days",
    perYear: "/year",
    currentCosts: "Current Costs",
    withMawidi: "With Mawidi",
    noShowLosses: "No-Show Losses",
    staffCosts: "Staff Costs",
    mawidiCost: "Mawidi Cost",
    recovered: "Recovered Revenue",
    leadTitle: "Get Your Full Personalized Savings Report",
    leadSubtitle:
      "We'll email you a detailed PDF with breakdowns, benchmarks, and an action plan.",
    nameLabel: "Full Name",
    emailLabel: "Work Email",
    phoneLabel: "Phone Number",
    companyLabel: "Clinic / Company Name",
    submitButton: "Send My Report",
    submitting: "Sending...",
    successMessage:
      "Report sent! Check your email for your personalized savings report.",
    errorGeneric: "Something went wrong. Please try again.",
    errorValidation: "Please fill in all required fields.",
    errorBot: "Verification failed. Please try again.",
    shareTitle: "Share Your Results",
    shareButton: "Copy Link",
    copied: "Copied!",
    ctaPrimary: "Start Your 14-Day Free Trial",
    ctaSecondary: "Try Our WhatsApp Demo",
    ctaTertiary: "Book a Demo Call",
    ctaTagline: "Join 200+ GCC businesses that reduced no-shows by 70%",
    privacyNote: "We respect your privacy. Unsubscribe anytime.",
  },
  ar: {
    title: "كم تكلفك حالات عدم الحضور؟",
    subtitle: "حاسبة العائد المجانية للعيادات والشركات الخدمية في الخليج",
    countryLabel: "الدولة",
    appointmentsLabel: "المواعيد الشهرية",
    appointmentValueLabel: "متوسط قيمة الموعد",
    noShowRateLabel: "نسبة عدم الحضور الحالية",
    receptionistSalaryLabel: "راتب موظف الاستقبال الشهري",
    receptionistCountLabel: "عدد موظفي الاستقبال",
    resultsTitle: "التأثير السنوي",
    losingLabel: "تخسر بسبب عدم الحضور",
    receptionistCostLabel: "تكلفة موظفي الاستقبال",
    savingsLabel: "مع موعدي: التوفير في السنة الأولى",
    roiLabel: "العائد على الاستثمار",
    paybackLabel: "يسترد تكلفته في",
    days: "يوم",
    perYear: "/سنة",
    currentCosts: "التكاليف الحالية",
    withMawidi: "مع موعدي",
    noShowLosses: "خسائر عدم الحضور",
    staffCosts: "تكاليف الموظفين",
    mawidiCost: "تكلفة موعدي",
    recovered: "الإيرادات المستردة",
    leadTitle: "احصل على تقرير التوفير الشخصي الكامل",
    leadSubtitle: "سنرسل لك ملف PDF مفصل بالتحليلات والمقارنات وخطة العمل.",
    nameLabel: "الاسم الكامل",
    emailLabel: "البريد الإلكتروني للعمل",
    phoneLabel: "رقم الهاتف",
    companyLabel: "اسم العيادة / الشركة",
    submitButton: "أرسل تقريري",
    submitting: "جاري الإرسال...",
    successMessage:
      "تم الإرسال! تحقق من بريدك الإلكتروني لتقرير التوفير الشخصي.",
    errorGeneric: "حدث خطأ. يرجى المحاولة مرة أخرى.",
    errorValidation: "يرجى ملء جميع الحقول المطلوبة.",
    errorBot: "فشل التحقق. يرجى المحاولة مرة أخرى.",
    shareTitle: "شارك نتائجك",
    shareButton: "نسخ الرابط",
    copied: "تم النسخ!",
    ctaPrimary: "ابدأ تجربتك المجانية لمدة 14 يوم",
    ctaSecondary: "جرب عرض واتساب التجريبي",
    ctaTertiary: "احجز مكالمة تجريبية",
    ctaTagline: "انضم لأكثر من 200 شركة في الخليج قللت عدم الحضور بنسبة 70%",
    privacyNote: "نحترم خصوصيتك. إلغاء الاشتراك في أي وقت.",
  },
};

// ---------------------------------------------------------------------------
// Animated number component
// ---------------------------------------------------------------------------
function AnimatedNumber({
  value,
  prefix = "",
  suffix = "",
}: {
  value: number;
  prefix?: string;
  suffix?: string;
}) {
  const [displayed, setDisplayed] = useState(0);

  useEffect(() => {
    const duration = 1500;
    const start = Date.now();
    const startVal = displayed;
    const animate = () => {
      const elapsed = Date.now() - start;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3); // ease-out cubic
      setDisplayed(Math.round(startVal + (value - startVal) * eased));
      if (progress < 1) requestAnimationFrame(animate);
    };
    requestAnimationFrame(animate);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value]);

  return (
    <span>
      {prefix}
      {displayed.toLocaleString()}
      {suffix}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Simple bar chart component
// ---------------------------------------------------------------------------
function CostComparisonBar({
  label,
  value,
  maxValue,
  color,
  currencySymbol,
}: {
  label: string;
  value: number;
  maxValue: number;
  color: "red" | "green";
  currencySymbol: string;
}) {
  const percentage = maxValue > 0 ? Math.max((value / maxValue) * 100, 4) : 4;
  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-sm">
        <span className="font-medium text-slate-700 dark:text-slate-300">
          {label}
        </span>
        <span
          className={
            color === "red"
              ? "font-bold text-red-600 dark:text-red-400"
              : "font-bold text-brand-green"
          }
        >
          {currencySymbol} {value.toLocaleString()}
        </span>
      </div>
      <div className="h-4 w-full overflow-hidden rounded-full bg-slate-100 dark:bg-slate-800">
        <div
          className={`h-full rounded-full transition-all duration-1000 ease-out ${
            color === "red"
              ? "bg-gradient-to-r from-red-400 to-red-600"
              : "bg-gradient-to-r from-brand-green to-emerald-500"
          }`}
          style={{ width: `${Math.min(percentage, 100)}%` }}
        />
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main Calculator Client
// ---------------------------------------------------------------------------
export default function CalculatorClient({ lang }: { lang: Lang }) {
  const isAr = lang === "ar";
  const t = content[isAr ? "ar" : "en"];
  const { executeRecaptcha } = useGoogleReCaptcha();

  // --- Calculator inputs ---
  const [selectedCountry, setSelectedCountry] = useState<CountryCode>("SA");
  const [monthlyAppointments, setMonthlyAppointments] = useState(300);
  const [avgAppointmentValue, setAvgAppointmentValue] = useState(350);
  const [noShowRate, setNoShowRate] = useState(32);
  const [receptionistSalary, setReceptionistSalary] = useState<number>(
    GCC_COUNTRIES.SA.defaultSalary,
  );
  const [receptionistCount, setReceptionistCount] = useState(1);
  const [showResults, setShowResults] = useState(false);

  // --- Lead form ---
  const [showLeadForm, setShowLeadForm] = useState(false);
  const [leadForm, setLeadForm] = useState({
    name: "",
    email: "",
    phone: "",
    company: "",
  });
  const [honeypot, setHoneypot] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  // --- Share ---
  const [copied, setCopied] = useState(false);

  // Sync default salary when country changes
  useEffect(() => {
    setReceptionistSalary(GCC_COUNTRIES[selectedCountry].defaultSalary);
  }, [selectedCountry]);

  // Fetch CSRF token on mount
  useEffect(() => {
    fetch("/api/csrf").catch(() => {});
  }, []);

  // Show results after first interaction
  useEffect(() => {
    setShowResults(true);
  }, []);

  // --- Calculations ---
  const calculations = useMemo(() => {
    const country = GCC_COUNTRIES[selectedCountry];
    const monthlyNoShowLoss =
      monthlyAppointments * (noShowRate / 100) * avgAppointmentValue;
    const annualNoShowLoss = monthlyNoShowLoss * 12;
    const receptionistCost = receptionistSalary * receptionistCount * 12;
    // Starter plan ($179/mo) + setup ($199 one-time)
    const mawidiAnnualCost =
      179 * country.exchangeRate * 12 + 199 * country.exchangeRate;
    const recoveredRevenue = monthlyNoShowLoss * 0.7 * 12; // 70% reduction
    const netSavings = recoveredRevenue + receptionistCost - mawidiAnnualCost;
    const roi =
      mawidiAnnualCost > 0 ? (netSavings / mawidiAnnualCost) * 100 : 0;
    const paybackDays =
      netSavings > 0 ? Math.ceil(mawidiAnnualCost / (netSavings / 365)) : 999;
    return {
      monthlyNoShowLoss,
      annualNoShowLoss,
      receptionistCost,
      mawidiAnnualCost: Math.round(mawidiAnnualCost),
      recoveredRevenue,
      netSavings: Math.round(netSavings),
      roi: Math.round(roi),
      paybackDays,
    };
  }, [
    monthlyAppointments,
    avgAppointmentValue,
    noShowRate,
    receptionistSalary,
    receptionistCount,
    selectedCountry,
  ]);

  const currencySymbol = GCC_COUNTRIES[selectedCountry].symbol;

  // --- Lead form submit ---
  const handleLeadSubmit = useCallback(
    async (e: FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setSubmitError(null);

      // Honeypot check
      if (honeypot) return;

      // Basic validation
      if (
        !leadForm.name.trim() ||
        !leadForm.email.trim() ||
        !leadForm.phone.trim()
      ) {
        setSubmitError(t.errorValidation);
        return;
      }

      setIsSubmitting(true);

      try {
        let recaptchaToken = "";
        if (executeRecaptcha) {
          recaptchaToken = await executeRecaptcha("roi_calculator_lead");
        }

        const csrfToken = getCSRFToken();
        const response = await fetch("/api/leads/resource-download", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(csrfToken && { "x-csrf-token": csrfToken }),
          },
          body: JSON.stringify({
            name: leadForm.name.trim(),
            email: leadForm.email.trim(),
            phone: leadForm.phone.trim(),
            company: leadForm.company.trim() || undefined,
            resourceType: "roi-report",
            resourceTitle: "ROI Calculator",
            language: isAr ? "ar" : "en",
            recaptchaToken,
            metadata: {
              country: selectedCountry,
              monthlyAppointments,
              avgAppointmentValue,
              noShowRate,
              receptionistSalary,
              receptionistCount,
              annualNoShowLoss: calculations.annualNoShowLoss,
              netSavings: calculations.netSavings,
              roi: calculations.roi,
              paybackDays: calculations.paybackDays,
            },
          }),
        });

        if (!response.ok) {
          const data = await response.json();
          if (data.error?.includes("Bot verification")) {
            throw new Error(t.errorBot);
          }
          throw new Error(data.error || "Submission failed");
        }

        setSubmitSuccess(true);
      } catch (err) {
        console.error("Lead form error:", err);
        setSubmitError(err instanceof Error ? err.message : t.errorGeneric);
      } finally {
        setIsSubmitting(false);
      }
    },
    [
      leadForm,
      honeypot,
      executeRecaptcha,
      isAr,
      selectedCountry,
      monthlyAppointments,
      avgAppointmentValue,
      noShowRate,
      receptionistSalary,
      receptionistCount,
      calculations,
      t,
    ],
  );

  // --- Share ---
  const handleShare = useCallback(() => {
    const params = new URLSearchParams({
      c: selectedCountry,
      a: String(monthlyAppointments),
      v: String(avgAppointmentValue),
      n: String(noShowRate),
      s: String(receptionistSalary),
      r: String(receptionistCount),
    });
    const url = `${window.location.origin}/${lang}/tools/roi-calculator?${params.toString()}`;
    navigator.clipboard.writeText(url).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }, [
    selectedCountry,
    monthlyAppointments,
    avgAppointmentValue,
    noShowRate,
    receptionistSalary,
    receptionistCount,
    lang,
  ]);

  // --- Restore from URL params on mount ---
  useEffect(() => {
    if (typeof window === "undefined") return;
    const params = new URLSearchParams(window.location.search);
    const c = params.get("c") as CountryCode | null;
    if (c && c in GCC_COUNTRIES) setSelectedCountry(c);
    const a = params.get("a");
    if (a) setMonthlyAppointments(Number(a));
    const v = params.get("v");
    if (v) setAvgAppointmentValue(Number(v));
    const n = params.get("n");
    if (n) setNoShowRate(Number(n));
    const s = params.get("s");
    if (s) setReceptionistSalary(Number(s));
    const r = params.get("r");
    if (r) setReceptionistCount(Number(r));
  }, []);

  const barMax = Math.max(
    calculations.annualNoShowLoss + calculations.receptionistCost,
    calculations.mawidiAnnualCost,
  );

  return (
    <div
      className="mx-auto max-w-6xl px-4 py-12 sm:px-6 lg:px-8"
      dir={isAr ? "rtl" : "ltr"}
    >
      {/* ---------------------------------------------------------------- */}
      {/* HERO SECTION                                                     */}
      {/* ---------------------------------------------------------------- */}
      <header className="mb-12 text-center">
        <div className="mb-4 inline-flex items-center gap-2 rounded-full bg-brand-green/10 px-4 py-2 text-sm font-medium text-brand-green">
          <Calculator className="h-4 w-4" />
          <span>{isAr ? "أداة مجانية" : "Free Tool"}</span>
        </div>
        <h1 className="text-3xl font-bold text-slate-900 dark:text-white sm:text-4xl md:text-5xl">
          {t.title}
        </h1>
        <p className="mt-4 text-lg text-slate-600 dark:text-slate-400 md:text-xl">
          {t.subtitle}
        </p>
      </header>

      <div className="grid gap-8 lg:grid-cols-2">
        {/* ---------------------------------------------------------------- */}
        {/* INPUT SECTION                                                    */}
        {/* ---------------------------------------------------------------- */}
        <div className="space-y-6 rounded-2xl border border-slate-200 bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900 sm:p-8">
          <h2 className="flex items-center gap-2 text-xl font-bold text-slate-900 dark:text-white">
            <Building2 className="h-5 w-5 text-brand-green" />
            {isAr ? "بيانات عيادتك" : "Your Business Details"}
          </h2>

          {/* Country Selector */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-300">
              {t.countryLabel}
            </label>
            <div className="grid grid-cols-3 gap-2 sm:grid-cols-6">
              {(Object.keys(GCC_COUNTRIES) as CountryCode[]).map((code) => {
                const c = GCC_COUNTRIES[code];
                return (
                  <button
                    key={code}
                    type="button"
                    onClick={() => setSelectedCountry(code)}
                    className={`rounded-lg border px-3 py-2 text-xs font-medium transition-all ${
                      selectedCountry === code
                        ? "border-brand-green bg-brand-green/10 text-brand-green ring-2 ring-brand-green/20"
                        : "border-slate-200 bg-white text-slate-600 hover:border-brand-green/50 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-400"
                    }`}
                  >
                    {isAr ? c.nameAr : c.nameEn}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Monthly Appointments */}
          <SliderInput
            label={t.appointmentsLabel}
            value={monthlyAppointments}
            onChange={setMonthlyAppointments}
            min={50}
            max={2000}
            step={10}
            icon={<Users className="h-4 w-4" />}
            isAr={isAr}
          />

          {/* Avg Appointment Value */}
          <SliderInput
            label={t.appointmentValueLabel}
            value={avgAppointmentValue}
            onChange={setAvgAppointmentValue}
            min={50}
            max={2000}
            step={10}
            suffix={currencySymbol}
            icon={<DollarSign className="h-4 w-4" />}
            isAr={isAr}
          />

          {/* No-Show Rate */}
          <SliderInput
            label={t.noShowRateLabel}
            value={noShowRate}
            onChange={setNoShowRate}
            min={5}
            max={60}
            step={1}
            suffix="%"
            icon={<TrendingUp className="h-4 w-4" />}
            isAr={isAr}
            sliderColor="red"
          />

          {/* Receptionist Salary */}
          <SliderInput
            label={t.receptionistSalaryLabel}
            value={receptionistSalary}
            onChange={setReceptionistSalary}
            min={
              selectedCountry === "KW" ||
              selectedCountry === "BH" ||
              selectedCountry === "OM"
                ? 100
                : 1000
            }
            max={
              selectedCountry === "KW" ||
              selectedCountry === "BH" ||
              selectedCountry === "OM"
                ? 2000
                : 15000
            }
            step={
              selectedCountry === "KW" ||
              selectedCountry === "BH" ||
              selectedCountry === "OM"
                ? 50
                : 100
            }
            suffix={currencySymbol}
            icon={<Users className="h-4 w-4" />}
            isAr={isAr}
          />

          {/* Receptionist Count */}
          <SliderInput
            label={t.receptionistCountLabel}
            value={receptionistCount}
            onChange={setReceptionistCount}
            min={0}
            max={10}
            step={1}
            icon={<Users className="h-4 w-4" />}
            isAr={isAr}
          />
        </div>

        {/* ---------------------------------------------------------------- */}
        {/* RESULTS SECTION                                                  */}
        {/* ---------------------------------------------------------------- */}
        <div className="space-y-6">
          {showResults && (
            <>
              {/* Key metrics */}
              <div className="space-y-4 rounded-2xl border border-slate-200 bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900 sm:p-8">
                <h2 className="flex items-center gap-2 text-xl font-bold text-slate-900 dark:text-white">
                  <TrendingUp className="h-5 w-5 text-brand-green" />
                  {t.resultsTitle}
                </h2>

                {/* No-show losses */}
                <div className="rounded-xl border border-red-200 bg-red-50 p-4 dark:border-red-900/50 dark:bg-red-950/30">
                  <p className="text-sm font-medium text-red-800 dark:text-red-300">
                    {t.losingLabel}
                  </p>
                  <p className="text-2xl font-bold text-red-600 dark:text-red-400 sm:text-3xl">
                    <AnimatedNumber
                      value={Math.round(calculations.annualNoShowLoss)}
                      prefix={`${currencySymbol} `}
                    />
                    <span className="text-base font-normal"> {t.perYear}</span>
                  </p>
                </div>

                {/* Receptionist cost */}
                <div className="rounded-xl border border-red-200 bg-red-50 p-4 dark:border-red-900/50 dark:bg-red-950/30">
                  <p className="text-sm font-medium text-red-800 dark:text-red-300">
                    {t.receptionistCostLabel}
                  </p>
                  <p className="text-2xl font-bold text-red-600 dark:text-red-400 sm:text-3xl">
                    <AnimatedNumber
                      value={calculations.receptionistCost}
                      prefix={`${currencySymbol} `}
                    />
                    <span className="text-base font-normal"> {t.perYear}</span>
                  </p>
                </div>

                {/* Net savings */}
                <div className="rounded-xl border border-green-200 bg-green-50 p-4 dark:border-green-900/50 dark:bg-green-950/30">
                  <p className="text-sm font-medium text-green-800 dark:text-green-300">
                    {t.savingsLabel}
                  </p>
                  <p className="text-2xl font-bold text-brand-green sm:text-3xl">
                    <AnimatedNumber
                      value={calculations.netSavings}
                      prefix={`${currencySymbol} `}
                    />
                    <span className="mx-2 text-base font-normal text-slate-500">
                      ({calculations.roi}% {t.roiLabel})
                    </span>
                  </p>
                </div>

                {/* Payback days */}
                <div className="rounded-xl border border-green-200 bg-green-50 p-4 dark:border-green-900/50 dark:bg-green-950/30">
                  <p className="text-sm font-medium text-green-800 dark:text-green-300">
                    {t.paybackLabel}
                  </p>
                  <p className="text-2xl font-bold text-brand-green sm:text-3xl">
                    <AnimatedNumber value={calculations.paybackDays} />
                    <span className="text-base font-normal"> {t.days}</span>
                  </p>
                </div>
              </div>

              {/* Bar chart comparison */}
              <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900 sm:p-8">
                <h3 className="mb-4 text-lg font-bold text-slate-900 dark:text-white">
                  {t.currentCosts} vs. {t.withMawidi}
                </h3>
                <div className="space-y-4">
                  <CostComparisonBar
                    label={t.noShowLosses}
                    value={Math.round(calculations.annualNoShowLoss)}
                    maxValue={barMax}
                    color="red"
                    currencySymbol={currencySymbol}
                  />
                  <CostComparisonBar
                    label={t.staffCosts}
                    value={calculations.receptionistCost}
                    maxValue={barMax}
                    color="red"
                    currencySymbol={currencySymbol}
                  />
                  <CostComparisonBar
                    label={t.mawidiCost}
                    value={calculations.mawidiAnnualCost}
                    maxValue={barMax}
                    color="green"
                    currencySymbol={currencySymbol}
                  />
                  <CostComparisonBar
                    label={t.recovered}
                    value={Math.round(calculations.recoveredRevenue)}
                    maxValue={barMax}
                    color="green"
                    currencySymbol={currencySymbol}
                  />
                </div>
              </div>

              {/* Share */}
              <div className="flex items-center justify-center gap-4">
                <button
                  type="button"
                  onClick={handleShare}
                  className="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700"
                >
                  <Share2 className="h-4 w-4" />
                  {copied ? t.copied : t.shareButton}
                </button>
              </div>
            </>
          )}
        </div>
      </div>

      {/* ------------------------------------------------------------------ */}
      {/* LEAD GATE SECTION                                                  */}
      {/* ------------------------------------------------------------------ */}
      <div className="mt-12 rounded-2xl border border-brand-green/20 bg-gradient-to-br from-brand-green/5 to-emerald-500/5 p-6 shadow-lg sm:p-8">
        {submitSuccess ? (
          <div className="flex flex-col items-center gap-3 py-8 text-center">
            <CheckCircle className="h-12 w-12 text-brand-green" />
            <p className="text-lg font-semibold text-brand-green">
              {t.successMessage}
            </p>
          </div>
        ) : (
          <>
            <div className="mb-6 text-center">
              <div className="mb-3 inline-flex items-center gap-2 rounded-full bg-brand-green/10 px-4 py-1.5 text-sm font-medium text-brand-green">
                <Download className="h-4 w-4" />
                <span>PDF</span>
              </div>
              <h2 className="text-2xl font-bold text-slate-900 dark:text-white">
                {t.leadTitle}
              </h2>
              <p className="mt-2 text-slate-600 dark:text-slate-400">
                {t.leadSubtitle}
              </p>
            </div>

            {!showLeadForm ? (
              <div className="text-center">
                <button
                  type="button"
                  onClick={() => setShowLeadForm(true)}
                  className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-500 px-8 py-3 text-lg font-semibold text-white transition-all hover:from-green-600 hover:to-emerald-600 hover:shadow-lg"
                >
                  <Download className="h-5 w-5" />
                  {isAr ? "أريد التقرير المجاني" : "Get My Free Report"}
                </button>
              </div>
            ) : (
              <form
                onSubmit={handleLeadSubmit}
                className="mx-auto max-w-lg space-y-4"
              >
                {/* Honeypot - hidden from users */}
                <input
                  type="text"
                  name="website"
                  value={honeypot}
                  onChange={(e) => setHoneypot(e.target.value)}
                  className="absolute -left-[9999px] opacity-0"
                  tabIndex={-1}
                  autoComplete="off"
                  aria-hidden="true"
                />

                <div className="grid gap-4 sm:grid-cols-2">
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">
                      {t.nameLabel} *
                    </label>
                    <input
                      type="text"
                      required
                      value={leadForm.name}
                      onChange={(e) =>
                        setLeadForm((p) => ({ ...p, name: e.target.value }))
                      }
                      className="w-full rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                    />
                  </div>
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">
                      {t.emailLabel} *
                    </label>
                    <input
                      type="email"
                      required
                      value={leadForm.email}
                      onChange={(e) =>
                        setLeadForm((p) => ({ ...p, email: e.target.value }))
                      }
                      className="w-full rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                    />
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">
                      {t.phoneLabel} *
                    </label>
                    <input
                      type="tel"
                      required
                      value={leadForm.phone}
                      onChange={(e) =>
                        setLeadForm((p) => ({ ...p, phone: e.target.value }))
                      }
                      className="w-full rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                    />
                  </div>
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">
                      {t.companyLabel}
                    </label>
                    <input
                      type="text"
                      value={leadForm.company}
                      onChange={(e) =>
                        setLeadForm((p) => ({
                          ...p,
                          company: e.target.value,
                        }))
                      }
                      className="w-full rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-slate-900 placeholder-slate-400 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                    />
                  </div>
                </div>

                {submitError && (
                  <div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-600 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">
                    <AlertCircle className="h-4 w-4 flex-shrink-0" />
                    <span>{submitError}</span>
                  </div>
                )}

                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full rounded-xl bg-gradient-to-r from-brand-green to-emerald-500 px-6 py-3 text-lg font-semibold text-white transition-all hover:from-green-600 hover:to-emerald-600 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {isSubmitting ? (
                    <span className="inline-flex items-center gap-2">
                      <Loader2 className="h-5 w-5 animate-spin" />
                      {t.submitting}
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-2">
                      <Download className="h-5 w-5" />
                      {t.submitButton}
                    </span>
                  )}
                </button>

                <p className="text-center text-xs text-slate-500 dark:text-slate-400">
                  {t.privacyNote}
                </p>
              </form>
            )}
          </>
        )}
      </div>

      {/* ------------------------------------------------------------------ */}
      {/* CTA SECTION                                                        */}
      {/* ------------------------------------------------------------------ */}
      <div className="mt-12 rounded-2xl bg-gradient-to-br from-slate-900 to-slate-800 p-8 text-center shadow-xl dark:from-slate-800 dark:to-slate-700 sm:p-12">
        <h2 className="text-2xl font-bold text-white sm:text-3xl">
          {isAr
            ? "جاهز لاسترداد إيراداتك المفقودة؟"
            : "Ready to Recover Your Lost Revenue?"}
        </h2>
        <p className="mx-auto mt-3 max-w-2xl text-slate-300">{t.ctaTagline}</p>

        <div className="mt-8 flex flex-col items-center gap-4 sm:flex-row sm:justify-center">
          <Link
            href={`/${lang}/signup?plan=tier2`}
            className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-500 px-8 py-3.5 text-lg font-semibold text-white transition-all hover:from-green-600 hover:to-emerald-600 hover:shadow-lg"
          >
            {t.ctaPrimary}
            <ArrowRight className={`h-5 w-5 ${isAr ? "rotate-180" : ""}`} />
          </Link>
          <Link
            href={`/${lang}/demo/instant`}
            className="inline-flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 px-8 py-3.5 text-lg font-semibold text-white backdrop-blur transition-all hover:bg-white/20"
          >
            {t.ctaSecondary}
          </Link>
        </div>
        <div className="mt-4">
          <Link
            href={`/${lang}/demo`}
            className="text-sm text-slate-400 underline transition-colors hover:text-white"
          >
            {t.ctaTertiary}
          </Link>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Reusable Slider + Number Input
// ---------------------------------------------------------------------------
function SliderInput({
  label,
  value,
  onChange,
  min,
  max,
  step,
  suffix,
  icon,
  isAr,
  sliderColor = "green",
}: {
  label: string;
  value: number;
  onChange: (v: number) => void;
  min: number;
  max: number;
  step: number;
  suffix?: string;
  icon?: React.ReactNode;
  isAr: boolean;
  sliderColor?: "green" | "red";
}) {
  return (
    <div>
      <div className="mb-2 flex items-center justify-between">
        <label className="flex items-center gap-1.5 text-sm font-medium text-slate-700 dark:text-slate-300">
          {icon && <span className="text-brand-green">{icon}</span>}
          {label}
        </label>
        <div className="flex items-center gap-1">
          <input
            type="number"
            value={value}
            onChange={(e) => {
              const v = Number(e.target.value);
              if (!isNaN(v)) onChange(Math.max(min, Math.min(max, v)));
            }}
            className={`w-24 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-900 focus:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white ${isAr ? "text-left" : "text-right"}`}
            min={min}
            max={max}
            step={step}
          />
          {suffix && (
            <span className="text-sm font-medium text-slate-500 dark:text-slate-400">
              {suffix}
            </span>
          )}
        </div>
      </div>
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className={`h-2 w-full cursor-pointer appearance-none rounded-full ${
          sliderColor === "red"
            ? "bg-red-100 accent-red-500 dark:bg-red-900/30"
            : "bg-brand-green/20 accent-brand-green"
        }`}
      />
      <div className="mt-1 flex justify-between text-xs text-slate-400">
        <span>
          {min.toLocaleString()}
          {suffix ? ` ${suffix}` : ""}
        </span>
        <span>
          {max.toLocaleString()}
          {suffix ? ` ${suffix}` : ""}
        </span>
      </div>
    </div>
  );
}
