"use client";

import { useEffect } from "react";
import { triggerPay } from "@/app/lib/triggerPay";
import styles from "@/app/vip/components/vip.module.css";

type InstantQaVipModalProps = {
  open: boolean;
  onClose: () => void;
};

export function InstantQaVipModal({ open, onClose }: InstantQaVipModalProps) {
  useEffect(() => {
    if (open) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [open, onClose]);

  if (!open) return null;

  const handleUnlock = () => {
    onClose();
    triggerPay();
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="qa-vip-modal-title"
    >
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />
      <div
        className="relative w-full max-w-[360px] rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-2xl animate__animated animate__fadeIn animate__faster"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mb-4 flex items-center gap-3">
          <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[var(--accent)]/20 text-xl">
            💬
          </span>
          <h2 id="qa-vip-modal-title" className="text-lg font-semibold text-[var(--foreground)]" style={{ margin: 0 }}>
            即时问答
          </h2>
        </div>
        <p className="mb-6 text-sm leading-relaxed text-[var(--muted-foreground)]">
          即时问答是会员专享的贴心服务，开通后即可获得一对一技术咨询支持，随时解答你的疑问～
        </p>
        <div className="flex flex-col gap-3">
          <button
            type="button"
            onClick={handleUnlock}
            className={`${styles.btnPrimary} ${styles.btnLarge} w-full`}
          >
            立即开通 →
          </button>
          <button
            type="button"
            onClick={onClose}
            className="w-full rounded-full border border-[var(--border)] py-2.5 text-sm text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
          >
            稍后再说
          </button>
        </div>
      </div>
    </div>
  );
}
