"use client";

import { useEffect, useRef, useState, type FormEvent, type PointerEvent } from "react";
import { BottomToast } from "@/components/bottom-toast";
import { useI18n } from "@/components/i18n-provider";
import { StaticUiLocalizer } from "@/components/static-ui-localizer";

type DeveloperApiKey = {
  createdAt: string;
  displayKey: string;
  id: number;
  lastUsedAt: string | null;
  name: string;
};

type IntegrationResponse = {
  error?: string;
  key?: DeveloperApiKey;
  keys?: DeveloperApiKey[];
  mailAppAccessEnabled?: boolean;
  legacyAppCompatibilityEnabled?: boolean;
  mailbox?: string;
  message?: string;
  ok?: boolean;
  planAvailable?: boolean;
  pop3AccessEnabled?: boolean;
  ready?: boolean;
  secret?: string;
};

type IntegrationTab = "api" | "imap" | "pop3";

type ConnectionBadge = {
  label: string;
  tone: "authentication" | "protocol" | "security";
};

const MAIL_HOST = "mx1.officialsite.kr";
const API_ENDPOINT = "https://mail.officialsite.kr/api/v1/mail/send";
const API_MESSAGE_ENDPOINT = "https://mail.officialsite.kr/api/v1/mail/messages";

function integrationTabClassName(active: boolean) {
  return `relative inline-flex min-w-0 flex-1 items-center justify-center gap-2 rounded-t-[14px] border px-4 text-[13px] font-semibold transition-all duration-200 sm:min-w-[148px] sm:flex-none ${
    active
      ? "z-10 -mb-px h-11 border-[#d8e3f3] border-b-white bg-white text-[#2f6df6] shadow-[0_-5px_16px_rgba(47,109,246,0.07)]"
      : "h-10 border-[#dfe7f2] bg-[#edf2f8] text-[#697991] hover:bg-[#e6edf7] hover:text-[#2f6df6]"
  }`;
}

function ImapTabIcon() {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="h-4 w-4 shrink-0"
    >
      <rect x="3.5" y="5.5" width="17" height="13" rx="2.5" />
      <path d="m4.8 7 7.2 5.6L19.2 7" />
    </svg>
  );
}

function ApiTabIcon() {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="h-4 w-4 shrink-0"
    >
      <path d="m8.5 8-4 4 4 4" />
      <path d="m15.5 8 4 4-4 4" />
      <path d="m13.5 5-3 14" />
    </svg>
  );
}

function formatDate(value: string | null) {
  if (!value) {
    return "사용 기록 없음";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return "사용 기록 없음";
  }

  return new Intl.DateTimeFormat("ko-KR", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(date);
}

function CopyIcon() {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="h-[15px] w-[15px]"
    >
      <rect x="8" y="8" width="10.5" height="10.5" rx="2" />
      <path d="M15.5 8V6.8A1.8 1.8 0 0 0 13.7 5H6.8A1.8 1.8 0 0 0 5 6.8v6.9a1.8 1.8 0 0 0 1.8 1.8H8" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="h-[15px] w-[15px]"
    >
      <path d="m5 12 4.2 4.2L19 6.7" />
    </svg>
  );
}

function CopyButton({ label, value }: { label?: string; value: string }) {
  const { tr } = useI18n();
  const [copied, setCopied] = useState(false);

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1500);
    } catch {
      setCopied(false);
    }
  };

  return (
    <button
      type="button"
      onClick={copy}
      className="inline-flex h-8 shrink-0 cursor-pointer items-center gap-1.5 rounded-[9px] px-2.5 text-[12px] font-semibold text-[#61738f] transition-colors hover:bg-[#edf4ff] hover:text-[#2f6df6]"
      aria-label={`${label ? tr(label) : tr("값")} ${tr("복사")}`}
    >
      {copied ? <CheckIcon /> : <CopyIcon />}
      <span>{tr(copied ? "복사됨" : "복사")}</span>
    </button>
  );
}

function ConnectionRow({
  label,
  value,
  detail,
  badges = [],
  copyValue,
}: {
  badges?: ConnectionBadge[];
  copyValue?: string;
  detail: string;
  label: string;
  value: string;
}) {
  const { tr } = useI18n();

  return (
    <div className="grid min-w-0 gap-2 border-t border-[#edf1f6] py-3 sm:grid-cols-[128px_minmax(0,1fr)_auto] sm:items-center sm:gap-4">
      <p className="text-[12px] font-semibold text-[#7b8ca8]">{tr(label)}</p>
      <div className="min-w-0">
        <p className="break-all text-[14px] font-semibold text-[#263956]">{tr(value)}</p>
        {badges.length > 0 ? (
          <div className="mt-2 flex flex-wrap gap-1.5">
            {badges.map((badge) => (
              <span
                key={`${badge.tone}-${badge.label}`}
                className={`inline-flex h-6 items-center rounded-full border px-2.5 text-[10px] font-semibold tracking-[-0.01em] ${
                  badge.tone === "security"
                    ? "border-[#b9e4d8] bg-[#f0fbf7] text-[#178064]"
                    : badge.tone === "authentication"
                      ? "border-[#d9d4f7] bg-[#f7f5ff] text-[#6958b8]"
                      : "border-[#cfe0ff] bg-[#f2f7ff] text-[#2f6df6]"
                }`}
              >
                {tr(badge.label)}
              </span>
            ))}
          </div>
        ) : null}
        <p className="mt-1 text-[12px] leading-5 text-[#7b8ca8]">{tr(detail)}</p>
      </div>
      {copyValue ? <CopyButton label={label} value={copyValue} /> : null}
    </div>
  );
}

function SectionHeader({
  eyebrow,
  title,
  description,
}: {
  description: string;
  eyebrow: string;
  title: string;
}) {
  const { tr } = useI18n();

  return (
    <div className="pb-4">
      <p className="text-[12px] font-semibold uppercase tracking-[0.1em] text-[#2f6df6]">
        {tr(eyebrow)}
      </p>
      <h2 className="mt-1 text-[17px] font-semibold tracking-[-0.035em] text-[#16233c] sm:text-[18px]">
        {tr(title)}
      </h2>
      <p className="mt-1.5 text-[13px] leading-5 text-[#7183a1]">{tr(description)}</p>
    </div>
  );
}

function OutlookInputRow({
  label,
  value,
  note,
}: {
  label: string;
  note?: string;
  value: string;
}) {
  const { tr } = useI18n();

  return (
    <div className="grid gap-1.5 border-t border-[#edf1f6] py-3 sm:grid-cols-[180px_minmax(0,1fr)] sm:items-start sm:gap-5">
      <p className="text-[12px] font-semibold text-[#687b99]">{tr(label)}</p>
      <div className="min-w-0">
        <p className="break-all text-[13px] font-semibold text-[#263956]">{tr(value)}</p>
        {note ? <p className="mt-1 text-[12px] leading-5 text-[#7b8ca8]">{tr(note)}</p> : null}
      </div>
    </div>
  );
}

export function MailIntegrationsPanel({
  mailbox,
  planAvailable,
}: {
  mailbox: string;
  planAvailable: boolean;
}) {
  const [keys, setKeys] = useState<DeveloperApiKey[]>([]);
  const [activeTab, setActiveTab] = useState<IntegrationTab>("imap");
  const [resolvedMailbox, setResolvedMailbox] = useState(mailbox);
  const [ready, setReady] = useState(false);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [keyName, setKeyName] = useState("");
  const [externalPassword, setExternalPassword] = useState("");
  const [externalPasswordConfirm, setExternalPasswordConfirm] = useState("");
  const [pop3Password, setPop3Password] = useState("");
  const [pop3PasswordConfirm, setPop3PasswordConfirm] = useState("");
  const [mailAppAccessEnabled, setMailAppAccessEnabled] = useState(false);
  const [legacyAppCompatibilityEnabled, setLegacyAppCompatibilityEnabled] = useState(false);
  const [pop3AccessEnabled, setPop3AccessEnabled] = useState(false);
  const [mailboxReady, setMailboxReady] = useState(false);
  const [effectivePlanAvailable, setEffectivePlanAvailable] = useState(planAvailable);
  const [generatedSecret, setGeneratedSecret] = useState("");
  const [notice, setNotice] = useState<{ message: string; tone: "error" | "success" } | null>(null);
  const planTooltipRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      try {
        const response = await fetch("/api/mailbox/integrations", { cache: "no-store" });
        const data = (await response.json()) as IntegrationResponse;

        if (!response.ok) {
          throw new Error(data.message || "외부 연동 정보를 불러오지 못했습니다.");
        }

        if (!cancelled) {
          const nextPlanAvailable = Boolean(data.planAvailable);

          setKeys(data.keys ?? []);
          setReady(Boolean(data.ready) && nextPlanAvailable);
          setMailboxReady(Boolean(data.ready));
          setResolvedMailbox(data.mailbox || mailbox);
          setMailAppAccessEnabled(Boolean(data.mailAppAccessEnabled));
          setLegacyAppCompatibilityEnabled(Boolean(data.legacyAppCompatibilityEnabled));
          setPop3AccessEnabled(Boolean(data.pop3AccessEnabled));
          setEffectivePlanAvailable(nextPlanAvailable);

        }
      } catch (error) {
        if (!cancelled) {
          setNotice({
            message: error instanceof Error ? error.message : "외부 연동 정보를 불러오지 못했습니다.",
            tone: "error",
          });
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void load();
    return () => {
      cancelled = true;
    };
  }, [mailbox]);

  useEffect(() => {
    if (!notice) {
      return undefined;
    }

    const timeoutId = window.setTimeout(() => setNotice(null), 3200);
    return () => window.clearTimeout(timeoutId);
  }, [notice]);

  const createKey = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!keyName.trim() || submitting) {
      return;
    }

    setSubmitting(true);
    setNotice(null);

    try {
      const response = await fetch("/api/mailbox/integrations", {
        body: JSON.stringify({ name: keyName }),
        headers: { "Content-Type": "application/json" },
        method: "POST",
      });
      const data = (await response.json()) as IntegrationResponse;

      if (!response.ok || !data.key || !data.secret) {
        throw new Error(data.message || "API 키를 만들지 못했습니다.");
      }

      setKeys((current) => [data.key!, ...current]);
      setGeneratedSecret(data.secret);
      setKeyName("");
      setNotice({ message: "API 키를 만들었습니다. 지금 안전한 곳에 보관해주세요.", tone: "success" });
    } catch (error) {
      setNotice({
        message: error instanceof Error ? error.message : "API 키를 만들지 못했습니다.",
        tone: "error",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const movePlanTooltip = (event: PointerEvent<HTMLDivElement>) => {
    const tooltip = planTooltipRef.current;

    if (!tooltip) {
      return;
    }

    const left = Math.min(event.clientX + 16, window.innerWidth - 252);
    const top = Math.min(event.clientY + 18, window.innerHeight - 54);
    tooltip.style.transform = `translate3d(${Math.max(8, left)}px, ${Math.max(8, top)}px, 0)`;
  };

  const saveExternalPassword = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (submitting || !externalPassword || externalPassword !== externalPasswordConfirm) {
      setNotice({
        message: externalPassword !== externalPasswordConfirm
          ? "외부 연결 비밀번호가 서로 일치하지 않습니다."
          : "외부 연결 비밀번호를 입력해주세요.",
        tone: "error",
      });
      return;
    }

    setSubmitting(true);
    setNotice(null);

    try {
      const response = await fetch("/api/mailbox/integrations", {
        body: JSON.stringify({ password: externalPassword }),
        headers: { "Content-Type": "application/json" },
        method: "PUT",
      });
      const data = (await response.json()) as IntegrationResponse;

      if (!response.ok || !data.mailAppAccessEnabled) {
        throw new Error(data.message || "외부 연결 비밀번호를 설정하지 못했습니다.");
      }

      setMailAppAccessEnabled(true);
      setExternalPassword("");
      setExternalPasswordConfirm("");
      setNotice({ message: "외부 메일 앱 연결을 활성화했습니다.", tone: "success" });
    } catch (error) {
      setNotice({
        message: error instanceof Error ? error.message : "외부 연결 비밀번호를 설정하지 못했습니다.",
        tone: "error",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const disableExternalAccess = async () => {
    if (submitting || !mailAppAccessEnabled) {
      return;
    }

    setSubmitting(true);
    setNotice(null);

    try {
      const response = await fetch("/api/mailbox/integrations", {
        body: JSON.stringify({ mailAppAccessEnabled: false }),
        headers: { "Content-Type": "application/json" },
        method: "PATCH",
      });
      const data = (await response.json()) as IntegrationResponse;

      if (!response.ok) {
        throw new Error(data.message || "외부 메일 앱 연결을 해제하지 못했습니다.");
      }

      setMailAppAccessEnabled(false);
      setNotice({
        message: legacyAppCompatibilityEnabled
          ? "외부 연결 전용 비밀번호를 해제했습니다. 구버전 앱 호환이 켜진 동안에는 계정 비밀번호로 IMAP에 연결할 수 있습니다."
          : "외부 메일 앱 연결을 차단했습니다.",
        tone: "success",
      });
    } catch (error) {
      setNotice({
        message: error instanceof Error ? error.message : "외부 메일 앱 연결을 해제하지 못했습니다.",
        tone: "error",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const disableLegacyCompatibility = async () => {
    if (submitting || !legacyAppCompatibilityEnabled) return;
    setSubmitting(true);
    setNotice(null);
    try {
      const response = await fetch("/api/mailbox/integrations", {
        body: JSON.stringify({ legacyAppCompatibilityEnabled: false }),
        headers: { "Content-Type": "application/json" },
        method: "PATCH",
      });
      const data = (await response.json()) as IntegrationResponse;
      if (!response.ok) throw new Error(data.message || "구버전 앱 호환을 해제하지 못했습니다.");
      setLegacyAppCompatibilityEnabled(false);
      setMailAppAccessEnabled(Boolean(data.mailAppAccessEnabled));
      setNotice({ message: "구버전 앱 호환 연결을 해제했습니다. 구버전 앱은 업데이트가 필요합니다.", tone: "success" });
    } catch (error) {
      setNotice({ message: error instanceof Error ? error.message : "구버전 앱 호환을 해제하지 못했습니다.", tone: "error" });
    } finally {
      setSubmitting(false);
    }
  };

  const savePop3Password = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (submitting || !pop3Password || pop3Password !== pop3PasswordConfirm) {
      setNotice({
        message: pop3Password !== pop3PasswordConfirm
          ? "POP3 전용 비밀번호가 서로 일치하지 않습니다."
          : "POP3 전용 비밀번호를 입력해주세요.",
        tone: "error",
      });
      return;
    }

    setSubmitting(true);
    setNotice(null);

    try {
      const response = await fetch("/api/mailbox/integrations", {
        body: JSON.stringify({ accessType: "pop3", password: pop3Password }),
        headers: { "Content-Type": "application/json" },
        method: "PUT",
      });
      const data = (await response.json()) as IntegrationResponse;

      if (!response.ok) {
        throw new Error(data.message || "POP3 전용 비밀번호를 설정하지 못했습니다.");
      }

      setPop3AccessEnabled(Boolean(data.pop3AccessEnabled));
      setPop3Password("");
      setPop3PasswordConfirm("");
      setNotice({ message: "POP3 수신을 활성화했습니다.", tone: "success" });
    } catch (error) {
      setNotice({
        message: error instanceof Error ? error.message : "POP3 전용 비밀번호를 설정하지 못했습니다.",
        tone: "error",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const disablePop3Access = async () => {
    if (submitting || !pop3AccessEnabled) {
      return;
    }

    setSubmitting(true);
    setNotice(null);

    try {
      const response = await fetch("/api/mailbox/integrations", {
        body: JSON.stringify({ pop3AccessEnabled: false }),
        headers: { "Content-Type": "application/json" },
        method: "PATCH",
      });
      const data = (await response.json()) as IntegrationResponse;

      if (!response.ok) {
        throw new Error(data.message || "POP3 연결을 차단하지 못했습니다.");
      }

      setPop3AccessEnabled(false);
      setNotice({ message: "POP3 수신을 차단했습니다.", tone: "success" });
    } catch (error) {
      setNotice({
        message: error instanceof Error ? error.message : "POP3 연결을 차단하지 못했습니다.",
        tone: "error",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const revokeKey = async (apiKey: DeveloperApiKey) => {
    if (!window.confirm(`'${apiKey.name}' API 키를 폐기할까요? 폐기 후에는 복구할 수 없습니다.`)) {
      return;
    }

    setSubmitting(true);
    setNotice(null);

    try {
      const response = await fetch("/api/mailbox/integrations", {
        body: JSON.stringify({ id: apiKey.id }),
        headers: { "Content-Type": "application/json" },
        method: "DELETE",
      });
      const data = (await response.json()) as IntegrationResponse;

      if (!response.ok) {
        throw new Error(data.message || "API 키를 폐기하지 못했습니다.");
      }

      setKeys((current) => current.filter((item) => item.id !== apiKey.id));
      setGeneratedSecret("");
      setNotice({ message: "API 키를 폐기했습니다.", tone: "success" });
    } catch (error) {
      setNotice({
        message: error instanceof Error ? error.message : "API 키를 폐기하지 못했습니다.",
        tone: "error",
      });
    } finally {
      setSubmitting(false);
    }
  };

  const selectTab = (tab: IntegrationTab) => {
    setActiveTab(tab);
  };

  const curlExample = `curl -X POST ${API_ENDPOINT} \\\n  -H "Authorization: Bearer om_live_발급받은_API_키" \\\n  -H "Content-Type: application/json" \\\n  -d '{\n    "to": ["customer@example.com"],\n    "subject": "주문이 접수되었습니다",\n    "text": "주문 내용을 확인했습니다."\n  }'`;
  const statusCurlExample = `curl ${API_MESSAGE_ENDPOINT}/2251918 \\\n  -H "Authorization: Bearer om_live_발급받은_API_키"`;
  const statusResponseExample = `{
  "ok": true,
  "data": {
    "messageId": 2251918,
    "status": "sent",
    "from": "${resolvedMailbox}",
    "to": "customer@example.com",
    "subject": "주문이 접수되었습니다",
    "messageIdHeader": "<...>",
    "createdAt": "2026-08-06T10:00:00.000Z",
    "updatedAt": "2026-08-06T10:00:02.000Z",
    "logs": []
  }
}`;
  const planRestricted = !effectivePlanAvailable;

  return (
    <StaticUiLocalizer>
      <>
      <div className="om-setup-header lg:flex-row lg:items-start lg:justify-between lg:gap-5">
        <div className="om-setup-header-copy">
          <h1 className="om-page-title text-[#16233c]">외부 연동</h1>
          <p className="om-setup-header-description">
            Outlook 등 외부 메일 앱의 IMAP, POP3, SMTP 연결과 발송 API는 성장 플랜부터 제공됩니다. 오피셜메일 웹과 앱은 무료 플랜에서도 사용할 수 있습니다.
          </p>
        </div>
        <span className={`om-badge om-badge-lg ${effectivePlanAvailable ? "om-badge-info" : "om-badge-soft"}`}>
          {effectivePlanAvailable ? "성장 플랜 이용 중" : "성장 플랜 전용"}
        </span>
      </div>

      <div className="px-3 pb-5 pt-4 sm:px-4 lg:px-5">
        {legacyAppCompatibilityEnabled ? (
          <div className="mb-4 rounded-[12px] border border-[#f3d8a6] bg-[#fff9ec] px-4 py-3 text-[12px] leading-5 text-[#8b5a17]">
            <p>구버전 오피셜메일 앱 호환이 켜져 있어 계정 비밀번호로도 IMAP에 연결할 수 있습니다. 이 경우 타사 메일 프로그램에서도 같은 비밀번호가 동작할 수 있습니다. 모든 기기를 새 앱으로 업데이트한 뒤에는 이 호환 연결을 해제하는 것이 안전합니다.</p>
            <button type="button" disabled={submitting} onClick={() => void disableLegacyCompatibility()} className="mt-2 cursor-pointer font-semibold underline disabled:cursor-not-allowed disabled:opacity-60">
              구버전 앱 호환 해제 — 구버전 앱 로그인 중단
            </button>
          </div>
        ) : null}
        <div
          className="flex w-full items-end gap-1 sm:w-auto"
          role="tablist"
          aria-label="외부 연동 종류"
        >
          <button
            type="button"
            role="tab"
            aria-selected={activeTab === "pop3"}
            onClick={() => selectTab("pop3")}
            className={integrationTabClassName(activeTab === "pop3")}
          >
            <ImapTabIcon />
            <span>POP3</span>
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={activeTab === "imap"}
            onClick={() => selectTab("imap")}
            className={integrationTabClassName(activeTab === "imap")}
          >
            <ImapTabIcon />
            <span>IMAP/SMTP</span>
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={activeTab === "api"}
            onClick={() => selectTab("api")}
            className={integrationTabClassName(activeTab === "api")}
          >
            <ApiTabIcon />
            <span>발송 API</span>
          </button>
        </div>

        <div
          className="relative overflow-hidden rounded-b-[16px] rounded-tr-[16px] border border-[#d8e3f3] bg-white shadow-[0_14px_34px_rgba(26,45,78,0.06)]"
        >
          <div
            className="om-setup-content relative"
            aria-disabled={planRestricted}
            onPointerMove={planRestricted ? movePlanTooltip : undefined}
            onPointerEnter={
              planRestricted
                ? () => planTooltipRef.current?.classList.replace("opacity-0", "opacity-100")
                : undefined
            }
            onPointerLeave={
              planRestricted
                ? () => planTooltipRef.current?.classList.replace("opacity-100", "opacity-0")
                : undefined
            }
          >
            {planRestricted ? (
              <>
                <div
                  className="absolute inset-0 z-20 flex cursor-not-allowed items-start justify-center bg-white/78 px-5 pt-14 backdrop-blur-[8px]"
                  aria-label="성장 플랜 전용 기능"
                >
                  <div className="rounded-[14px] border border-[#cddcff] bg-white px-5 py-4 text-center shadow-[0_14px_36px_rgba(35,67,125,0.14)]">
                    <p className="text-[14px] font-semibold text-[#203758]">성장 플랜 전용 외부 연동</p>
                    <p className="mt-1 text-[12px] leading-5 text-[#71819a]">외부 메일 앱 연결과 발송 API는 성장 플랜부터 사용할 수 있습니다.</p>
                  </div>
                </div>
                <div
                  ref={planTooltipRef}
                  className="pointer-events-none fixed left-0 top-0 z-[200] max-w-[240px] rounded-[10px] bg-[#17233a] px-3 py-2 text-[12px] font-semibold text-white opacity-0 shadow-[0_12px_30px_rgba(18,32,65,0.22)] transition-opacity duration-150"
                >
                  성장 플랜부터 이용 가능한 서비스예요!
                </div>
              </>
            ) : null}
            <div
              className={planRestricted ? "pointer-events-none select-none opacity-15 blur-[5px]" : "contents"}
              inert={planRestricted}
            >
              {activeTab === "imap" ? (
            <>
              <section className="om-setup-panel bg-[#f8faff] px-3 py-4 sm:px-4 lg:px-5">
                <SectionHeader
                  eyebrow="보안"
                  title={mailAppAccessEnabled ? "외부 연결 비밀번호 변경" : "외부 메일 앱 연결 활성화"}
                  description="오피셜메일 로그인 비밀번호와 분리된 전용 비밀번호입니다. 성장 플랜에서 IMAP 수신과 SMTP 발송에 사용할 수 있습니다."
                />
                <form className="mt-4 grid gap-3 sm:grid-cols-2" onSubmit={saveExternalPassword}>
                  <input
                    type="password"
                    autoComplete="new-password"
                    value={externalPassword}
                    onChange={(event) => setExternalPassword(event.target.value)}
                    placeholder="외부 연결 비밀번호"
                    className="h-11 rounded-[11px] border border-[#d7e1f0] bg-white px-3 text-[13px] text-[#263956] outline-none transition-colors focus:border-[#2f6df6]"
                  />
                  <input
                    type="password"
                    autoComplete="new-password"
                    value={externalPasswordConfirm}
                    onChange={(event) => setExternalPasswordConfirm(event.target.value)}
                    placeholder="외부 연결 비밀번호 확인"
                    className="h-11 rounded-[11px] border border-[#d7e1f0] bg-white px-3 text-[13px] text-[#263956] outline-none transition-colors focus:border-[#2f6df6]"
                  />
                  <div className="sm:col-span-2">
                    <div className="flex flex-wrap gap-2">
                      <button
                        type="submit"
                        disabled={submitting}
                        className="om-btn-primary h-10 cursor-pointer rounded-[11px] px-5 text-[13px] disabled:cursor-not-allowed disabled:opacity-60"
                      >
                        {submitting ? "설정 중..." : mailAppAccessEnabled ? "비밀번호 변경" : "외부 연결 활성화"}
                      </button>
                      {mailAppAccessEnabled ? (
                        <button
                          type="button"
                          disabled={submitting}
                          onClick={() => void disableExternalAccess()}
                          className="h-10 cursor-pointer rounded-[11px] border border-[#d9e2ef] bg-white px-5 text-[13px] font-semibold text-[#7c4a55] transition-colors hover:bg-[#fff4f5] disabled:cursor-not-allowed disabled:opacity-60"
                        >
                          외부 연결 차단
                        </button>
                      ) : null}
                    </div>
                  </div>
                </form>
              </section>
              <section className="om-setup-panel bg-white px-3 py-4 sm:px-4 lg:px-5">
                <SectionHeader
                  eyebrow="메일 앱"
                  title="IMAP/SMTP 연결값"
                  description="성장 플랜에서 IMAP으로 메일함을 동기화하고 SMTP로 메일을 발송할 때 사용하는 설정입니다."
                />
          <ConnectionRow
            label="사용자 이름"
            value={resolvedMailbox}
            detail={effectivePlanAvailable ? "받는 메일과 보내는 메일 모두 전체 주소를 입력합니다." : "전체 메일 주소를 입력합니다."}
            copyValue={resolvedMailbox}
          />
          <ConnectionRow
            label="받는 메일"
            value={`${MAIL_HOST} · 993`}
            badges={[
              { label: "IMAP", tone: "protocol" },
              { label: "SSL/TLS", tone: "security" },
            ]}
            detail="외부 연결 전용 비밀번호로 메일함과 읽음 상태를 동기화합니다."
            copyValue={MAIL_HOST}
          />
          {effectivePlanAvailable ? <ConnectionRow
            label="보내는 메일"
            value={`${MAIL_HOST} · 587`}
            badges={[
              { label: "SMTP", tone: "protocol" },
              { label: "STARTTLS", tone: "security" },
              { label: "인증 필요", tone: "authentication" },
            ]}
            detail="일반적인 메일 앱에서 권장하는 기본 발송 연결입니다."
            copyValue={MAIL_HOST}
          /> : null}
          {effectivePlanAvailable ? <ConnectionRow
            label="보내는 메일 대체 연결"
            value={`${MAIL_HOST} · 465`}
            badges={[
              { label: "SMTP", tone: "protocol" },
              { label: "SSL/TLS", tone: "security" },
              { label: "인증 필요", tone: "authentication" },
            ]}
            detail="587 포트 또는 STARTTLS를 사용할 수 없는 환경에서 선택합니다."
            copyValue={MAIL_HOST}
          /> : null}
        </section>

            </>
          ) : activeTab === "pop3" ? (
            <>
              <section className="om-setup-panel bg-[#f8faff] px-3 py-4 sm:px-4 lg:px-5">
                <SectionHeader
                  eyebrow="성장 플랜 외부 수신"
                  title={pop3AccessEnabled ? "POP3 전용 비밀번호 변경" : "POP3 수신 활성화"}
                  description="POP3는 성장 플랜에서 받은메일함을 기기로 내려받는 수신 전용 방식입니다."
                />
                <form className="mt-4 grid gap-3 sm:grid-cols-2" onSubmit={savePop3Password}>
                  <input
                    type="password"
                    autoComplete="new-password"
                    value={pop3Password}
                    onChange={(event) => setPop3Password(event.target.value)}
                    placeholder="POP3 전용 비밀번호"
                    disabled={!mailboxReady}
                    className="h-11 rounded-[11px] border border-[#d7e1f0] bg-white px-3 text-[13px] text-[#263956] outline-none transition-colors focus:border-[#2f6df6] disabled:cursor-not-allowed disabled:bg-[#f3f5f8]"
                  />
                  <input
                    type="password"
                    autoComplete="new-password"
                    value={pop3PasswordConfirm}
                    onChange={(event) => setPop3PasswordConfirm(event.target.value)}
                    placeholder="POP3 전용 비밀번호 확인"
                    disabled={!mailboxReady}
                    className="h-11 rounded-[11px] border border-[#d7e1f0] bg-white px-3 text-[13px] text-[#263956] outline-none transition-colors focus:border-[#2f6df6] disabled:cursor-not-allowed disabled:bg-[#f3f5f8]"
                  />
                  <div className="sm:col-span-2">
                    <p className="mb-3 text-[12px] leading-5 text-[#71819a]">
                      이 비밀번호는 POP3 수신에만 사용할 수 있으며 IMAP·SMTP 인증에는 사용할 수 없습니다.
                    </p>
                    <div className="flex flex-wrap gap-2">
                      <button
                        type="submit"
                        disabled={submitting || !mailboxReady}
                        className="om-btn-primary h-10 cursor-pointer rounded-[11px] px-5 text-[13px] disabled:cursor-not-allowed disabled:opacity-60"
                      >
                        {submitting ? "설정 중..." : pop3AccessEnabled ? "비밀번호 변경" : "POP3 수신 활성화"}
                      </button>
                      {pop3AccessEnabled ? (
                        <button
                          type="button"
                          disabled={submitting}
                          onClick={() => void disablePop3Access()}
                          className="h-10 cursor-pointer rounded-[11px] border border-[#d9e2ef] bg-white px-5 text-[13px] font-semibold text-[#7c4a55] transition-colors hover:bg-[#fff4f5] disabled:cursor-not-allowed disabled:opacity-60"
                        >
                          POP3 수신 차단
                        </button>
                      ) : null}
                    </div>
                  </div>
                </form>
                {!mailboxReady && !loading ? (
                  <p className="mt-3 text-[12px] leading-5 text-[#b36b2c]">도메인 연결과 메일함 활성화를 완료하면 POP3를 사용할 수 있습니다.</p>
                ) : null}
              </section>

              <section className="om-setup-panel bg-white px-3 py-4 sm:px-4 lg:px-5">
                <SectionHeader
                  eyebrow="연결값"
                  title="POP3 받는 메일 서버 설정"
                  description="메일 프로그램의 수신 방식에서 POP3를 선택하고 아래 수신값만 입력하세요."
                />
                <ConnectionRow
                  label="사용자 이름"
                  value={resolvedMailbox}
                  detail="전체 메일 주소를 입력합니다."
                  copyValue={resolvedMailbox}
                />
                <ConnectionRow
                  label="POP3 받는 메일"
                  value={`${MAIL_HOST} · 995`}
                  badges={[
                    { label: "POP3", tone: "protocol" },
                    { label: "SSL/TLS", tone: "security" },
                    { label: "수신 전용", tone: "authentication" },
                  ]}
                  detail="위에서 설정한 POP3 전용 비밀번호로 받은메일함을 내려받습니다."
                  copyValue={MAIL_HOST}
                />
                {effectivePlanAvailable ? (
                  <p className="mt-4 rounded-[11px] bg-[#f5f8fd] px-4 py-3 text-[12px] leading-5 text-[#71819a]">
                    메일 발송도 연결하려면 IMAP/SMTP 탭에서 별도의 외부 연결 비밀번호를 설정하세요.
                  </p>
                ) : null}
              </section>

              <section className="om-setup-panel bg-white px-3 py-4 sm:px-4 lg:px-5">
                <SectionHeader
                  eyebrow="동작 범위"
                  title="POP3 클라이언트 설정 안내"
                  description="POP3의 보관·삭제 동작은 연결한 메일 프로그램에서 결정됩니다."
                />
                <OutlookInputRow label="적용 범위" value="받은메일함의 메일" note="POP3는 사용자 메일함이나 보낸메일함을 동기화하지 않습니다." />
                <OutlookInputRow label="읽음 표시" value="메일 프로그램 설정에 따름" note="POP3 수신과 오피셜메일의 읽음 상태는 IMAP처럼 실시간 동기화되지 않습니다." />
                <OutlookInputRow label="원본 보관" value="서버에 복사본 보관 권장" note="메일 프로그램에서 ‘서버에 메시지 복사본 남기기’를 켜야 다른 기기와 웹메일에서도 계속 확인할 수 있습니다." />
                <OutlookInputRow label="외부 메일 포함" value="받은메일함에 수신된 메일 포함" note="오피셜메일 받은메일함에 존재하는 메시지를 POP3로 내려받습니다." />
              </section>
            </>
          ) : (
            <section className="om-setup-panel bg-white px-3 py-4 sm:px-4 lg:px-5">
              <SectionHeader
                eyebrow="Developer API"
            title="서비스 발송 API"
            description="복사 가능한 요청 예시를 AI 코딩 도구에 전달해 주문 완료·회원가입·비밀번호 재설정 같은 메일 발송 코드를 빠르게 구현할 수 있습니다."
          />

          <div className="mb-4 border-y border-[#dce7fa] bg-[#f7faff] px-3 py-4 sm:px-4">
            <p className="text-[13px] font-semibold text-[#263956]">바이브코딩으로도 바로 연결할 수 있습니다</p>
            <p className="mt-1 text-[12px] leading-5 text-[#6f819d]">
              아래 API 예제를 복사해 “이 요청 규격으로 우리 서비스의 주문 완료 메일을 연결해줘”라고 요청하면 됩니다. AI가 계정이나 보안 설정을 대신하는 기능은 아니며, 생성된 서버 코드는 반드시 검토한 뒤 API 키를 서버 환경변수에 보관하세요.
            </p>
          </div>

          {generatedSecret ? (
            <div className="mb-4 border-y border-[#cfe0ff] bg-[#f5f8ff] px-3 py-4 sm:px-4">
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div className="min-w-0">
                  <p className="text-[13px] font-semibold text-[#234b9c]">지금 API 키를 저장해주세요</p>
                  <p className="mt-1 text-[12px] leading-5 text-[#64799d]">
                    보안을 위해 이 값은 페이지를 벗어나면 다시 확인할 수 없습니다.
                  </p>
                  <code className="mt-2 block break-all text-[13px] font-semibold text-[#173a7a]">
                    {generatedSecret}
                  </code>
                </div>
                <CopyButton label="새 API 키" value={generatedSecret} />
              </div>
            </div>
          ) : null}

          <form onSubmit={createKey} className="flex flex-col gap-2 border-t border-[#edf1f6] py-4 sm:flex-row">
            <input
              type="text"
              value={keyName}
              onChange={(event) => setKeyName(event.target.value)}
              maxLength={80}
              placeholder="키 이름 예: 주문 알림 서버"
              disabled={!ready || submitting}
              className="h-10 min-w-0 flex-1 rounded-[10px] border border-[#dfe7f4] bg-white px-3 text-[13px] text-[#263956] outline-none transition-colors placeholder:text-[#9aa8bd] focus:border-[#9fbdff] disabled:cursor-not-allowed disabled:bg-[#f6f8fb]"
            />
            <button
              type="submit"
              disabled={!ready || !keyName.trim() || submitting}
              className="om-btn-primary h-10 shrink-0 rounded-[10px] px-4 text-[13px] shadow-none hover:shadow-none disabled:cursor-not-allowed disabled:opacity-50"
            >
              {submitting ? "처리 중" : "API 키 만들기"}
            </button>
          </form>

          {!ready && !loading ? (
            <p className="border-t border-[#edf1f6] py-3 text-[13px] text-[#b36b2c]">
              도메인 연결과 메일함 활성화를 완료하면 API 키를 발급할 수 있습니다.
            </p>
          ) : null}

          <div className="border-t border-[#edf1f6]">
            <div className="flex items-center justify-between py-3">
              <p className="text-[13px] font-semibold text-[#30425f]">활성 API 키</p>
              <span className="text-[12px] text-[#8391a8]">{loading ? "불러오는 중" : `${keys.length}개`}</span>
            </div>
            {!loading && keys.length === 0 ? (
              <p className="border-t border-[#edf1f6] py-4 text-[13px] text-[#7b8ca8]">
                아직 발급한 API 키가 없습니다.
              </p>
            ) : null}
            {keys.map((apiKey) => (
              <div
                key={apiKey.id}
                className="grid gap-3 border-t border-[#edf1f6] py-3 sm:grid-cols-[minmax(0,1fr)_180px_auto] sm:items-center"
              >
                <div className="min-w-0">
                  <p className="truncate text-[13px] font-semibold text-[#263956]">{apiKey.name}</p>
                  <code className="mt-1 block text-[12px] text-[#6f819d]">{apiKey.displayKey}</code>
                </div>
                <div className="text-[12px] leading-5 text-[#7b8ca8]">
                  <p>생성 {formatDate(apiKey.createdAt)}</p>
                  <p>최근 사용 {formatDate(apiKey.lastUsedAt)}</p>
                </div>
                <button
                  type="button"
                  onClick={() => void revokeKey(apiKey)}
                  disabled={submitting}
                  className="h-8 cursor-pointer rounded-[9px] px-2.5 text-[12px] font-semibold text-[#a15b62] transition-colors hover:bg-[#fff1f2] disabled:cursor-not-allowed disabled:opacity-50"
                >
                  폐기
                </button>
              </div>
            ))}
          </div>

          <div className="mt-2 border-t border-[#edf1f6] pt-4">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <p className="text-[13px] font-semibold text-[#30425f]">POST {API_ENDPOINT}</p>
                <p className="mt-1 text-[12px] leading-5 text-[#7b8ca8]">
                  JSON으로 to, subject와 text 또는 html을 보냅니다. 요청당 수신자는 최대 50명입니다.
                </p>
              </div>
              <CopyButton label="API 예제" value={curlExample} />
            </div>
            <pre className="mt-3 overflow-x-auto rounded-[10px] bg-[#172033] p-4 text-[12px] leading-6 text-[#dce7ff]">
              <code>{curlExample}</code>
            </pre>
          </div>

          <div className="mt-5 border-t border-[#edf1f6] pt-4">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <p className="text-[13px] font-semibold text-[#30425f]">
                  GET {API_MESSAGE_ENDPOINT}/&#123;messageId&#125;
                </p>
                <p className="mt-1 text-[12px] leading-5 text-[#7b8ca8]">
                  발송 응답으로 받은 messageId를 넣어 현재 상태와 전송 로그를 확인합니다.
                </p>
              </div>
              <CopyButton label="발송 기록 조회 예제" value={statusCurlExample} />
            </div>
            <pre className="mt-3 overflow-x-auto rounded-[10px] bg-[#172033] p-4 text-[12px] leading-6 text-[#dce7ff]">
              <code>{statusCurlExample}</code>
            </pre>
            <p className="mt-4 text-[12px] font-semibold text-[#687b99]">응답 예시</p>
            <pre className="mt-2 overflow-x-auto rounded-[10px] bg-[#f4f7fc] p-4 text-[12px] leading-6 text-[#30425f]">
              <code>{statusResponseExample}</code>
            </pre>
            <p className="mt-3 text-[12px] leading-5 text-[#7b8ca8]">
              상태는 queued(대기), sent(발송 완료), failed(실패) 중 하나로 확인할 수 있습니다.
            </p>
          </div>
            </section>
              )}
            </div>
          </div>
        </div>
      </div>
      {notice ? <BottomToast notice={notice} onClose={() => setNotice(null)} /> : null}
      </>
    </StaticUiLocalizer>
  );
}
