import Link from "next/link";
import {
  copy as localizedCopy,
  homeCopy,
  seoGenericCopy,
} from "@/components/localized-public-pages";
import { localizeStaticUiValue } from "@/components/server-static-ui-localizer";
import type { SupportedLocale } from "@/lib/i18n-config";
import { MAIL_PLAN_CARDS } from "@/lib/mail-plan-cards";

function CheckBullet() {
  return (
    <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[#2f6df6] text-[12px] font-bold text-white shadow-[0_8px_18px_rgba(47,109,246,0.22)]">
      ✓
    </span>
  );
}

function ActionLink({
  href,
  children,
  featured = false,
}: {
  href: string;
  children: string;
  featured?: boolean;
}) {
  const className = featured
    ? "om-btn-primary h-[56px] w-full rounded-[16px] px-6 text-[16px]"
    : "om-btn-secondary h-[56px] w-full rounded-[16px] px-6 text-[16px]";

  if (/^https?:\/\//.test(href)) {
    return (
      <a href={href} className={className}>
        {children}
        <span aria-hidden>→</span>
      </a>
    );
  }

  return (
    <Link href={href} className={className}>
      {children}
      <span aria-hidden>→</span>
    </Link>
  );
}

export function LandingPricingSection({
  growthPriceDescription,
  growthPriceLabel,
  growthPriceTaxNote,
  locale,
  primaryHref,
}: {
  growthPriceDescription: string;
  growthPriceLabel: string;
  growthPriceTaxNote: string;
  locale: SupportedLocale;
  primaryHref: string;
}) {
  const translatedPlans = localizeStaticUiValue(MAIL_PLAN_CARDS, locale).map((plan) =>
    plan.key === "growth"
      ? {
          ...plan,
          price: growthPriceLabel,
          taxNote: growthPriceTaxNote,
        }
      : plan,
  );
  const translated = <T extends readonly [string, string, string, string, string, string]>(row: T) => localizedCopy(locale, row);
  const text = <T extends readonly [string, string, string, string, string, string]>(korean: string, row: T) => locale === "ko" ? korean : translated(row);
  const comparisonRows = [
    {
      label: text("월 이용료", ["월 이용료", "Monthly price", "月费", "月額料金", "Phí hàng tháng", "Ежемесячная цена"]),
      free: text("0원", ["0원", "Free", "免费", "無料", "Miễn phí", "Бесплатно"]),
      growth: `${growthPriceLabel}${text(" / 사용자", [" / 사용자", " / user", " / 用户", " / ユーザー", " / người dùng", " / пользователь"])}`,
      team: text("준비 중", ["준비 중", "Coming soon", "即将推出", "準備中", "Sắp ra mắt", "Скоро"]),
    },
    {
      label: text("메일 계정", ["메일 계정", "Mail accounts", "邮件账号", "メールアカウント", "Tài khoản email", "Почтовые аккаунты"]),
      free: text("대표 계정 1개", ["대표 계정 1개", "1 primary account", "1 个主账号", "代表アカウント1件", "1 tài khoản chính", "1 основной аккаунт"]),
      growth: text("직원 계정 추가 · 인원별 과금", ["직원 계정 추가 · 인원별 과금", "Add staff · priced per user", "添加员工账号 · 按用户计费", "スタッフ追加 · ユーザー課金", "Thêm nhân viên · tính phí theo người", "Сотрудники · оплата за пользователя"]),
      team: text("팀 단위 계정 관리", ["팀 단위 계정 관리", "Team account management", "团队账号管理", "チーム単位のアカウント管理", "Quản lý tài khoản theo nhóm", "Управление аккаунтами команды"]),
    },
    {
      label: text("메일 발송", ["메일 발송", "Sending", "邮件发送", "メール送信", "Gửi email", "Отправка писем"]),
      free: text("하루 30건", ["하루 30건", "30 per day", "每天 30 封", "1日30件", "30 email/ngày", "30 в день"]),
      growth: text("무제한 · 오발송 방지 적용", ["무제한 · 오발송 방지 적용", "Unlimited · anti-abuse protection", "无限 · 含防滥用保护", "無制限 · 誤送信防止あり", "Không giới hạn · có chống lạm dụng", "Без ограничений · защита от злоупотреблений"]),
      team: text("무제한 · 운영 정책 적용", ["무제한 · 운영 정책 적용", "Unlimited · policy controls", "无限 · 支持运营策略", "無制限 · 運用ポリシー対応", "Không giới hạn · chính sách vận hành", "Без ограничений · политики управления"]),
    },
    {
      label: text("메일함 용량", ["메일함 용량", "Mailbox storage", "邮箱容量", "メールボックス容量", "Dung lượng hộp thư", "Объем почты"]),
      free: text("사용자당 2GB", ["사용자당 2GB", "2GB per user", "每用户 2GB", "1ユーザー2GB", "2GB/người dùng", "2 ГБ на пользователя"]),
      growth: text("사용자당 10GB", ["사용자당 10GB", "10GB per user", "每用户 10GB", "1ユーザー10GB", "10GB/người dùng", "10 ГБ на пользователя"]),
      team: text("무제한 · 공정 사용 정책", ["무제한 · 공정 사용 정책", "Unlimited · fair use policy", "无限 · 公平使用政策", "無制限 · 公正利用ポリシー", "Không giới hạn · chính sách sử dụng hợp lý", "Без ограничений · политика добросовестного использования"]),
    },
    {
      label: text("파일서랍", ["파일서랍", "File drawer", "文件柜", "ファイル保管庫", "Kho tệp", "Файловое хранилище"]),
      free: text("사용자당 2GB", ["사용자당 2GB", "2GB per user", "每用户 2GB", "1ユーザー2GB", "2GB/người dùng", "2 ГБ на пользователя"]),
      growth: text("사용자당 10GB", ["사용자당 10GB", "10GB per user", "每用户 10GB", "1ユーザー10GB", "10GB/người dùng", "10 ГБ на пользователя"]),
      team: text("사용자당 100GB", ["사용자당 100GB", "100GB per user", "每用户 100GB", "1ユーザー100GB", "100GB/người dùng", "100 ГБ на пользователя"]),
    },
    {
      label: text("일반 첨부·수신 메일", ["일반 첨부·수신 메일", "Regular attachments · incoming mail", "普通附件·收件", "通常の添付・受信メール", "Tệp đính kèm thường · thư đến", "Обычные вложения · входящие письма"]),
      free: text("메일당 최대 25MB", ["메일당 최대 25MB", "Up to 25MB per message", "每封最多 25MB", "1通あたり最大25MB", "Tối đa 25MB mỗi thư", "До 25 МБ на письмо"]),
      growth: text("메일당 최대 40MB", ["메일당 최대 40MB", "Up to 40MB per message", "每封最多 40MB", "1通あたり最大40MB", "Tối đa 40MB mỗi thư", "До 40 МБ на письмо"]),
      team: text("성장 플랜 기준", ["성장 플랜 기준", "Growth plan limits", "按成长方案上限", "成長プランの上限", "Theo giới hạn gói Tăng trưởng", "Лимиты тарифа «Рост»"]),
    },
    {
      label: text("대용량 첨부", ["대용량 첨부", "Large attachments", "大附件", "大容量添付", "Tệp đính kèm lớn", "Крупные вложения"]),
      free: "—",
      growth: text("파일당 250MB · 30일 · 100회", ["파일당 250MB · 30일 · 100회", "250MB/file · 30 days · 100 downloads", "每文件 250MB · 30 天 · 100 次下载", "1ファイル250MB・30日・100回", "250MB/tệp · 30 ngày · 100 lượt tải", "250 МБ/файл · 30 дней · 100 скачиваний"]),
      team: text("성장 플랜 기준", ["성장 플랜 기준", "Growth plan limits", "按成长方案上限", "成長プランの上限", "Theo giới hạn gói Tăng trưởng", "Лимиты тарифа «Рост»"]),
    },
    {
      label: text("AI 어시스트 브릿지", ["AI 어시스트 브릿지", "AI Assist Bridge", "AI 助手桥接", "AIアシストブリッジ", "Cầu nối trợ lý AI", "AI Assist Bridge"]),
      free: "—",
      growth: text("지원", ["지원", "Included", "支持", "対応", "Có", "Включено"]),
      team: text("지원", ["지원", "Included", "支持", "対応", "Có", "Включено"]),
    },
    {
      label: text("자동발송 예약", ["자동발송 예약", "Scheduled auto-send", "定时自动发送", "自動送信予約", "Lên lịch gửi tự động", "Автоматическая отправка"]),
      free: "—",
      growth: text("지원", ["지원", "Included", "支持", "対応", "Có", "Включено"]),
      team: text("지원", ["지원", "Included", "支持", "対応", "Có", "Включено"]),
    },
    {
      label: text("외부 메일 앱", ["외부 메일 앱", "External mail apps", "外部邮件应用", "外部メールアプリ", "Ứng dụng thư ngoài", "Почтовые приложения"]),
      free: "—",
      growth: text("IMAP · POP3 · SMTP", ["IMAP · POP3 · SMTP", "IMAP · POP3 · SMTP", "IMAP · POP3 · SMTP", "IMAP・POP3・SMTP", "IMAP · POP3 · SMTP", "IMAP · POP3 · SMTP"]),
      team: text("IMAP · POP3 · SMTP", ["IMAP · POP3 · SMTP", "IMAP · POP3 · SMTP", "IMAP · POP3 · SMTP", "IMAP・POP3・SMTP", "IMAP · POP3 · SMTP", "IMAP · POP3 · SMTP"]),
    },
    {
      label: text("서비스 발송 API", ["서비스 발송 API", "Sending API", "发送 API", "送信API", "API gửi email", "API отправки"]),
      free: "—",
      growth: text("지원 · 활성 키 최대 10개", ["지원 · 활성 키 최대 10개", "Included · up to 10 active keys", "支持 · 最多 10 个有效密钥", "対応 · 有効キー最大10個", "Có · tối đa 10 khóa hoạt động", "Включено · до 10 активных ключей"]),
      team: text("지원 · 조직 운영 고도화 예정", ["지원 · 조직 운영 고도화 예정", "Included · advanced organization controls planned", "支持 · 计划提供高级组织控制", "対応 · 組織向け高度機能を予定", "Có · dự kiến quản trị tổ chức nâng cao", "Включено · расширенное управление организацией"]),
    },
    {
      label: text("권한과 공유 주소", ["권한과 공유 주소", "Roles and shared addresses", "权限和共享地址", "権限と共有アドレス", "Quyền và địa chỉ dùng chung", "Роли и общие адреса"]),
      free: "—",
      growth: text("대표 관리자 중심", ["대표 관리자 중심", "Primary admin controls", "主管理员控制", "代表管理者が管理", "Quản trị viên chính quản lý", "Управление основным администратором"]),
      team: text("역할 분리 · 팀 메일함", ["역할 분리 · 팀 메일함", "Role separation · team inboxes", "角色分离 · 团队邮箱", "権限分離 · チーム受信箱", "Phân quyền · hộp thư nhóm", "Разделение ролей · общие ящики"]),
    },
  ];

  return (
    <section
      id="pricing"
      className="relative mt-12 px-4 py-10 sm:px-8 sm:py-12 lg:px-10 lg:py-14"
    >
      <div className="pointer-events-none absolute -left-[180px] top-[4%] h-[420px] w-[420px] rounded-full bg-[#8db6ff]/18 blur-[140px]" />
      <div className="pointer-events-none absolute -right-[160px] bottom-[2%] h-[360px] w-[360px] rounded-full bg-[#f8c89b]/16 blur-[140px]" />

      <div className="relative z-10 text-center">
        <h2 className="text-balance text-[26px] font-semibold leading-[1.18] tracking-[-0.06em] text-[#111a33] sm:text-[34px] lg:text-[46px]">
          {text("메일 비용은 줄이고 사업에 더 집중하세요", homeCopy.priceTitle)}
        </h2>
        <p className="mx-auto mt-4 max-w-[760px] text-[15px] leading-7 text-[#5f6e88] sm:mt-5 sm:text-[17px] sm:leading-7">
          {growthPriceDescription}
        </p>
      </div>

      <div className="relative z-10 mx-auto mt-10 grid max-w-[1060px] gap-5 sm:mt-12 sm:gap-6 lg:grid-cols-3">
        {translatedPlans.map((plan) => (
          <article
            key={plan.key}
            className={`relative flex h-full flex-col rounded-[24px] border bg-white/96 p-6 shadow-[0_20px_44px_rgba(15,23,42,0.05)] sm:rounded-[28px] sm:p-7 ${
              plan.featured
                ? "border-[#9dc0ff] shadow-[0_24px_54px_rgba(47,109,246,0.16)]"
                : "border-[#e6edf8]"
            }`}
          >
            {plan.featured ? (
              <div className="absolute left-1/2 top-0 -translate-x-1/2 -translate-y-1/2 rounded-full bg-[linear-gradient(135deg,#ff8a1d,#ff6a00)] px-5 py-2 text-[12px] font-bold tracking-[-0.02em] text-white shadow-[0_12px_28px_rgba(255,122,24,0.28)]">
                {text("가장 많이 선택", ["가장 많이 선택", "Most popular", "最受欢迎", "一番人気", "Phổ biến nhất", "Самый популярный"])}
              </div>
            ) : null}

            <p
              className={`text-[11px] font-bold uppercase tracking-[0.1em] ${
                plan.featured ? "text-[#2f6df6]" : "text-[#8c9ab1]"
              }`}
            >
              {plan.label}
            </p>
            <h3 className="mt-2 text-[26px] font-extrabold tracking-[-0.05em] text-[#061832] sm:text-[28px]">
              {plan.title}
            </h3>
            <p className="mt-2 text-[14px] font-medium leading-6 text-[#6c7a93]">
              {plan.description}
            </p>

            <div className="mt-8 min-h-[104px]">
              <div className="flex items-end gap-2">
                <span
                  className={`leading-none font-black tracking-[-0.08em] ${
                    plan.featured
                      ? "text-[48px] text-[#2f6df6] sm:text-[54px]"
                      : "text-[42px] text-[#061832] sm:text-[46px]"
                  }`}
                >
                  {plan.price}
                </span>
                {plan.priceSuffix ? (
                  <span className="mb-1 text-[14px] font-bold text-[#98a4b9] sm:mb-1.5 sm:text-[16px]">
                    {plan.priceSuffix}
                  </span>
                ) : null}
              </div>
              {plan.taxNote ? (
                <p className="mt-1 text-[11px] font-medium text-[#98a4b9]">{plan.taxNote}</p>
              ) : null}
              <p className="mt-3 text-[14px] font-medium text-[#98a4b9]">
                {plan.note}
              </p>
              {plan.featured ? (
                <p className="mt-2 text-[12px] leading-5 text-[#6f7d95]">
                  {text("월·연 구독 시 결제일 기준 자동 갱신되는 정기결제 상품입니다.", ["월·연 구독 시 결제일 기준 자동 갱신되는 정기결제 상품입니다.", "Monthly and annual subscriptions renew automatically on the billing date.", "月付和年付订阅将在账单日自动续订。", "月額・年額プランは決済日に自動更新されます。", "Gói tháng và năm tự động gia hạn vào ngày thanh toán.", "Месячная и годовая подписка автоматически продлевается в дату оплаты."])}
                </p>
              ) : null}
            </div>

            <div className="my-6 h-px w-full bg-[#edf2fb]" />

            <ul className="flex flex-1 flex-col gap-3">
              {plan.features.map((feature) => (
                <li
                  key={feature}
                  className="flex items-start gap-3 text-[15px] leading-[1.55] text-[#465468]"
                >
                  <CheckBullet />
                  <span>{feature}</span>
                </li>
              ))}
            </ul>

            {plan.cta ? (
              <div className="mt-8">
                <ActionLink href={primaryHref} featured={plan.featured}>
                  {plan.cta}
                </ActionLink>
              </div>
            ) : null}
          </article>
        ))}
      </div>

      <div className="relative z-10 mx-auto mt-8 max-w-[1060px] overflow-hidden rounded-[24px] border border-[#e2eaf7] bg-white/96 shadow-[0_20px_44px_rgba(15,23,42,0.05)] sm:mt-10 sm:rounded-[28px]">
        <div className="border-b border-[#e8eef8] px-5 py-5 sm:px-7 sm:py-6">
          <p className="text-[11px] font-bold uppercase tracking-[0.1em] text-[#2f6df6]">
            {text("플랜 비교", ["플랜 비교", "Plan comparison", "套餐比较", "プラン比較", "So sánh gói", "Сравнение тарифов"])}
          </p>
          <h3 className="mt-2 text-[22px] font-extrabold tracking-[-0.045em] text-[#111a33] sm:text-[26px]">
            {text("필요한 기능과 용량을 한눈에 비교하세요", ["필요한 기능과 용량을 한눈에 비교하세요", "Compare features and storage at a glance", "一目了然地比较功能和容量", "機能と容量をひと目で比較", "So sánh nhanh tính năng và dung lượng", "Сравните функции и объем хранилища"])}
          </h3>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full min-w-[820px] border-collapse text-left">
            <thead>
              <tr className="bg-[#f7f9fd] text-[13px] font-bold text-[#243754]">
                <th className="w-[25%] px-5 py-4 sm:px-7">{text("비교 항목", ["비교 항목", "Feature", "比较项目", "比較項目", "Hạng mục", "Функция"])}</th>
                <th className="w-[25%] border-l border-[#e3eaf5] px-5 py-4">{text("무료", ["무료", "Free", "免费", "無料", "Miễn phí", "Бесплатный"])}</th>
                <th className="w-[25%] border-l border-[#dbe7fb] bg-[#edf4ff] px-5 py-4 text-[#2f6df6]">{text("성장", ["성장", "Growth", "成长", "成長", "Tăng trưởng", "Growth"])}</th>
                <th className="w-[25%] border-l border-[#e3eaf5] px-5 py-4">
                  <span>{text("팀", ["팀", "Team", "团队", "チーム", "Nhóm", "Команда"])}</span>
                  <span className="ml-2 rounded-full bg-[#e9eef7] px-2 py-1 text-[10px] font-bold text-[#75849c]">
                    {text("제공 예정", ["제공 예정", "Planned", "即将推出", "提供予定", "Sắp có", "Планируется"])}
                  </span>
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#edf2f8] text-[13px] leading-6 text-[#53647e] sm:text-[14px]">
              {comparisonRows.map((row) => (
                <tr key={row.label} className="transition-colors hover:bg-[#fbfcff]">
                  <th className="px-5 py-3.5 font-semibold text-[#243754] sm:px-7">{row.label}</th>
                  <td className="border-l border-[#e7edf6] px-5 py-3.5">{row.free}</td>
                  <td className="border-l border-[#dfe9f9] bg-[#f8fbff] px-5 py-3.5 font-semibold text-[#315ea9]">{row.growth}</td>
                  <td className="border-l border-[#e7edf6] px-5 py-3.5">{row.team}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

      </div>

      <div className="relative z-10 mx-auto mt-10 max-w-[980px] text-center text-[12px] leading-6 text-[#96a2b6] sm:mt-12 sm:text-[14px] sm:leading-7">
        {text("무료 플랜은 대표자 1명 기준 1계정 제공입니다.", homeCopy.free)}
        <br />
        {growthPriceDescription}
        <br />
        {text("월간·연간 구독권은 해지 시점 기준 미사용 잔여일에 대해 일할 계산 환불이 적용됩니다.", seoGenericCopy.operations[1])}
        <br />
        {text("전액 청약철회는 결제 후 7일 이내이며 메일 송수신 이력이 전혀 없을 때만 가능합니다.", seoGenericCopy.operations[2])}
        <br />
        {text("도메인 연결, DNS 안내, 대표 메일 생성 흐름은 가입 후 메일 설정 화면에서 바로 이어집니다.", homeCopy.stepsTitle)}
      </div>
    </section>
  );
}
