"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import vipStyles from "@/app/vip/components/vip.module.css";
import styles from "./NetdiskDownloadsSection.module.css";
import { Copyable } from "@/app/vip/components/Copyable";
import { NETDISK_RESOURCES, type NetdiskLink, type NetdiskResource } from "@/app/config/netdisk-downloads";

type Variant = "vip" | "guest";

type ModalState = {
  resource: NetdiskResource;
  link: NetdiskLink;
} | null;

function DownloadIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M12 3v12" />
      <path d="m17 10-5 5-5-5" />
      <path d="M21 21H3" />
    </svg>
  );
}

function buildCopyText(resource: NetdiskResource, link: NetdiskLink) {
  if (link.copyText?.trim()) return link.copyText.trim();
  const url = link.url?.trim() || "";
  const code = link.code?.trim() || "";
  const codeLabel = link.codeLabel || "提取码";

  // 复制内容尽量“无歧义”，不写百度/夸克字样（避免用户认为需要转发“带品牌”）
  return [resource.title, url, code ? `${codeLabel}: ${code}` : ""].filter(Boolean).join("\n");
}

function getResourceEmoji(resource: NetdiskResource) {
  if (resource.id === "system-firmware") return "🧱";
  if (resource.id === "software-tools") return "🛠️";
  return "📦";
}

export function NetdiskDownloadsSection({ variant, onRequireVip }: { variant: Variant; onRequireVip?: () => void }) {
  const [open, setOpen] = useState<Record<string, boolean>>({});
  const [modal, setModal] = useState<ModalState>(null);
  const locked = variant === "guest";

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

  const getLinkByProvider = (resource: NetdiskResource, provider: NetdiskLink["provider"]) => {
    return resource.links.find((l) => l.provider === provider) || null;
  };

  return (
    <div className={vipStyles.section} aria-label="网盘下载">
      <h2 className={vipStyles.sectionTitle}>网盘下载</h2>

      <div className={`${vipStyles.topicGrid} animate__animated animate__fadeInUp`} style={{ animationDelay: "0.2s", animationFillMode: "both" }}>
        {NETDISK_RESOURCES.map((r) => {
          const isOpen = !!open[r.id];
          const emoji = getResourceEmoji(r);

          return (
            <div
              key={r.id}
              className={vipStyles.topicCard}
              role="button"
              tabIndex={0}
              onClick={() => {
                if (locked) {
                  onRequireVip?.();
                  return;
                }
                setOpen((m) => ({ ...m, [r.id]: !m[r.id] }));
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  if (locked) onRequireVip?.();
                  else setOpen((m) => ({ ...m, [r.id]: !m[r.id] }));
                }
              }}
              aria-expanded={variant === "vip" ? isOpen : undefined}
              style={{ textAlign: "center", cursor: "pointer", opacity: locked ? 0.98 : 1 }}
            >
              {locked && <span className={vipStyles.topicLock} title="会员专享">🔒</span>}

              <span className={vipStyles.topicCardInner}>
                <span className={vipStyles.topicIcon} aria-hidden="true">
                  {emoji}
                </span>
                <span className={vipStyles.topicTitle}>{r.title}</span>
              </span>

              {variant === "vip" && isOpen && (
                <div id={`netdisk-panel-${r.id}`} className={styles.panel} role="region" aria-label={`${r.title} 链接`}>
                  {(() => {
                    const quark = getLinkByProvider(r, "quark");
                    const quarkUrl = quark?.url?.trim() || "";

                    return (
                      <div className={styles.iconRow} aria-label="下载图标">
                        <button
                          type="button"
                          className={`${styles.netdiskIconBtn} ${!quarkUrl ? styles.netdiskIconBtnDisabled : ""}`}
                          onClick={() => {
                            if (!quark || !quarkUrl) return;
                            setModal({ resource: r, link: quark });
                          }}
                          disabled={!quarkUrl}
                          aria-disabled={!quarkUrl}
                          title={quarkUrl ? "打开夸克网盘分享" : "链接待补充"}
                        >
                          <span className={styles.iconColorQuark} aria-hidden="true">
                            <DownloadIcon />
                          </span>
                        </button>
                      </div>
                    );
                  })()}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {modal && (
        <div
          className={styles.modalOverlay}
          role="dialog"
          aria-modal="true"
          aria-label="分享链接弹窗"
          onMouseDown={(e) => {
            if (e.target === e.currentTarget) setModal(null);
          }}
        >
          <div className={styles.modal}>
            <div className={styles.modalHeader}>
              <div className={styles.modalTitleRow}>
                <span className={styles.modalIcon} aria-hidden="true">
                  <DownloadIcon />
                </span>
                <div className={styles.modalTitle}>{modal.resource.title}</div>
              </div>
              <button type="button" className={styles.modalCloseBtn} onClick={() => setModal(null)} aria-label="关闭">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M18 6 6 18" />
                  <path d="M6 6l12 12" />
                </svg>
              </button>
            </div>

            <div className={styles.modalBody}>
              <div className={styles.modalPre} aria-label="网盘分享内容">
                {buildCopyText(modal.resource, modal.link)}
              </div>
            </div>

            <div className={styles.modalActions}>
              <Copyable
                text={buildCopyText(modal.resource, modal.link)}
                className={styles.modalCopyBtn}
              >
                复制
              </Copyable>

              {modal.link.url ? (
                <Link
                  className={styles.modalOpenBtn}
                  href={modal.link.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  title="打开分享链接"
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M14 3h7v7" />
                    <path d="M10 14L21 3" />
                    <path d="M21 14v7H3V3h7" />
                  </svg>
                </Link>
              ) : (
                <span className={`${styles.modalOpenBtn} ${styles.modalOpenBtnDisabled}`} aria-disabled="true">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M14 3h7v7" />
                    <path d="M10 14L21 3" />
                    <path d="M21 14v7H3V3h7" />
                  </svg>
                </span>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

