import { onMounted, onBeforeUnmount, ref } from 'vue';
import { ElMessage } from 'element-plus';

/**
 * 保护水印节点防篡改
 * @param {Ref<HTMLElement>} containerRef - 包含水印的父容器的 Ref
 * @param {String} watermarkSelector - 水印节点的类名选择器，默认 '.watermark-overlay'
 * @param {Ref<Boolean>} isVipRef - 用户的 VIP 状态引用，如果是 VIP 则不进行检查
 */
export function useWatermarkGuard(containerRef, isVipRef, watermarkSelector = '.watermark-overlay') {
  let observer = null;
  let pollTimer = null;
  const isDestroyed = ref(false);

  const enforcePunishment = () => {
    if (isDestroyed.value) return;
    if (!containerRef.value) return;

    // 锁定原始尺寸，防止清空内部元素（如撑起宽高的图片）后导致外层盒子塌陷
    const width = containerRef.value.offsetWidth;
    const height = containerRef.value.offsetHeight;
    if (width && height) {
      containerRef.value.style.width = width + 'px';
      containerRef.value.style.height = height + 'px';
    }

    // 触发惩罚机制：将容器内容彻底清空并显示红色警告
    isDestroyed.value = true;
    containerRef.value.innerHTML = `
      <div style="
        position: absolute;
        inset: 0;
        background: rgba(245, 247, 250, 0.85);
        backdrop-filter: blur(8px);
        z-index: 999999;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 24px;
        text-align: center;
      ">
        <div style="
          background: #ffffff;
          border-radius: 20px;
          padding: 40px 24px;
          box-shadow: 0 12px 32px rgba(139, 126, 250, 0.15);
          width: 85%;
          max-width: 320px;
          display: flex;
          flex-direction: column;
          align-items: center;
        ">
          <div style="
            width: 64px;
            height: 64px;
            background: linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(142, 197, 252, 0.4);
          ">🛡️</div>
          <h3 style="color: #333333; font-size: 18px; font-weight: 600; margin: 0 0 12px 0;">预览已受保护</h3>
          <p style="color: #666666; font-size: 14px; line-height: 1.6; margin: 0 0 28px 0;">检测到水印显示异常<br>为保护创作者权益，预览已终止</p>
          <button onclick="window.location.reload()" style="
            background: linear-gradient(90deg, #9b81ec 0%, #7d65f5 100%);
            color: white;
            border: none;
            border-radius: 24px;
            padding: 10px 32px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(155, 129, 236, 0.3);
            transition: transform 0.2s;
          " onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
            重新加载
          </button>
        </div>
      </div>
    `;
    ElMessage.warning('由于水印显示异常，预览已被终止');
    
    if (observer) {
      observer.disconnect();
    }
  };

  const checkWatermarkIntegrity = () => {
    if (!containerRef.value || isDestroyed.value) return;
    // 如果是 VIP，不需要水印，也不需要防篡改检查
    if (isVipRef && isVipRef.value === true) return;

    const watermarkNode = containerRef.value.querySelector(watermarkSelector);
    
    // 检查 1：节点是否被直接删除
    if (!watermarkNode) {
      enforcePunishment();
      return;
    }

    // 检查 2：是否被通过 style 修改导致隐藏
    const styles = window.getComputedStyle(watermarkNode);
    if (
      styles.display === 'none' ||
      styles.visibility === 'hidden' ||
      styles.opacity === '0' ||
      parseFloat(styles.opacity) < 0.1 ||
      parseFloat(styles.width) < 10 ||
      parseFloat(styles.height) < 10 ||
      styles.position === 'static'
    ) {
      enforcePunishment();
      return;
    }
  };

  onMounted(() => {
    if (!containerRef.value) return;

    // 初次检查 (延迟一下等节点渲染完毕)
    setTimeout(() => {
      checkWatermarkIntegrity();
    }, 800);

    // 监听容器内的节点变动
    observer = new MutationObserver((mutations) => {
      if (isVipRef && isVipRef.value === true) return;
      let shouldCheck = false;
      
      for (const mutation of mutations) {
        // 如果是子节点树发生变化（可能删除了节点）
        if (mutation.type === 'childList') {
          shouldCheck = true;
          break;
        }
        // 如果是属性发生了变化（包含自身和所有子节点的样式属性改变）
        if (mutation.type === 'attributes') {
          shouldCheck = true;
          break;
        }
      }

      if (shouldCheck) {
        // 使用 setTimeout 避免在 DOM 更新周期中同步导致卡死，给恶意篡改一个反应时间
        setTimeout(() => checkWatermarkIntegrity(), 50);
      }
    });

    observer.observe(containerRef.value, {
      childList: true,       // 监听子节点增删
      subtree: true,         // 监听所有后代节点
      attributes: true,      // 监听属性变化
      attributeFilter: ['style', 'class'] // 只关注样式和类的变化
    });

    // 终极防御：轮询检查（防止修改全局 CSS 绕过 MutationObserver）
    pollTimer = setInterval(() => {
      checkWatermarkIntegrity();
    }, 1500);
  });

  onBeforeUnmount(() => {
    if (observer) {
      observer.disconnect();
    }
    if (pollTimer) {
      clearInterval(pollTimer);
    }
  });

  return { isDestroyed };
}
