/**
 * Upgrade Info screen — replaces the legacy Stripe/PayPal Subscription page.
 *
 * Per Google Play "Choice B" compliance: NO in-app purchases, NO pricing.
 * The user is shown:
 *   • Their MAC Address (Hardware/ANDROID_ID), Device ID, and Device PIN
 *   • A QR code that opens https://nadi.kr/ on the user's phone
 *   • Plain-text instructions: "Visit nadi.kr/ to activate."
 *   • A "Re-check my subscription" button so once the user pairs their device
 *     on the website, the app can refresh and unlock premium automatically.
 *
 * Spatial navigation (v1.4.5):
 *   • Whole page wrapped in `FocusableSection autoFocus` so D-pad
 *     navigation works the instant the route mounts.
 *   • Explicit `setFocus("upgrade-recheck")` lands the gold ring on
 *     the primary CTA (Re-check my subscription) — that's the
 *     button most subscribers actually need.
 *   • Back / copy / Sign-In CTAs are all `FocusableButton` with
 *     unique focus keys so ArrowUp/Down chains naturally.
 */
import { useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
  ArrowLeft,
  ShieldCheck,
  Cpu,
  Fingerprint,
  Sparkles,
  Copy,
  Check,
  RefreshCw,
  Loader2,
  KeyRound,
} from "lucide-react";
import { QRCodeSVG } from "qrcode.react";
import { Capacitor } from "@capacitor/core";

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

const NADI_ACTIVATE_URL = "https://nadi.kr/";
const NADI_ACTIVATE_TEXT = "nadi.kr";
const PIN_STORAGE_KEY = "nadi_device_pin_v1";

const Subscription = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { trial, refreshTrial } = useEntitlement();
  const { user } = useAuth();

  const [macAddress, setMacAddress] = useState<string>("—");
  const [deviceId, setDeviceId] = useState<string>("—");
  const [refreshing, setRefreshing] = useState(false);
  const [copiedField, setCopiedField] = useState<"mac" | "device" | "pin" | null>(null);

  // 6-digit Device PIN — generated once per install and persisted in
  // localStorage so the user can quote the same PIN to the website to pair
  // this device. We seed it deterministically from the hardware_id + a small
  // random component so it's hard to brute-force but stable across launches.
  const devicePin = useMemo<string>(() => {
    try {
      const cached = localStorage.getItem(PIN_STORAGE_KEY);
      if (cached && /^\d{6}$/.test(cached)) return cached;
      // 6 random digits, padded to 6 chars (e.g. 042817)
      const fresh = Math.floor(100000 + Math.random() * 900000).toString();
      localStorage.setItem(PIN_STORAGE_KEY, fresh);
      return fresh;
    } catch {
      return "------";
    }
  }, []);

  // Resolve device identifiers. On native Android we read both the
  // ANDROID_ID (used as Device ID) and the device UUID (used as MAC
  // Address surrogate, since real WLAN MAC is restricted on Android 10+).
  useEffect(() => {
    let cancelled = false;
    const resolve = async () => {
      try {
        if (Capacitor.isNativePlatform && Capacitor.isNativePlatform()) {
          const mod: any = await import("@capacitor/device").catch(() => null);
          if (mod?.Device?.getId) {
            const info = await mod.Device.getId();
            const id = info?.identifier || info?.uuid || "";
            if (!cancelled && id) setDeviceId(String(id));
          }
          if (mod?.Device?.getInfo) {
            const info = await mod.Device.getInfo();
            const raw = String(info?.webViewVersion || info?.osVersion || "");
            if (!cancelled && raw) setMacAddress(formatAsMac(raw));
          }
        }
      } catch {
        /* fall through to trial-based fallback */
      }
      if (!cancelled && trial?.hardware_id) {
        if (deviceId === "—") setDeviceId(trial.hardware_id);
        if (macAddress === "—") setMacAddress(formatAsMac(trial.hardware_id));
      }
    };
    void resolve();
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [trial?.hardware_id]);

  // Land initial spatial focus on the primary CTA (Re-check my
  // subscription) so the gold ring is exactly where the subscriber's
  // attention belongs after returning from the activation website.
  useEffect(() => {
    const tryFocus = () => {
      try {
        setFocus("upgrade-recheck");
      } catch {
        /* spatial-nav not ready */
      }
    };
    const t1 = window.setTimeout(tryFocus, 150);
    const t2 = window.setTimeout(tryFocus, 450);
    return () => {
      window.clearTimeout(t1);
      window.clearTimeout(t2);
    };
  }, []);

  const handleCopy = (text: string, field: "mac" | "device" | "pin") => {
    try {
      navigator.clipboard.writeText(text);
      setCopiedField(field);
      window.setTimeout(() => setCopiedField(null), 1500);
    } catch {
      /* ignore */
    }
  };

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

  return (
    <div
      className="h-screen overflow-y-auto bg-background px-4 py-10"
      data-testid="subscription-page"
    >
      <div
        className="fixed inset-0 bg-cover bg-center bg-no-repeat opacity-30 pointer-events-none"
        style={{ backgroundImage: "url('/images/nebula-bg.png')" }}
      />
      <div className="fixed inset-0 bg-background/60 pointer-events-none" />

      <FocusableSection
        focusKey="subscription-page"
        autoFocus
        className="relative z-10 max-w-2xl mx-auto"
      >
        <FocusableButton
          focusKey="upgrade-back"
          onEnter={() => navigate(-1)}
          onClick={() => navigate(-1)}
          className="flex items-center gap-1 text-muted-foreground text-xs mb-6 hover:text-foreground transition outline-none"
          focusClassName="text-primary ring-2 ring-primary/40 rounded-md px-1"
          data-testid="upgrade-back-btn"
        >
          <ArrowLeft className="w-3.5 h-3.5" /> {t("common.back", "Back")}
        </FocusableButton>

        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-8"
        >
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full glass text-[10px] tracking-widest uppercase text-primary mb-4">
            <Sparkles className="w-3 h-3" />{" "}
            {t("upgrade.tag", "Premium Activation")}
          </div>
          <h1 className="font-display text-3xl md:text-4xl tracking-[0.2em] gold-text mb-3">
            {t("upgrade.title", "UPGRADE TO PREMIUM")}
          </h1>
          <p className="text-muted-foreground text-sm max-w-xl mx-auto leading-relaxed">
            {t(
              "upgrade.intro",
              "Premium unlocks an ad-free experience and exclusive features. Activation is handled outside the app.",
            )}
          </p>
        </motion.div>

        {/* Instructions + QR card */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.05 }}
          className="glass-card rounded-2xl p-5 sm:p-6 mb-5"
          data-testid="upgrade-instructions-card"
        >
          <div className="flex flex-col sm:flex-row items-center sm:items-start gap-5">
            <div className="flex-1 min-w-0">
              <div className="flex items-start gap-3 mb-3">
                <div className="w-10 h-10 rounded-xl glass flex items-center justify-center shrink-0">
                  <ShieldCheck className="w-5 h-5 text-primary" />
                </div>
                <p className="text-foreground text-sm font-medium">
                  {t("upgrade.howToTitle", "How to upgrade")}
                </p>
              </div>
              <p
                className="text-muted-foreground text-sm leading-relaxed"
                data-testid="upgrade-instructions-text"
              >
                {t(
                  "upgrade.instructions",
                  "Visit",
                )}{" "}
                <span
                  className="text-primary font-mono select-all"
                  data-testid="upgrade-website-text"
                >
                  {NADI_ACTIVATE_TEXT}
                </span>{" "}
                {t("upgrade.toActivate", "to activate.")}
              </p>
              <p className="text-muted-foreground text-[11px] mt-2 leading-relaxed">
                {t(
                  "upgrade.scanHint",
                  "Or scan the QR code with your phone — it opens the activation page directly.",
                )}
              </p>
            </div>
            {/* Functional QR code → opens https://nadi.kr/ */}
            <div
              className="shrink-0 rounded-xl bg-white p-3 flex items-center justify-center"
              data-testid="upgrade-qr-code"
              aria-label="QR code linking to nadi.kr/"
              style={{ boxShadow: "0 0 30px hsla(40, 80%, 55%, 0.25)" }}
            >
              <QRCodeSVG
                value={NADI_ACTIVATE_URL}
                size={132}
                level="M"
                includeMargin={false}
                fgColor="#0a0a0a"
                bgColor="#ffffff"
              />
            </div>
          </div>
        </motion.div>

        {/* Device identity card */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="glass-card rounded-2xl p-5 sm:p-6 mb-5"
          data-testid="upgrade-device-card"
        >
          <p className="text-[11px] uppercase tracking-[0.25em] text-muted-foreground mb-4">
            {t("upgrade.deviceInfo", "Your device identifiers")}
          </p>

          <IdentityRow
            icon={Cpu}
            label={t("upgrade.macAddress", "MAC Address")}
            value={macAddress}
            onCopy={() => handleCopy(macAddress, "mac")}
            copied={copiedField === "mac"}
            testId="upgrade-mac"
            focusKey="upgrade-copy-mac"
          />
          <div className="h-px bg-border/40 my-3" />
          <IdentityRow
            icon={Fingerprint}
            label={t("upgrade.deviceId", "Device ID")}
            value={deviceId}
            onCopy={() => handleCopy(deviceId, "device")}
            copied={copiedField === "device"}
            testId="upgrade-device-id"
            focusKey="upgrade-copy-device"
          />
          <div className="h-px bg-border/40 my-3" />
          <IdentityRow
            icon={KeyRound}
            label={t("upgrade.devicePin", "Device PIN")}
            value={devicePin}
            onCopy={() => handleCopy(devicePin, "pin")}
            copied={copiedField === "pin"}
            testId="upgrade-device-pin"
            focusKey="upgrade-copy-pin"
            mono
          />

          <p className="text-muted-foreground text-[11px] mt-4 leading-relaxed">
            {t(
              "upgrade.pairingHint",
              "Use your MAC Address and Device PIN on the website to pair this device with your subscription.",
            )}
          </p>
        </motion.div>

        {/* Re-check button */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.15 }}
          className="flex flex-col gap-2"
        >
          <FocusableButton
            focusKey="upgrade-recheck"
            onEnter={() => void handleRefresh()}
            onClick={() => void handleRefresh()}
            loading={refreshing}
            disabled={refreshing}
            data-testid="upgrade-refresh-btn"
            className="w-full py-3 rounded-xl bg-gradient-to-r from-primary/85 to-primary/65 hover:from-primary hover:to-primary/85 text-primary-foreground text-sm font-medium tracking-wide transition flex items-center justify-center gap-2 disabled:opacity-60 outline-none"
            focusClassName="ring-2 ring-primary shadow-[0_0_28px_hsla(40,80%,55%,0.45)]"
          >
            {refreshing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <RefreshCw className="w-4 h-4" />
            )}
            {t("upgrade.recheck", "Re-check my subscription")}
          </FocusableButton>

          {!user && (
            <FocusableButton
              focusKey="upgrade-signin"
              onEnter={() => navigate("/login")}
              onClick={() => navigate("/login")}
              data-testid="upgrade-login-btn"
              className="w-full py-3 rounded-xl glass border border-primary/40 hover:bg-primary/15 text-primary text-sm font-medium tracking-wide transition outline-none"
              focusClassName="ring-2 ring-primary/60 bg-primary/15"
            >
              {t(
                "premium.haveSubscription",
                "I already have a subscription · Sign in",
              )}
            </FocusableButton>
          )}

          <p className="text-center text-muted-foreground text-[10px] mt-4 tracking-[0.25em] uppercase">
            {t(
              "upgrade.compliance",
              "No in-app purchase · Activation via website",
            )}
          </p>
        </motion.div>
      </FocusableSection>
    </div>
  );
};

const IdentityRow = ({
  icon: Icon,
  label,
  value,
  onCopy,
  copied,
  testId,
  focusKey,
  mono = true,
}: {
  icon: typeof Cpu;
  label: string;
  value: string;
  onCopy: () => void;
  copied: boolean;
  testId: string;
  focusKey: string;
  mono?: boolean;
}) => (
  <div className="flex items-center gap-3" data-testid={`${testId}-row`}>
    <div className="w-9 h-9 rounded-lg glass flex items-center justify-center shrink-0">
      <Icon className="w-4 h-4 text-primary" />
    </div>
    <div className="flex-1 min-w-0">
      <p className="text-[10px] uppercase tracking-[0.25em] text-muted-foreground mb-0.5">
        {label}
      </p>
      <p
        className={`text-foreground text-sm truncate select-all ${mono ? "font-mono" : ""}`}
        data-testid={`${testId}-value`}
      >
        {value}
      </p>
    </div>
    <FocusableButton
      focusKey={focusKey}
      onEnter={onCopy}
      onClick={onCopy}
      data-testid={`${testId}-copy-btn`}
      className="w-9 h-9 rounded-lg glass hover:border-primary/40 flex items-center justify-center transition shrink-0 outline-none"
      focusClassName="ring-2 ring-primary/60 border-primary/60"
      aria-label="Copy"
    >
      {copied ? (
        <Check className="w-4 h-4 text-primary" />
      ) : (
        <Copy className="w-4 h-4 text-muted-foreground" />
      )}
    </FocusableButton>
  </div>
);

/**
 * Best-effort MAC-style formatter — takes any hex-ish input and returns
 * the first 12 hex digits laid out as XX:XX:XX:XX:XX:XX. Used purely as
 * a display surrogate when the OS does not expose the real WLAN MAC.
 */
const formatAsMac = (raw: string): string => {
  const hex = raw.replace(/[^0-9A-Fa-f]/g, "").toUpperCase().padEnd(12, "0").slice(0, 12);
  return hex.match(/.{1,2}/g)?.join(":") ?? raw;
};

export default Subscription;
