/**
 * TVGuestLockOverlay — full-screen lock shown ONLY when:
 *   - Platform is Samsung Tizen or LG webOS
 *   - Visitor is NOT logged in (guest mode)
 *   - Device-level 15-day trial has expired
 *   - Device is not flagged premium by the admin
 *
 * Reuses the same visual language as ExpiredOverlay (the lock screen for
 * expired paid subscribers) and the WhatsApp number / pre-filled message
 * configured by the admin in /admin → Support card.
 *
 * The trial clock is enforced SERVER-SIDE on hardware_id, so reinstalling
 * the .wgt / .ipk does NOT restart the 15 days — the user lands here
 * again immediately.
 */
import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import { MessageCircle, Lock, RefreshCw, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";

import { useEntitlement } from "@/hooks/useEntitlement";
import { fetchAppInfo, type AppInfo, buildWhatsAppUrl } from "@/lib/appInfo";
import { getPlatform } from "@/lib/platform";

const platformLabel = (p: string): string => {
  if (p === "tizen") return "Samsung Tizen TV";
  if (p === "webos") return "LG webOS TV";
  return p;
};

const TVGuestLockOverlay = () => {
  const { t } = useTranslation();
  const { trial, tvGuestLocked, refreshTrial } = useEntitlement();
  const [info, setInfo] = useState<AppInfo | null>(null);
  const [refreshing, setRefreshing] = useState(false);

  // Fetch admin-configured support contact (whatsapp + message) once
  // when the overlay first mounts. Cheap (cached at the CDN edge).
  useEffect(() => {
    if (!tvGuestLocked) return;
    let cancelled = false;
    void fetchAppInfo()
      .then((d) => {
        if (!cancelled) setInfo(d);
      })
      .catch(() => {
        /* network errors are non-fatal — button just won't have a number */
      });
    return () => {
      cancelled = true;
    };
  }, [tvGuestLocked]);

  if (!tvGuestLocked) return null;

  const hwid = trial?.hardware_id || "unknown";
  const platform = getPlatform();
  const number = info?.support?.whatsapp_number || "";
  const baseMessage =
    info?.support?.whatsapp_message ||
    t("tvLock.whatsappPrefillBase", {
      defaultValue:
        "Hello! I would like to activate a Premium account for Nadiplayer.",
    });
  const fullMessage = `${baseMessage}\n\n` +
    `${t("tvLock.deviceLabel", { defaultValue: "Device" })}: ${platformLabel(platform)}\n` +
    `${t("tvLock.deviceIdLabel", { defaultValue: "Device ID" })}: ${hwid}`;
  const waHref = buildWhatsAppUrl(number, fullMessage);

  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await refreshTrial();
    } finally {
      setRefreshing(false);
    }
  };

  return (
    <motion.div
      data-testid="tv-guest-lock-overlay"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      className="fixed inset-0 z-[10000] flex items-center justify-center px-6"
      style={{
        background:
          "radial-gradient(ellipse at center, hsl(200, 40%, 10%) 0%, #000 80%)",
      }}
    >
      <motion.div
        initial={{ y: 20, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.6, ease: "easeOut" }}
        className="glass-card rounded-3xl p-8 sm:p-12 w-full max-w-xl text-center"
      >
        {/* Icon */}
        <div
          className="w-20 h-20 mx-auto rounded-2xl glass flex items-center justify-center mb-6"
          style={{
            border: "1px solid hsla(40, 80%, 55%, 0.45)",
            boxShadow: "0 0 50px hsla(40, 80%, 55%, 0.30)",
          }}
        >
          <Lock
            className="w-10 h-10 text-primary gold-glow"
            strokeWidth={1.4}
          />
        </div>

        {/* Title */}
        <h1
          data-testid="tv-guest-lock-title"
          className="font-display text-2xl sm:text-3xl md:text-4xl tracking-[0.22em] gold-text mb-4"
          style={{ textShadow: "0 0 30px hsla(40, 80%, 55%, 0.35)" }}
        >
          {t("tvLock.title", { defaultValue: "FREE TRIAL ENDED" })}
        </h1>

        {/* Message */}
        <p
          data-testid="tv-guest-lock-description"
          className="text-foreground/85 text-sm sm:text-base mb-2 leading-relaxed max-w-md mx-auto"
        >
          {t("tvLock.body", {
            defaultValue:
              "Your 30-day free trial on this Smart TV has ended. To keep watching, please contact us on WhatsApp to activate a Premium account.",
          })}
        </p>

        {/* Trial breadcrumb */}
        {trial && (
          <p className="mt-2 text-[11px] tracking-wider text-muted-foreground/70">
            {t("tvLock.daysUsed", {
              defaultValue:
                "{{used}} / {{total}} days used · started {{date}}",
              used: trial.days_used,
              total: trial.trial_days,
              date: (trial.first_seen_at || "").slice(0, 10),
            })}
          </p>
        )}

        {/* Primary action — WhatsApp */}
        <div className="flex flex-col gap-3 mt-7">
          {waHref ? (
            <a
              href={waHref}
              target="_blank"
              rel="noopener noreferrer"
              data-testid="tv-guest-lock-whatsapp-btn"
              className="inline-flex items-center justify-center gap-2 px-6 py-3 rounded-xl bg-[#25D366] hover:bg-[#1ebe57] text-white font-semibold text-sm sm:text-base transition-colors outline-none focus:ring-2 focus:ring-[#25D366]/60"
            >
              <MessageCircle className="w-5 h-5" />
              {t("tvLock.contactWhatsapp", {
                defaultValue: "Contact Admin on WhatsApp",
              })}
            </a>
          ) : (
            <div
              data-testid="tv-guest-lock-no-number"
              className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-xs text-destructive"
            >
              {t("tvLock.noNumber", {
                defaultValue:
                  "Support contact is not configured yet. Please reach out via the website.",
              })}
            </div>
          )}

          {number && (
            <p
              className="text-muted-foreground text-xs tracking-wide"
              data-testid="tv-guest-lock-number"
            >
              {number}
            </p>
          )}

          {/* Re-check (after admin grants premium remotely) */}
          <button
            data-testid="tv-guest-lock-recheck-btn"
            onClick={handleRefresh}
            disabled={refreshing}
            className="mt-2 text-[11px] tracking-wide text-muted-foreground hover:text-foreground transition-colors flex items-center justify-center gap-1.5 disabled:opacity-60"
          >
            {refreshing ? (
              <Loader2 className="w-3 h-3 animate-spin" />
            ) : (
              <RefreshCw className="w-3 h-3" />
            )}
            {t("tvLock.recheck", { defaultValue: "I've been activated · Re-check" })}
          </button>
        </div>

        {/* Device ID footnote (so user can read it out on the call) */}
        <p
          className="mt-8 text-[10px] tracking-[0.25em] uppercase text-muted-foreground/60 break-all"
          data-testid="tv-guest-lock-hwid"
        >
          {t("tvLock.deviceIdLabel", { defaultValue: "Device ID" })}: {hwid}
        </p>
      </motion.div>
    </motion.div>
  );
};

export default TVGuestLockOverlay;
