/**
 * About menu — the LAST card on the Account page (FEATURE 2026-01).
 *
 * UX: five chevron-styled rows in the Nadi Player dark/gold theme.
 *
 *   1. App Version      — read-only, real installed version (resolved via
 *                         @capacitor/app on native, falls back to the
 *                         compile-time __APP_VERSION__ in web preview).
 *   2. Privacy Policy   — opens a styled modal with admin-editable text.
 *   3. Terms & Conditions — opens a styled modal with admin-editable text.
 *   4. Contact Us       — opens a `mailto:` intent to the support address
 *                         (defaults to nadiplayer@nadi.kr when the admin
 *                         hasn't set one).
 *   5. Rate Us          — Google Play Store deep-link via the
 *                         `market://` URI on Android, falls back to the
 *                         https Play URL elsewhere.
 *
 * Premium / ad-free / free — visible for everyone. Play Store compliance
 * (Privacy + Terms surfaced from the app's account screen).
 */
import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import ReactMarkdown from "react-markdown";
import {
  Info,
  ShieldCheck,
  FileText,
  Mail,
  Star,
  ChevronRight,
  X,
} from "lucide-react";
import {
  APP_VERSION,
  fetchAppInfo,
  resolveInstalledVersion,
  type AppInfo,
} from "@/lib/appInfo";
import { isTizen, isWebOS } from "@/lib/platform";
import { FocusableButton } from "@/components/focusable";
import { useFocusRestore } from "@/hooks/useFocusRestore";

/** Android package name used for the Play Store deep-link. Keep in sync
 *  with `applicationId` in `frontend/android/app/build.gradle`. */
const ANDROID_PACKAGE = "com.nadi.player";
/** Hard-coded fallback used when the admin hasn't filled in
 *  `support_email`. The user explicitly asked for this address in the
 *  product brief. */
const FALLBACK_CONTACT_EMAIL = "nadiplayer@nadi.kr";

type ModalKind = "privacy" | "terms" | "rate-tv" | null;

const AboutMenu = () => {
  const [info, setInfo] = useState<AppInfo | null>(null);
  const [installedVersion, setInstalledVersion] =
    useState<string>(APP_VERSION);
  const [modal, setModal] = useState<ModalKind>(null);

  // Restore focus to the triggering row when the modal closes.
  useFocusRestore(!!modal, [
    "about-privacy",
    "about-terms",
    "about-contact",
    "about-rate",
    "tv-back-button",
  ]);

  // Close on Escape / Tizen / WebOS Back at the document level.
  useEffect(() => {
    if (!modal) return;
    const handler = (e: KeyboardEvent) => {
      if (
        e.key === "Escape" ||
        e.keyCode === 10009 /* Tizen Return */ ||
        e.keyCode === 461 /* WebOS Back */
      ) {
        e.preventDefault();
        e.stopPropagation();
        setModal(null);
      }
    };
    document.addEventListener("keydown", handler, true);
    return () => document.removeEventListener("keydown", handler, true);
  }, [modal]);

  // Lock D-pad focus inside the about-modal on open.
  useEffect(() => {
    if (!modal) return;
    let timers: number[] = [];
    const tryFocus = async () => {
      try {
        const { setFocus } = await import(
          "@noriginmedia/norigin-spatial-navigation"
        );
        setFocus("about-modal-ok");
      } catch {
        /* spatial-nav not ready */
      }
    };
    timers.push(window.setTimeout(tryFocus, 120));
    timers.push(window.setTimeout(tryFocus, 360));
    return () => timers.forEach((t) => window.clearTimeout(t));
  }, [modal]);

  // Resolve installed version (Capacitor → APP_VERSION fallback).
  useEffect(() => {
    let cancelled = false;
    void resolveInstalledVersion()
      .then((v) => {
        if (!cancelled) setInstalledVersion(v);
      })
      .catch(() => undefined);
    return () => {
      cancelled = true;
    };
  }, []);

  // Lazy-load app-info so admin-edited Privacy + Terms text is fresh.
  useEffect(() => {
    let cancelled = false;
    void fetchAppInfo()
      .then((d) => {
        if (!cancelled) setInfo(d);
      })
      .catch(() => undefined);
    return () => {
      cancelled = true;
    };
  }, []);

  const supportEmail = info?.support?.email?.trim() || FALLBACK_CONTACT_EMAIL;
  const privacyText =
    info?.privacy_policy_text?.trim() ||
    "Nadiplayer respects your privacy. This app is a media player that plays streams from playlists you provide. We do not collect, store, or share any personal data. Playlists are stored locally on your device only.";
  const termsText =
    info?.terms_policy_text?.trim() ||
    "NadiPlayer is an IPTV media player only — no streams, channels, or playlists are provided with the app. You are responsible for ensuring that any playlist or stream you load complies with the laws of your country and the rights of the content owner.";

  const openContact = () => {
    // mailto: works in both Capacitor (Android intent) and web (default
    // mail client). Encoding the subject keeps the support inbox tidy.
    const subject = encodeURIComponent("Nadiplayer Support");
    window.location.href = `mailto:${supportEmail}?subject=${subject}`;
  };

  const openRateUs = () => {
    // Samsung Tizen / LG webOS QA (v1.4.2):
    //   - Linking to Google Play (market:// or play.google.com) is a
    //     hard reject on Smart TVs — those stores don't exist there,
    //     navigation fails / WebView blanks.
    //   - Samsung explicitly requires that all "rate the app" actions
    //     route users to the SAMSUNG App Store listing.
    // We render an in-app modal explaining where to rate the app
    // instead of attempting any external navigation.
    if (isTizen() || isWebOS()) {
      setModal("rate-tv");
      return;
    }
    // Android / web fallback: Play Store deep-link (unchanged).
    const marketUrl = `market://details?id=${ANDROID_PACKAGE}`;
    const httpsUrl = `https://play.google.com/store/apps/details?id=${ANDROID_PACKAGE}`;
    try {
      window.location.href = marketUrl;
      window.setTimeout(() => {
        try {
          window.open(httpsUrl, "_blank", "noopener,noreferrer");
        } catch { /* popup blocked — already attempted market:// */ }
      }, 700);
    } catch {
      window.location.href = httpsUrl;
    }
  };

  return (
    <>
      <div
        className="glass-card rounded-2xl p-4 space-y-3"
        data-testid="account-about-menu"
      >
        {/* Header */}
        <div className="flex items-center gap-2">
          <Info className="h-4 w-4 text-primary" />
          <p className="text-sm font-medium text-foreground">About</p>
        </div>

        <div className="space-y-2">
          {/* App Version (read-only) */}
          <div
            className="flex items-center gap-3 rounded-xl border border-border/60 bg-background/30 px-3 py-2.5"
            data-testid="about-app-version-row"
          >
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-primary/30 bg-primary/10">
              <Info className="h-4 w-4 text-primary" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="text-xs font-medium text-foreground">App Version</p>
              <p className="text-[11px] text-muted-foreground">
                v{installedVersion}
              </p>
            </div>
          </div>

          {/* Privacy Policy */}
          <AboutRow
            icon={<ShieldCheck className="h-4 w-4 text-primary" />}
            label="Privacy Policy"
            sub="How we handle your data"
            testid="about-privacy-row"
            focusKey="about-privacy"
            onClick={() => setModal("privacy")}
          />

          {/* Terms & Conditions */}
          <AboutRow
            icon={<FileText className="h-4 w-4 text-primary" />}
            label="Terms & Conditions"
            sub="Your agreement with us"
            testid="about-terms-row"
            focusKey="about-terms"
            onClick={() => setModal("terms")}
          />

          {/* Contact Us */}
          <AboutRow
            icon={<Mail className="h-4 w-4 text-primary" />}
            label="Contact Us"
            sub={supportEmail}
            testid="about-contact-row"
            focusKey="about-contact"
            onClick={openContact}
          />

          {/* Rate Us */}
          <AboutRow
            icon={<Star className="h-4 w-4 text-primary" />}
            label="Rate Us"
            sub={
              isTizen()
                ? "Rate on Samsung App Store"
                : isWebOS()
                  ? "Rate on LG Content Store"
                  : "Open on Google Play"
            }
            testid="about-rate-row"
            focusKey="about-rate"
            onClick={openRateUs}
          />
        </div>
      </div>

      {/* Privacy / Terms modal — dark/gold themed, same surface as
          glass-card so it visually belongs to the Account page. */}
      <AnimatePresence>
        {modal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.18 }}
            className="fixed inset-0 z-[80] flex items-end sm:items-center justify-center bg-black/70 backdrop-blur-sm px-3 pb-3 pt-12 sm:p-4"
            data-testid={`about-modal-${modal}`}
            onClick={() => setModal(null)}
          >
            <motion.div
              initial={{ y: 24, opacity: 0, scale: 0.98 }}
              animate={{ y: 0, opacity: 1, scale: 1 }}
              exit={{ y: 24, opacity: 0, scale: 0.98 }}
              transition={{ duration: 0.22, ease: "easeOut" }}
              onClick={(e) => e.stopPropagation()}
              className="w-full max-w-lg max-h-[80vh] overflow-hidden rounded-2xl border border-primary/30 bg-background/95 backdrop-blur-xl shadow-2xl shadow-primary/10 flex flex-col"
            >
              <div className="flex items-center justify-between gap-3 border-b border-border/60 px-4 py-3">
                <div className="flex items-center gap-2">
                  {modal === "privacy" ? (
                    <ShieldCheck className="h-4 w-4 text-primary" />
                  ) : modal === "rate-tv" ? (
                    <Star className="h-4 w-4 text-primary" />
                  ) : (
                    <FileText className="h-4 w-4 text-primary" />
                  )}
                  <h2 className="text-sm font-semibold text-foreground tracking-wide">
                    {modal === "privacy"
                      ? "Privacy Policy"
                      : modal === "rate-tv"
                        ? "Rate this app"
                        : "Terms & Conditions"}
                  </h2>
                </div>
                <FocusableButton
                  focusKey="about-modal-close"
                  onEnter={() => setModal(null)}
                  onClick={() => setModal(null)}
                  data-testid="about-modal-close"
                  className="grid h-8 w-8 place-items-center rounded-lg border border-border/60 bg-background/30 text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground outline-none"
                  focusClassName="border-primary/60 ring-2 ring-primary/40"
                  aria-label="Close"
                >
                  <X className="h-4 w-4" />
                </FocusableButton>
              </div>
              <div className="overflow-y-auto px-4 py-4 text-[13px] leading-relaxed text-muted-foreground prose-about">
                {modal === "rate-tv" ? (
                  <div className="space-y-3" data-testid="about-rate-tv-body">
                    <p className="leading-relaxed">
                      Thanks for using <strong className="text-foreground">Nadiplayer</strong>! ⭐
                    </p>
                    <p className="leading-relaxed">
                      {isTizen()
                        ? "Please rate this app from the Samsung Apps store on your TV: open Apps → search Nadiplayer → leave a rating."
                        : "Please rate this app from the LG Content Store: open the Store on your TV → search Nadiplayer → leave a rating."}
                    </p>
                    <p className="leading-relaxed text-[12px] text-muted-foreground/80">
                      In-app links to external app stores are restricted on
                      Smart-TV platforms — that&apos;s why we route you to the
                      built-in store instead.
                    </p>
                  </div>
                ) : (
                  <ReactMarkdown
                  components={{
                    h1: ({ children }) => (
                      <h3 className="mb-2 mt-3 text-base font-semibold text-foreground first:mt-0">
                        {children}
                      </h3>
                    ),
                    h2: ({ children }) => (
                      <h4 className="mb-2 mt-3 text-sm font-semibold text-foreground first:mt-0">
                        {children}
                      </h4>
                    ),
                    h3: ({ children }) => (
                      <h5 className="mb-2 mt-3 text-[13px] font-semibold text-foreground first:mt-0">
                        {children}
                      </h5>
                    ),
                    p: ({ children }) => (
                      <p className="mb-3 leading-relaxed last:mb-0">{children}</p>
                    ),
                    ul: ({ children }) => (
                      <ul className="mb-3 list-disc space-y-1 pl-5 marker:text-primary">
                        {children}
                      </ul>
                    ),
                    ol: ({ children }) => (
                      <ol className="mb-3 list-decimal space-y-1 pl-5 marker:text-primary">
                        {children}
                      </ol>
                    ),
                    li: ({ children }) => <li className="leading-relaxed">{children}</li>,
                    strong: ({ children }) => (
                      <strong className="font-semibold text-foreground">{children}</strong>
                    ),
                    a: ({ href, children }) => (
                      <a
                        href={href}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-primary underline-offset-2 hover:underline"
                      >
                        {children}
                      </a>
                    ),
                    code: ({ children }) => (
                      <code className="rounded bg-background/60 px-1 py-0.5 font-mono text-[12px] text-primary">
                        {children}
                      </code>
                    ),
                    hr: () => <hr className="my-3 border-border/60" />,
                  }}
                >
                  {modal === "privacy" ? privacyText : termsText}
                </ReactMarkdown>
                )}
              </div>
              <div className="border-t border-border/60 px-4 py-3 text-right">
                <FocusableButton
                  focusKey="about-modal-ok"
                  onEnter={() => setModal(null)}
                  onClick={() => setModal(null)}
                  className="rounded-lg border border-primary/40 bg-primary/15 px-4 py-2 text-xs font-medium text-primary transition-colors hover:bg-primary/25 outline-none"
                  focusClassName="ring-2 ring-primary/60 bg-primary/25"
                  data-testid="about-modal-ok"
                >
                  OK
                </FocusableButton>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

type AboutRowProps = {
  icon: React.ReactNode;
  label: string;
  sub: string;
  onClick: () => void;
  testid: string;
  focusKey: string;
};

const AboutRow = ({ icon, label, sub, onClick, testid, focusKey }: AboutRowProps) => (
  <FocusableButton
    focusKey={focusKey}
    onEnter={onClick}
    onClick={onClick}
    data-testid={testid}
    className="group flex w-full items-center gap-3 rounded-xl border border-border/60 bg-background/30 px-3 py-2.5 text-left transition-colors hover:border-primary/40 hover:bg-background/50 outline-none"
    focusClassName="border-primary/60 bg-primary/10 ring-2 ring-primary/40"
  >
    <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-primary/30 bg-primary/10 transition-colors group-hover:border-primary/50">
      {icon}
    </div>
    <div className="min-w-0 flex-1">
      <p className="text-xs font-medium text-foreground">{label}</p>
      <p className="truncate text-[11px] text-muted-foreground">{sub}</p>
    </div>
    <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground transition-colors group-hover:text-primary" />
  </FocusableButton>
);

export default AboutMenu;
