/**
 * Unified "no active server" empty-state card.
 *
 * Shown on Live TV, Movies, Series tabs when there is no active profile.
 * Replaces the legacy "No Xtream server is configured yet" / "Please contact
 * your admin" copy (Google Play compliance: choice B — no in-app purchase
 * mention but a clean UPGRADE NOW button that opens the renewal page).
 *
 *  • UPGRADE NOW  → /subscription (logged-in users) or /trial-expired (guests)
 *  • SIGN IN      → /login (only rendered for guests)
 *  • Add a profile → opens the same manual input form (URL / Username / Password)
 *                    that guest users get. Available for EVERY user — guests AND
 *                    logged-in subscribers — so nobody is ever stuck on this
 *                    screen.
 *
 * Spatial navigation (v1.4.5):
 *   The whole prompt card is wrapped in a `FocusableSection trap autoFocus`
 *   so D-pad navigation is locked inside the overlay until the user picks
 *   an action. On mount we explicitly call `setFocus` to the first CTA
 *   ("Upgrade Now" for guests, "Add a profile" for subscribers) so the
 *   gold ring lands where the user expects.
 */

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

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

interface NoServerPromptProps {
  /**
   * Optional test-id prefix so each tab (livetv / movies / series) can be
   * targeted independently in e2e tests without changing internal IDs.
   */
  testIdPrefix?: string;
}

const NoServerPrompt = ({ testIdPrefix = "no-server" }: NoServerPromptProps) => {
  const { t } = useTranslation();
  const nav = useNavigate();
  const { user, isGuest } = useAuth();
  const connect = useConnectProfile();
  const { userIsPremium } = useEntitlement();

  const [addOpen, setAddOpen] = useState(false);

  const isLoggedIn = !!user && !isGuest;
  // Active subscriber (logged-in with days_remaining > 0) OR admin → don't
  // pitch them anything; they're already paying. Just offer "Add a profile"
  // so they can layer their personal Xtream/M3U/Stalker on top.
  const hideUpgradePitch = userIsPremium || user?.role === "admin";

  // UPGRADE NOW destination — ALWAYS the internal Upgrade Info screen
  // (no in-app purchase). The screen displays the user's MAC + Device ID
  // and instructs them to activate Premium on nadi.kr from a browser.
  const upgradeHref = "/subscription";

  // On mount, lock D-pad focus inside the overlay and land on the first
  // CTA so the user immediately sees the gold ring on the action they
  // most likely want.
  const firstFocusKey = hideUpgradePitch
    ? `${testIdPrefix}-add-profile`
    : `${testIdPrefix}-upgrade`;
  useEffect(() => {
    const tryFocus = () => {
      try {
        setFocus(firstFocusKey);
      } catch {
        /* spatial nav not ready */
      }
    };
    const t1 = window.setTimeout(tryFocus, 120);
    const t2 = window.setTimeout(tryFocus, 350);
    return () => {
      window.clearTimeout(t1);
      window.clearTimeout(t2);
    };
  }, [firstFocusKey]);

  return (
    <>
      <FocusableSection
        focusKey={`${testIdPrefix}-overlay`}
        autoFocus
        trap
        className="h-full flex items-center justify-center px-4"
        data-testid={`${testIdPrefix}-empty-wrapper`}
      >
        <motion.div
          initial={{ opacity: 0, y: 14, scale: 0.98 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          transition={{ duration: 0.45, ease: "easeOut" }}
          className="relative glass-card rounded-3xl p-6 sm:p-8 max-w-md w-full overflow-hidden"
          style={{
            border: "1px solid hsla(40, 80%, 55%, 0.4)",
            boxShadow: "0 0 60px hsla(40, 80%, 55%, 0.18)",
          }}
          data-testid={`${testIdPrefix}-prompt-card`}
        >
          {/* Soft gold radial glow for depth */}
          <div
            className="absolute inset-0 pointer-events-none opacity-70"
            style={{
              background:
                "radial-gradient(circle at 100% 0%, hsla(40,80%,55%,0.22), transparent 55%)",
            }}
          />

          <div className="relative flex flex-col items-center text-center">
            {/* Crown badge */}
            <div
              className="w-14 h-14 rounded-2xl glass flex items-center justify-center mb-4"
              style={{
                border: "1px solid hsla(40, 80%, 55%, 0.55)",
                boxShadow: "0 0 24px hsla(40, 80%, 55%, 0.35)",
              }}
            >
              <Crown
                className="w-7 h-7 text-primary gold-glow"
                strokeWidth={1.5}
              />
            </div>

            <h2
              className="font-display text-xl sm:text-2xl tracking-[0.2em] gold-text mb-2"
              data-testid={`${testIdPrefix}-prompt-title`}
            >
              {hideUpgradePitch
                ? t("noServer.titleSubscriber", "Add a profile")
                : t("noServer.title", "Upgrade to Premium")}
            </h2>

            {!hideUpgradePitch && (
              <p
                className="text-foreground/90 text-sm leading-relaxed mb-2"
                data-testid={`${testIdPrefix}-prompt-pitch`}
              >
                {t(
                  "premium.upgradePitch",
                  "Upgrade to a Premium Account to enjoy an ad-free experience and exclusive features.",
                )}
              </p>
            )}

            {hideUpgradePitch && (
              <p
                className="text-muted-foreground text-sm leading-relaxed mb-2"
                data-testid={`${testIdPrefix}-prompt-subscriber-hint`}
              >
                {t(
                  "noServer.subscriberHint",
                  "Connect your own Xtream Codes, M3U playlist, or Stalker portal to start watching.",
                )}
              </p>
            )}

            {!isLoggedIn && (
              <p className="text-muted-foreground text-[11px] mb-4">
                {t("noServer.alreadySubscribed", "Already have a subscription?")}
              </p>
            )}

            {/* Primary CTA row: UPGRADE NOW + SIGN IN — only for non-subscribers */}
            {!hideUpgradePitch && (
              <div className="flex flex-col sm:flex-row gap-2 w-full mt-2">
                <FocusableButton
                  focusKey={`${testIdPrefix}-upgrade`}
                  onEnter={() => nav(upgradeHref)}
                  onClick={() => nav(upgradeHref)}
                  className="flex-1 inline-flex items-center justify-center gap-2 py-2.5 rounded-xl bg-gradient-to-r from-primary/85 to-primary/65 hover:from-primary hover:to-primary/85 text-primary-foreground text-[12px] font-semibold tracking-[0.2em] uppercase transition-colors outline-none"
                  focusClassName="ring-2 ring-primary shadow-[0_0_24px_hsla(40,80%,55%,0.45)]"
                  data-testid={`${testIdPrefix}-upgrade-btn`}
                >
                  <Sparkles className="w-3.5 h-3.5" />
                  {t("noServer.upgradeNow", "Upgrade Now")}
                </FocusableButton>

                {!isLoggedIn && (
                  <FocusableButton
                    focusKey={`${testIdPrefix}-signin`}
                    onEnter={() => nav("/login")}
                    onClick={() => nav("/login")}
                    className="flex-1 inline-flex items-center justify-center gap-2 py-2.5 rounded-xl glass border border-primary/40 hover:bg-primary/15 text-primary text-[12px] font-semibold tracking-[0.2em] uppercase transition-colors outline-none"
                    focusClassName="ring-2 ring-primary shadow-[0_0_24px_hsla(40,80%,55%,0.45)]"
                    data-testid={`${testIdPrefix}-signin-btn`}
                  >
                    <LogIn className="w-3.5 h-3.5" />
                    {t("noServer.signIn", "Sign In")}
                  </FocusableButton>
                )}
              </div>
            )}

            {/* Divider + Add own profile.  Skip the divider for subscribers
                because the Add button is the only CTA they see. */}
            {!hideUpgradePitch && (
              <div className="w-full flex items-center gap-3 my-5">
                <div className="flex-1 h-px bg-border/60" />
                <span className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground">
                  {t("noServer.or", "or")}
                </span>
                <div className="flex-1 h-px bg-border/60" />
              </div>
            )}

            <FocusableButton
              focusKey={`${testIdPrefix}-add-profile`}
              onEnter={() => setAddOpen(true)}
              onClick={() => setAddOpen(true)}
              focusClassName="ring-2 ring-primary shadow-[0_0_24px_hsla(40,80%,55%,0.45)]"
              className={`w-full inline-flex items-center justify-center gap-2 py-2.5 rounded-xl outline-none ${
                hideUpgradePitch
                  ? "bg-gradient-to-r from-primary/85 to-primary/65 hover:from-primary hover:to-primary/85 text-primary-foreground text-[12px] font-semibold tracking-[0.2em] uppercase mt-4"
                  : "glass hover:border-primary/40 text-foreground text-[12px] font-medium"
              } transition-colors`}
              data-testid={`${testIdPrefix}-add-profile-btn`}
            >
              <Plus className="w-3.5 h-3.5 text-primary" />
              {t("noServer.addOwnProfile", "Add a profile")}
            </FocusableButton>
            <p className="text-muted-foreground text-[10px] mt-2">
              {t(
                "noServer.addOwnHint",
                "Use your own Xtream / M3U / Stalker credentials.",
              )}
            </p>
          </div>
        </motion.div>
      </FocusableSection>

      {/* Same dialog used by Account → Add Server.  Guests are already
          forced into "Own server" mode automatically; logged-in users
          who hit this empty state get the full "Shared / Own" toggle
          if their admin has provisioned shared profiles. */}
      <AddServerDialog
        open={addOpen}
        onClose={() => setAddOpen(false)}
        onSubmit={async (data) => {
          const created = await connect(data);
          if (created) setAddOpen(false);
        }}
      />
    </>
  );
};

export default NoServerPrompt;
