"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import { useTrack } from "@/hooks/use-track";
import { TRACKING_EVENTS } from "@/lib/tracking-events";
import { useDeveloperFlags } from "@/components/developer-flags-provider";

const STORAGE_KEY = "download_nova_ops_popup_closed";

export function OpsPopup() {
  const [open, setOpen] = useState(false);
  const { track } = useTrack();
  const { flags } = useDeveloperFlags();

  useEffect(() => {
    if (!flags.opsPopup) return;
    const closed = window.localStorage.getItem(STORAGE_KEY) === "1";
    if (!closed) {
      const timer = window.setTimeout(() => {
        setOpen(true);
        track(TRACKING_EVENTS.popupExpose, { scene: "global_ops_popup" });
      }, 1500);
      return () => window.clearTimeout(timer);
    }
  }, [track, flags.opsPopup]);

  if (!flags.opsPopup) return null;

  const close = () => {
    setOpen(false);
    window.localStorage.setItem(STORAGE_KEY, "1");
    track(TRACKING_EVENTS.popupClose, { scene: "global_ops_popup" });
  };

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 grid place-items-end bg-slate-950/45 p-4 md:place-items-center"
          onClick={close}
        >
          <motion.div
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 16, opacity: 0 }}
            className="card-glass w-full max-w-md"
            onClick={(e) => e.stopPropagation()}
          >
            <p className="text-xs text-cyan-300">限时运营活动</p>
            <h3 className="mt-1 text-xl font-semibold">关注公众号领取专属解锁码</h3>
            <p className="mt-2 text-sm text-slate-300">输入关键词“下载”，可获取新资源首发、加群入口与 VIP 试用资格。</p>
            <div className="mt-4 flex gap-2">
              <Link
                href="/unlock"
                onClick={() => track(TRACKING_EVENTS.popupClick, { target: "unlock", scene: "global_ops_popup" })}
                className="cta-main"
              >
                立即领取
              </Link>
              <button className="cta-sub" onClick={close}>稍后再说</button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
