import { useEffect } from "react";
import { useSiteConfig } from "../ConfigContext";

declare global {
  interface Window {
    CWDComments?: new (opts: {
      el: string;
      apiBaseUrl: string;
      postSlug: string;
      lang?: string;
      siteId?: string;
    }) => { mount: () => void };
    __cwdLikeStatusQueryPatched?: boolean;
  }
}

/** 修正 cwd-widget 点赞 GET 使用完整 URL 导致计数为 0 的问题（沿用旧脚本逻辑） */
function patchCwdLikeGetQuery(apiBaseNorm: string, postSlug: string): void {
  if (window.__cwdLikeStatusQueryPatched) return;
  window.__cwdLikeStatusQueryPatched = true;

  const base = apiBaseNorm;
  const orig = window.fetch.bind(window);
  window.fetch = function fetchPatched(input: RequestInfo | URL, init?: RequestInit) {
    let url =
      typeof input === "string"
        ? input
        : input instanceof URL
          ? input.toString()
          : input.url;
    let method = "GET";
    if (init?.method) method = String(init.method).toUpperCase();
    else if (typeof Request !== "undefined" && input instanceof Request) {
      method = String(input.method || "GET").toUpperCase();
    }
    if (
      url &&
      url.indexOf(base) === 0 &&
      url.indexOf("/api/like?") !== -1 &&
      method === "GET"
    ) {
      try {
        const u = new URL(url);
        const ps = u.searchParams.get("post_slug") || "";
        if (ps.indexOf("://") !== -1) {
          u.searchParams.set("post_slug", postSlug);
          if (typeof input === "string") {
            input = u.toString();
          } else if (typeof Request !== "undefined" && input instanceof Request) {
            input = new Request(u.toString(), input);
          } else if (input instanceof URL) {
            input = u;
          }
        }
      } catch {
        /* ignore */
      }
    }
    return orig(input as RequestInfo, init);
  };
}

export function CwdComments({ postSlug }: { postSlug: string }) {
  const { cwdApiBase, cwdSiteId } = useSiteConfig();

  useEffect(() => {
    const apiNorm = (cwdApiBase || "").replace(/\/$/, "");
    patchCwdLikeGetQuery(apiNorm, postSlug);

    function loadScript(src: string): Promise<void> {
      return new Promise((resolve, reject) => {
        const s = document.createElement("script");
        s.src = src;
        s.async = true;
        s.onload = () => resolve();
        s.onerror = () => reject(new Error(src));
        document.head.appendChild(s);
      });
    }

    let cancelled = false;
    const el = document.getElementById("comments");
    if (el) el.innerHTML = "";

    (async () => {
      try {
        if (!window.CWDComments) {
          await loadScript(
            "https://cdn.jsdelivr.net/npm/cwd-widget@0.1.11/dist/cwd.umd.js"
          );
        }
        if (cancelled || typeof window.CWDComments === "undefined") return;
        const opts: {
          el: string;
          apiBaseUrl: string;
          postSlug: string;
          lang?: string;
          siteId?: string;
        } = {
          el: "#comments",
          apiBaseUrl: cwdApiBase.replace(/\/$/, ""),
          postSlug,
          lang: "zh-CN"
        };
        if (cwdSiteId) opts.siteId = cwdSiteId;
        new window.CWDComments(opts).mount();
      } catch {
        const node = document.getElementById("comments");
        if (node) node.textContent = "评论插件加载失败。";
      }
    })();

    return () => {
      cancelled = true;
      const node = document.getElementById("comments");
      if (node) node.innerHTML = "";
    };
  }, [postSlug, cwdApiBase, cwdSiteId]);

  return (
    <section className="post-comments" aria-labelledby="comments-heading">
      <h2 id="comments-heading" className="post-comments__title">
        评论
      </h2>
      <div
        id="comments"
        data-api-base={cwdApiBase}
        data-post-slug={postSlug}
        data-lang="zh-CN"
        {...(cwdSiteId ? { "data-site-id": cwdSiteId } : {})}
      />
    </section>
  );
}
