"use client";

import { useEffect } from "react";
import { notify } from "@/lib/notifications/store";

const THREADS_ERROR_LABELS: Record<string, string> = {
  no_active_account: "請先在側欄選定帳號，再綁定官方 API。",
  missing_app_credentials: "系統尚未設定 Threads App，請聯絡管理員。",
  missing_code: "授權未完成，請重新綁定。",
  account_not_found: "帳號不存在，請重新選擇後再試。",
  "4476002": "Threads 不認得這個 App ID，請聯絡管理員檢查 Meta 後台設定。",
  "1349187": "Meta 拒絕不安全的 http 登入，請使用 https 網址。",
  "1349168": "Redirect URI 未列入 Meta 白名單，請聯絡管理員。",
};

export function ThreadsOAuthToast() {
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const connected = params.get("threads_connected");
    const error = params.get("threads_error");
    const bindThreads = params.get("bind_threads");

    if (connected === "1") {
      notify({ type: "success", title: "Threads 官方 API 已綁定" });
      window.history.replaceState({}, "", window.location.pathname);
    } else if (error) {
      notify({
        type: "error",
        title: "Threads 授權失敗",
        message: THREADS_ERROR_LABELS[error] ?? decodeURIComponent(error),
      });
      window.history.replaceState({}, "", window.location.pathname);
    } else if (bindThreads === "1") {
      notify({
        type: "info",
        title: "歡迎使用巡樓",
        message: "建議先到「連線設定」綁定 Threads 帳號，才能開始海巡與發文。",
        href: "/connections",
      });
      window.history.replaceState({}, "", window.location.pathname);
    }
  }, []);

  return null;
}