"use client";

import { useApp } from "@/contexts/AppContext";
import { ProductDetail } from "@/lib/api/fundmarket";

interface ProtocolLinkProps {
  label: string;
  url?: string;
}

function ProtocolLink({ label, url }: ProtocolLinkProps) {
  const enabled = !!url;

  return (
    <div
      onClick={() => enabled && window.open(url, '_blank', 'noopener,noreferrer')}
      className={`group rounded-xl border border-border-gray dark:border-gray-600 bg-bg-subtle dark:bg-gray-700 px-4 py-3.5 flex items-center justify-between w-full transition-all ${
        enabled
          ? 'cursor-pointer hover:border-black dark:hover:border-gray-400'
          : 'cursor-default opacity-40'
      }`}
    >
      <div className="flex items-center gap-2">
        <img
          src="/components/product/component-17.svg"
          alt=""
          width={20}
          height={20}
          className={enabled ? "transition-all group-hover:scale-110 group-hover:brightness-0 dark:group-hover:brightness-0 dark:group-hover:invert" : ""}
        />
        <span className={`text-body-small font-medium text-text-tertiary dark:text-gray-300 ${
          enabled ? 'transition-all group-hover:font-bold group-hover:text-text-primary dark:group-hover:text-white' : ''
        }`}>
          {label}
        </span>
      </div>
      <img
        src="/components/product/component-18.svg"
        alt=""
        width={20}
        height={20}
        className={enabled ? "transition-all group-hover:scale-110 group-hover:brightness-0 dark:group-hover:brightness-0 dark:group-hover:invert" : "opacity-40"}
      />
    </div>
  );
}

const DEFAULT_LINKS = [
  "Smart Contract",
  "Compliance",
  "Proof of Reserves",
  "Protocol Information",
];

interface ProtocolInformationProps {
  product: ProductDetail;
}

export default function ProtocolInformation({ product }: ProtocolInformationProps) {
  const { t } = useApp();

  const links = product.productLinks ?? [];

  // 只显示 display_area 为 protocol 或 both 的链接
  const protocolLinks = links.filter(
    (l) => l.displayArea === 'protocol' || l.displayArea === 'both'
  );

  // 有配置时用配置的，没配置时用默认占位（全部禁用）
  const items =
    protocolLinks.length > 0
      ? protocolLinks.map((l) => ({ label: l.linkText, url: l.linkUrl }))
      : DEFAULT_LINKS.map((label) => ({ label, url: undefined }));

  return (
    <div className="flex-1 bg-bg-surface dark:bg-gray-800 rounded-3xl border border-border-gray dark:border-gray-700 px-4 py-4 md:px-6 md:py-8 flex flex-col gap-4 min-h-0 overflow-hidden">
      <h3 className="text-body-large font-bold text-text-primary dark:text-white">
        {t("protocol.title")}
      </h3>
      <div className="flex-1 min-h-0 flex flex-col gap-2 overflow-y-auto pr-1 pb-1">
        {items.map((item, index) => (
          <ProtocolLink key={index} label={item.label} url={item.url} />
        ))}
      </div>
    </div>
  );
}
