/**
 * TrialExpired — dedicated lock screen shown when the device-level
 * 30-day trial has elapsed AND there is no premium entitlement on
 * this device or user.
 *
 * Per the product brief:
 *   - Clear expiry message
 *   - "Login" button for users who already bought a key on nadi.kr
 *   - NO "Buy Now" button inside the app (Google Play policy choice B:
 *     users buy the 1-year key externally on nadi.kr).
 */

import { motion } from "framer-motion";
import { LockKeyhole, LogIn, Sparkles, RefreshCw, Loader2 } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useEffect, useState } from "react";

import { useEntitlement } from "@/hooks/useEntitlement";
import {
  FocusableButton,
  FocusableSection,
  setFocus,
} from "@/components/focusable";

const NADI_WEBSITE_TEXT = "nadi.kr";

const TrialExpired = () => {
  const nav = useNavigate();
  const { t } = useTranslation();
  const { trial, refreshTrial } = useEntitlement();
  const [refreshing, setRefreshing] = useState(false);

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

  // Land initial spatial focus on the primary CTA so the gold ring is
  // exactly where most subscribers need it after the lock screen.
  useEffect(() => {
    const tryFocus = () => {
      try {
        setFocus("trial-expired-login");
      } catch {
        /* spatial-nav not ready */
      }
    };
    const t1 = window.setTimeout(tryFocus, 150);
    const t2 = window.setTimeout(tryFocus, 450);
    return () => {
      window.clearTimeout(t1);
      window.clearTimeout(t2);
    };
  }, []);

  return (
    <div
      data-testid="trial-expired-page"
      className="relative h-screen w-full overflow-hidden flex items-center justify-center px-4 py-10"
    >
      <div
        className="absolute inset-0 bg-cover bg-center bg-no-repeat"
        style={{ backgroundImage: "url('/images/nebula-bg.png')" }}
      />
      <div className="absolute inset-0 bg-background/70" />

      <motion.div
        initial={{ opacity: 0, y: 20, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.7, ease: "easeOut" }}
        className="relative z-10 w-full max-w-lg"
      >
        <FocusableSection
          focusKey="trial-expired-page"
          autoFocus
          className="glass-card rounded-3xl p-7 sm:p-10 text-center"
        >
        <div
          className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl glass mx-auto mb-5 flex items-center justify-center"
          style={{
            border: "1px solid hsla(40, 80%, 55%, 0.4)",
            boxShadow: "0 0 40px hsla(40, 80%, 55%, 0.28)",
          }}
        >
          <LockKeyhole
            className="w-8 h-8 sm:w-10 sm:h-10 text-primary gold-glow"
            strokeWidth={1.4}
          />
        </div>

        <h1
          data-testid="trial-expired-title"
          className="font-display text-2xl sm:text-3xl tracking-[0.25em] gold-text"
          style={{ textShadow: "0 0 30px hsla(40, 80%, 55%, 0.35)" }}
        >
          {t("trial.expiredTitle", "TRIAL EXPIRED")}
        </h1>

        <p
          data-testid="trial-expired-description"
          className="text-muted-foreground text-sm sm:text-base mt-4 leading-relaxed max-w-md mx-auto"
        >
          {t(
            "trial.expiredDescription",
            "Your 30-day free trial has expired. Upgrade to a 1-year premium account to continue using NadiPlayer without ads.",
          )}
        </p>

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

        <div className="flex flex-col gap-3 mt-7">
          <FocusableButton
            focusKey="trial-expired-login"
            data-testid="trial-expired-login-btn"
            onEnter={() => nav("/login")}
            onClick={() => nav("/login")}
            className="w-full py-3 rounded-xl bg-gradient-to-r from-primary/85 to-primary/60 text-primary-foreground font-medium text-sm hover:from-primary hover:to-primary/80 transition-all flex items-center justify-center gap-2 outline-none"
            focusClassName="ring-2 ring-primary shadow-[0_0_28px_hsla(40,80%,55%,0.45)]"
          >
            <LogIn className="w-4 h-4" />
            {t("trial.loginAlready", "I already have a subscription · Log in")}
          </FocusableButton>

          <FocusableButton
            focusKey="trial-expired-upgrade-info"
            data-testid="trial-expired-upgrade-info-btn"
            onEnter={() => nav("/subscription")}
            onClick={() => nav("/subscription")}
            className="w-full py-3 rounded-xl glass hover:border-primary/40 text-foreground font-medium text-sm transition-all flex items-center justify-center gap-2 outline-none"
            focusClassName="ring-2 ring-primary/60 border-primary/60"
          >
            <Sparkles className="w-4 h-4 text-primary" />
            {t("trial.upgradeInfo", "Upgrade info & device ID")}
          </FocusableButton>

          <p
            className="mt-2 text-[11px] tracking-wide text-muted-foreground/80 leading-relaxed text-center"
            data-testid="trial-expired-website-hint"
          >
            {t(
              "trial.visitWebsiteHint",
              "To upgrade to Premium and remove ads, please visit our website",
            )}{" "}
            <span className="text-primary font-mono select-all">
              {NADI_WEBSITE_TEXT}
            </span>{" "}
            {t("trial.fromBrowser", "from your browser.")}
          </p>

          <FocusableButton
            focusKey="trial-expired-refresh"
            data-testid="trial-expired-refresh-btn"
            onEnter={() => void handleRefresh()}
            onClick={() => void handleRefresh()}
            disabled={refreshing}
            loading={refreshing}
            className="mt-1 text-[11px] tracking-wide text-muted-foreground hover:text-foreground transition-colors flex items-center justify-center gap-1.5 disabled:opacity-60 outline-none"
            focusClassName="text-primary ring-2 ring-primary/40 rounded-md"
          >
            {refreshing ? (
              <Loader2 className="w-3 h-3 animate-spin" />
            ) : (
              <RefreshCw className="w-3 h-3" />
            )}
            {t("trial.recheck", "Re-check my subscription")}
          </FocusableButton>
        </div>

        <p className="mt-8 text-[10px] tracking-[0.25em] uppercase text-muted-foreground/60">
          {t("trial.footnote", "No in-app purchase · Key activation only")}
        </p>
        </FocusableSection>
      </motion.div>
    </div>
  );
};

export default TrialExpired;
