import type { ReactNode } from "react";
import type { Metadata } from "next";
import { headers } from "next/headers";
import Link from "next/link";
import {
  copy as localizedCopy,
  homeCopy,
  seoGenericCopy,
  shared,
  type PublicRow,
} from "@/components/localized-public-pages";
import { LandingPricingSection } from "@/components/landing-pricing-section";
import { LandingStorySections } from "@/components/landing-story-sections";
import {
  PublicLanguageMenu,
  PublicLocaleSuggestion,
} from "@/components/public-language-controls";
import { SiteFooter } from "@/components/site-footer";
import { ServerStaticUiLocalizer } from "@/components/server-static-ui-localizer";
import { WhyOfficialCarousel } from "@/components/why-official-carousel";
import {
  getMailAuthUrlForCurrentRequest,
  getMailEntryUrlForCurrentRequest,
  getSessionUser,
} from "@/lib/auth";
import { getMailAbsoluteUrl, getPublicSiteAbsoluteUrl } from "@/lib/mail-urls";
import {
  OFFICIAL_MAIL_ALTERNATE_SITE_NAMES,
  OFFICIAL_MAIL_SAME_AS,
  OFFICIAL_MAIL_SITE_NAME,
} from "@/lib/official-mail-brand";
import { buildPublicPageMetadata } from "@/lib/public-seo-i18n";
import { getPublicRepresentativeAccountCount } from "@/lib/public-service-stats";
import {
  getLocaleOption,
  resolveLocaleFromCountry,
  type SupportedLocale,
} from "@/lib/i18n-config";
import { resolveRequestLocale } from "@/lib/i18n-server";
import { getLocalizedPublicPath } from "@/lib/i18n-urls";
import { getRequestCountryCode } from "@/lib/request-country";
import {
  resolveMailBillingProvider,
  resolvePolarLocalizedPrice,
} from "@/lib/billing-region-server";
import { formatPolarPrice } from "@/lib/billing-region";
import { MAIL_GROWTH_PLAN_NET_PRICE_PER_MEMBER } from "@/lib/pricing";

const navItems: ReadonlyArray<{ href: string; label: PublicRow }> = [
  { href: "#about", label: ["서비스 소개", "Overview", "服务介绍", "サービス紹介", "Giới thiệu", "О сервисе"] },
  { href: "#features", label: ["무료 혜택", "Free benefits", "免费权益", "無料特典", "Quyền lợi miễn phí", "Бесплатно"] },
  { href: "#domain-connect", label: ["도메인 연결", "Domain setup", "域名连接", "ドメイン接続", "Kết nối tên miền", "Подключение домена"] },
  { href: "#mail-flow", label: ["운영 흐름", "How it works", "使用流程", "利用の流れ", "Quy trình", "Как это работает"] },
  { href: "#pricing", label: ["요금제", "Pricing", "价格", "料金", "Bảng giá", "Тарифы"] },
];

export async function generateMetadata(): Promise<Metadata> {
  return buildPublicPageMetadata({
    locale: await resolveRequestLocale(),
    page: "home",
    pathname: "/",
  });
}

const heroPerks = [
  "대표 메일 1개 무료",
  "1분 만에 가입",
  "신용카드 등록 없음",
];

const featureRail = [
  {
    title: "대표 메일 1개 무료",
    description: "대표님을 위한\n메일 계정 1개 무료 제공",
    icon: "mail",
  },
  {
    title: "우리 도메인 그대로",
    description: "이미 보유한 도메인으로\n바로 사용 가능",
    icon: "domain",
  },
  {
    title: "간편한 설정",
    description: "복잡한 IT 지식 없이\n쉽고 빠르게 세팅",
    icon: "setup",
  },
  {
    title: "안정적인 보안",
    description: "스팸 차단, 보안 필터로\n안전하게 보호",
    icon: "shield",
  },
];

const whyItems = [
  {
    title: "비용 걱정 없이 시작",
    description: "사업 초기 고정비를 줄이고,\n필요한 곳에 더 집중하세요.",
    icon: "briefcase",
  },
  {
    title: "전문적인 비즈니스 이미지",
    description: "우리 도메인의 메일 주소로\n신뢰도를 높이세요.",
    icon: "rocket",
  },
  {
    title: "성장해도 유연하게",
    description: "필요할 때 언제든\n추가 계정 및 기능 확장 가능",
    icon: "badge",
  },
] as const;

const stats = [
  { value: "0원", label: "대표 메일 1개 무료 시작" },
  { value: "3,900원", label: "성장 플랜 팀 인원 1명 월 요금 · VAT 별도" },
  { value: "3단계", label: "도메인 연결부터 발신 인증까지" },
  { value: "AI", label: "요약·답장 릴레이 자동화" },
];

function getLandingPriceCopy(
  locale: SupportedLocale,
  growthPriceLabel: string,
  domesticBilling: boolean,
) {
  const translated = (row: PublicRow) => localizedCopy(locale, row);

  if (domesticBilling) {
    return {
      banner: translated([
        `성장 플랜은 팀 인원당 월 ${growthPriceLabel}(VAT 별도)`,
        `Growth plan ${growthPriceLabel} per member/month (VAT excluded)`,
        `成长方案每位成员每月 ${growthPriceLabel}（不含增值税）`,
        `成長プランは1人あたり月${growthPriceLabel}（VAT別）`,
        `Gói Tăng trưởng ${growthPriceLabel}/thành viên/tháng (chưa VAT)`,
        `Тариф «Рост» ${growthPriceLabel} за участника в месяц (без НДС)`,
      ]),
      description: translated([
        `무료 플랜은 대표 메일 1개를 제공합니다. 성장 플랜은 팀 인원 1명당 월 ${growthPriceLabel}이며 VAT는 별도입니다.`,
        `The Free plan includes one primary mailbox. The Growth plan is ${growthPriceLabel} per team member per month, excluding VAT.`,
        `免费方案包含一个主邮箱。成长方案每位团队成员每月 ${growthPriceLabel}，另计增值税。`,
        `無料プランは代表メール1件を提供します。成長プランはチーム1名あたり月額${growthPriceLabel}（VAT別）です。`,
        `Gói Miễn phí gồm một hộp thư chính. Gói Tăng trưởng là ${growthPriceLabel} mỗi thành viên mỗi tháng, chưa gồm VAT.`,
        `Бесплатный тариф включает один основной ящик. Тариф «Рост» стоит ${growthPriceLabel} за участника в месяц без НДС.`,
      ]),
      statLabel: translated([
        "성장 플랜 팀 인원 1명 월 요금 · VAT 별도",
        "Growth plan per member/month · VAT excluded",
        "成长方案每位成员月费 · 不含增值税",
        "成長プラン1人あたり月額・VAT別",
        "Phí tháng mỗi thành viên · chưa VAT",
        "Цена за участника в месяц · без НДС",
      ]),
      taxNote: translated([
        "(VAT 별도)",
        "(VAT excluded)",
        "（不含增值税）",
        "（VAT別）",
        "(chưa VAT)",
        "(без НДС)",
      ]),
    };
  }

  return {
    banner: translated([
      `성장 플랜은 팀 인원당 월 ${growthPriceLabel}`,
      `Growth plan ${growthPriceLabel} per member/month`,
      `成长方案每位成员每月 ${growthPriceLabel}`,
      `成長プランは1人あたり月${growthPriceLabel}`,
      `Gói Tăng trưởng ${growthPriceLabel}/thành viên/tháng`,
      `Тариф «Рост» ${growthPriceLabel} за участника в месяц`,
    ]),
    description: translated([
      `무료 플랜은 대표 메일 1개를 제공합니다. 성장 플랜은 팀 인원 1명당 월 ${growthPriceLabel}입니다. 세금은 결제 단계에서 계산될 수 있습니다.`,
      `The Free plan includes one primary mailbox. The Growth plan is ${growthPriceLabel} per team member per month. Taxes may be calculated at checkout.`,
      `免费方案包含一个主邮箱。成长方案每位团队成员每月 ${growthPriceLabel}。税费可能在结账时计算。`,
      `無料プランは代表メール1件を提供します。成長プランはチーム1名あたり月額${growthPriceLabel}です。税金は決済時に計算される場合があります。`,
      `Gói Miễn phí gồm một hộp thư chính. Gói Tăng trưởng là ${growthPriceLabel} mỗi thành viên mỗi tháng. Thuế có thể được tính khi thanh toán.`,
      `Бесплатный тариф включает один основной ящик. Тариф «Рост» стоит ${growthPriceLabel} за участника в месяц. Налоги могут быть рассчитаны при оплате.`,
    ]),
    statLabel: translated([
      "성장 플랜 팀 인원 1명 월 요금",
      "Growth plan per member/month",
      "成长方案每位成员月费",
      "成長プラン1人あたり月額",
      "Phí tháng mỗi thành viên",
      "Цена за участника в месяц",
    ]),
    taxNote: translated([
      "(세금은 결제 단계에서 계산)",
      "(Taxes calculated at checkout)",
      "（税费在结账时计算）",
      "（税金は決済時に計算）",
      "(Thuế được tính khi thanh toán)",
      "(Налоги рассчитываются при оплате)",
    ]),
  };
}

const businessEmailResources = [
  {
    href: "/business-email",
    label: "서비스 안내",
    title: "무료 기업메일로 회사 이메일 만들기",
    description:
      "대표 메일 1개 무료 범위와 도메인 연결, 팀 확장 방식을 한 번에 확인하세요.",
  },
  {
    href: "/blog/company-email-address-guide",
    label: "시작 가이드",
    title: "회사 이메일 주소와 대표 메일 정하는 방법",
    description:
      "contact, support, admin 등 업무에 맞는 주소를 정하고 개통하는 순서를 확인하세요.",
  },
  {
    href: "/guide#domain",
    label: "DNS 연결",
    title: "도메인 메일 MX·SPF·DKIM 설정 가이드",
    description:
      "도메인 구입처에서 입력할 레코드와 연결 상태를 확인하는 과정을 안내합니다.",
  },
  {
    href: "/domain-mail-check",
    label: "무료 진단",
    title: "회사 도메인 메일 연결 상태 확인",
    description:
      "MX, SPF, DKIM, DMARC 공개 값을 조회해 수신·발신 문제를 점검하세요.",
  },
] as const;

const successStories = [
  {
    category: "온라인 스토어",
    title: "개인메일로 흩어지던 주문·제휴 문의를 공식 도메인 메일로 통합",
    description:
      "대표 메일을 먼저 열고, CS 담당자와 운영 담당자를 성장플랜 멤버로 확장해 고객 응대 경로를 한 곳으로 정리했습니다.",
    result: "문의 응대 경로 통합",
  },
  {
    category: "신규 법인",
    title: "홈페이지 오픈과 동시에 ceo@, contact@ 주소를 맞춰 브랜드 신뢰도 확보",
    description:
      "DNS 연결, SPF·DKIM 발신 인증, 대표 메일 세팅까지 한 흐름에서 완료해 거래처 첫 응대부터 공식 주소를 사용했습니다.",
    result: "도메인 기반 첫인상 정비",
  },
  {
    category: "소규모 팀",
    title: "대표가 모든 메일을 직접 보지 않아도 AI 요약과 릴레이로 핵심만 확인",
    description:
      "중요한 수신 메일은 AI 요약 후 보조 메일로 릴레이하고, 답장은 원 발신자에게 연결되도록 운영 부담을 줄였습니다.",
    result: "반복 확인 시간 절감",
  },
];

const customerReviews = [
  {
    role: "온라인 스토어 이*희 대표",
    quote:
      "처음엔 광고인 줄 알고 끊으려 했어요. 그런데 고객 문의를 아직 개인 메일로 받고 있다는 말에 바로 걸렸습니다.",
    point: "개인 메일에서 대표 메일로 전환",
  },
  {
    role: "신규 법인 김*우 대표",
    quote:
      "법인 만들고 명함까지 찍었는데 메일만 네이버 주소였습니다. 첫 거래처에 견적서를 보내야 해서 그날 바로 바꿨습니다.",
    point: "첫 거래처 응대 정리",
  },
  {
    role: "소규모 제작사 박*진 대표",
    quote:
      "촬영 중엔 메일함을 못 봅니다. 요약만 먼저 오니까 급한 견적 문의만 골라서 봅니다.",
    point: "현장 업무 중 메일 확인",
  },
  {
    role: "브랜드 쇼핑몰 최*아 대표",
    quote:
      "처음엔 저 혼자라 대표 메일 하나면 됐습니다. CS 담당자를 뽑고 나서도 기존 주소를 버리지 않고 멤버만 붙이면 돼서 정리가 쉬웠어요.",
    point: "CS 담당자 추가 운영",
  },
  {
    role: "마케팅 대행사 정*훈 대표",
    quote:
      "제안서 보낼 때 개인 사업자냐는 말을 몇 번 들었습니다. 주소 바꾼 뒤엔 그 설명부터 안 해도 됩니다.",
    point: "제안 단계 신뢰도 보완",
  },
  {
    role: "인테리어 스튜디오 한*정 대표",
    quote:
      "도면 찾느라 20분씩 버린 적이 있습니다. 제 개인 메일, 직원 메일, 카톡까지 섞여 있었거든요. 지금은 견적 문의 주소를 하나로 고정해두고 필요한 사람에게 전달합니다.",
    point: "도면·견적 메일 통합",
  },
  {
    role: "교육 서비스 윤*서 대표",
    quote:
      "아침마다 메일함부터 뒤졌습니다.",
    point: "수강 문의 우선순위 확인",
  },
  {
    role: "B2B 솔루션 강*민 대표",
    quote:
      "기업 담당자에게 보낸 메일이 스팸함으로 갔다고 하더라고요. 그때 SPF, DKIM 같은 걸 처음 제대로 신경 썼습니다. 설정 상태가 화면에 보여서 덜 답답했습니다.",
    point: "스팸함 이슈 대응",
  },
  {
    role: "콘텐츠 스튜디오 서*연 대표",
    quote:
      "인스타 DM이랑 개인 메일을 오가던 외주 문의를 contact 주소 하나로 모았습니다.",
    point: "외주 문의 접점 정리",
  },
  {
    role: "법률 사무소 문*호 대표",
    quote:
      "상담 일정 안내를 개인 메일로 보내는 게 늘 마음에 걸렸습니다. 사무소 도메인 주소로 바꾸니 고객에게 보내는 문장도 괜히 더 정돈해서 쓰게 됩니다.",
    point: "상담 안내 메일 정비",
  },
  {
    role: "병원 컨설팅 오*준 대표",
    quote:
      "큰 그룹웨어는 필요 없었습니다.",
    point: "작은 조직 기준 운영",
  },
  {
    role: "프랜차이즈 본사 노*현 대표",
    quote:
      "가맹 문의를 직원 개인 주소로 받다가 퇴사 후 기록 찾느라 고생했습니다. 지금은 본사 주소로 받고 담당자만 바꿉니다. 이게 맞는 구조였어요.",
    point: "담당자 변경 리스크 감소",
  },
  {
    role: "물류 스타트업 배*준 대표",
    quote:
      "운송 일정 변경 메일은 한 번 놓치면 바로 꼬입니다. 공식 주소로 모아두니 누가 봤는지 설명할 일이 줄었습니다.",
    point: "운송 일정 메일 정리",
  },
  {
    role: "패션 브랜드 민*경 대표",
    quote:
      "협찬 메일을 한 번 놓쳤습니다.",
    point: "협찬·CS 문의 분리",
  },
  {
    role: "개발 에이전시 신*재 대표",
    quote:
      "외주 개발 문의를 Gmail로 받았더니 계약 직전에 회사 메일이 없냐고 묻더라고요. 처음엔 별것 아닌 줄 알았는데, 상대 입장에서는 확인하고 싶은 포인트였던 것 같습니다.",
    point: "계약 전 신뢰 보완",
  },
  {
    role: "제조 스타트업 조*원 대표",
    quote:
      "발주서가 제 개인 메일로만 오던 게 문제였습니다. 제가 없으면 공장 쪽에서 내용을 못 봤거든요.",
    point: "발주서 공유 속도 개선",
  },
  {
    role: "뷰티샵 김*라 대표",
    quote:
      "예약은 카톡이면 충분하다고 생각했습니다. 그런데 브랜드 제휴 제안이 들어오면서부터는 메일이 필요하더라고요. 업체 응대용 주소를 따로 둔 뒤로 훨씬 깔끔합니다.",
    point: "예약 외 제휴 응대",
  },
  {
    role: "부동산 중개법인 이*석 대표",
    quote:
      "개인 메일 주소가 보이는 게 싫었습니다.",
    point: "매물 자료 발송 정리",
  },
  {
    role: "행사 기획사 장*은 대표",
    quote:
      "행사 견적 문의는 놓치면 끝입니다. 요약 알림 덕분에 이동 중에도 급한 건 바로 잡습니다.",
    point: "견적 문의 대응 속도",
  },
  {
    role: "회계 사무소 류*태 대표",
    quote:
      "세무 자료 요청을 개인 메일로 보내는 게 계속 걸렸습니다. 사무소 도메인 주소로 바꾸고 나니 고객에게 '이쪽으로 보내주세요'라고 말하기가 훨씬 자연스러워졌습니다.",
    point: "자료 요청 메일 공식화",
  },
  {
    role: "커머스 셀러 임*영 대표",
    quote:
      "나중에 해도 된다고 생각했는데 고객 문의가 늘자 개인 메일로는 바로 한계가 왔습니다.",
    point: "초기 사업자 메일 전환",
  },
  {
    role: "디자인 스튜디오 홍*빈 대표",
    quote:
      "포트폴리오는 신경 써서 만들었는데 정작 제안 메일 주소는 예전 개인 계정이었습니다. 주소 하나 바꿨을 뿐인데 스튜디오가 정리돼 보인다는 말을 들었습니다.",
    point: "제안서 첫인상 개선",
  },
  {
    role: "IT 컨설팅 백*수 대표",
    quote:
      "미팅 중엔 제목만 보고 판단하기 어렵습니다. 요약이 오면 지금 답할지 나중에 볼지 바로 갈립니다.",
    point: "미팅 중 중요도 판단",
  },
  {
    role: "식품 브랜드 유*나 대표",
    quote:
      "납품 문의와 고객 불만 메일이 섞이면 하루가 복잡해집니다. 주소를 나눠두니 직원에게 넘길 때 설명이 줄었습니다.",
    point: "납품·고객 문의 분리",
  },
  {
    role: "채용 대행사 송*현 대표",
    quote:
      "지원자 메일이 담당자 개인 계정에 남아 있으면 인수인계 때마다 일이 생깁니다. 회사 메일로 받으니 기록이 사라지지 않아서 좋습니다.",
    point: "채용 기록 인수인계",
  },
  {
    role: "건축 사무소 안*재 대표",
    quote:
      "현장 사진, 계약서, 문의 메일이 전부 흩어져 있었습니다. 대표 메일로 받고 담당자에게 넘기는 식으로 바꾸니 어디서 찾아야 할지부터 명확해졌습니다.",
    point: "현장·계약 자료 정리",
  },
  {
    role: "온라인 강의 박*영 대표",
    quote:
      "강의 오픈 날에는 같은 질문이 수십 개씩 옵니다. 전체 메일을 다 열지 않고 요약으로 먼저 흐름을 봅니다.",
    point: "강의 오픈 문의 파악",
  },
  {
    role: "렌탈 서비스 전*호 대표",
    quote:
      "휴일 AS 메일이 제일 힘들었습니다.",
    point: "AS 응대 채널 분리",
  },
  {
    role: "헬스케어 브랜드 권*지 대표",
    quote:
      "팀이 작아서 큰 시스템은 부담스러웠습니다. 대표 메일로 시작하고 운영자가 생겼을 때 계정을 붙이는 정도가 딱 맞았습니다. 처음부터 무겁게 갈 필요가 없었어요.",
    point: "작게 시작해 확장",
  },
  {
    role: "로컬 브랜드 심*호 대표",
    quote:
      "홈페이지 연락처가 개인 메일이면 아무래도 허전합니다. contact 주소 하나 만든 것만으로도 브랜드 기본이 잡힌 느낌이었습니다.",
    point: "홈페이지 연락처 정비",
  },
];

function JsonLd({ data }: { data: Record<string, unknown> }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(data) }}
    />
  );
}

function buildHomeSchemas(locale: SupportedLocale) {
  const translated = (row: PublicRow) => localizedCopy(locale, row);
  const canonicalHomeUrl = getPublicSiteAbsoluteUrl("/");
  const localizedHomeUrl = getPublicSiteAbsoluteUrl(getLocalizedPublicPath("/", locale));
  const businessEmailUrl = getPublicSiteAbsoluteUrl(getLocalizedPublicPath("/business-email", locale));
  const domainEmailUrl = getPublicSiteAbsoluteUrl(getLocalizedPublicPath("/domain-email", locale));
  const aiEmailSummaryUrl = getPublicSiteAbsoluteUrl(getLocalizedPublicPath("/ai-email-summary", locale));
  const organizationId = `${canonicalHomeUrl}#organization`;
  const websiteId = `${canonicalHomeUrl}#website`;
  const brandName = translated(shared.brand);

  const softwareSchema = {
    "@context": "https://schema.org",
    "@type": "SoftwareApplication",
    "@id": `${localizedHomeUrl}#software`,
    applicationCategory: "BusinessApplication",
    description: translated(homeCopy.lead),
    featureList: homeCopy.benefitTitles.map(translated),
    isAccessibleForFree: true,
    name: brandName,
    offers: {
      "@type": "Offer",
      description: translated(homeCopy.free),
      price: "0",
      priceCurrency: "KRW",
    },
    operatingSystem: "Web",
    provider: {
      "@id": organizationId,
    },
    subjectOf: [businessEmailUrl, domainEmailUrl, aiEmailSummaryUrl],
    url: localizedHomeUrl,
  };

  // Google supports one site name per domain, not one per locale directory.
  if (locale !== "ko") {
    return [softwareSchema];
  }

  return [
    {
      "@context": "https://schema.org",
      "@type": "Organization",
      "@id": organizationId,
      legalName: "KAVENIX",
      name: OFFICIAL_MAIL_SITE_NAME,
      description: translated(homeCopy.lead),
      logo: {
        "@type": "ImageObject",
        url: getPublicSiteAbsoluteUrl("/icon-512.png"),
        width: 512,
        height: 512,
      },
      sameAs: OFFICIAL_MAIL_SAME_AS,
      url: canonicalHomeUrl,
    },
    {
      "@context": "https://schema.org",
      "@type": "WebSite",
      "@id": websiteId,
      inLanguage: getLocaleOption(locale).htmlLang,
      name: OFFICIAL_MAIL_SITE_NAME,
      alternateName: OFFICIAL_MAIL_ALTERNATE_SITE_NAMES,
      about: [
        { "@type": "Thing", name: translated(shared.businessEmail) },
        { "@type": "Thing", name: translated(shared.domainEmail) },
        { "@type": "Thing", name: translated(homeCopy.benefitTitles[3]) },
      ],
      hasPart: businessEmailResources.map((resource, index) => ({
        "@type": "WebPage",
        name: translated(homeCopy.benefitTitles[index % homeCopy.benefitTitles.length]),
        url: getPublicSiteAbsoluteUrl(getLocalizedPublicPath(resource.href, locale)),
      })),
      publisher: {
        "@id": organizationId,
      },
      url: canonicalHomeUrl,
    },
    softwareSchema,
  ];
}

function IconBase({
  children,
  className,
}: {
  children: ReactNode;
  className?: string;
}) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
    >
      {children}
    </svg>
  );
}

function LogoMark({ locale }: { locale: SupportedLocale }) {
  return (
    <div className="flex items-center justify-center gap-2.5 text-center sm:gap-3">
      <span className="flex items-center justify-center text-[#2f6df6]">
        <IconBase className="h-[32px] w-[32px] sm:h-[40px] sm:w-[40px]">
          <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" />
        </IconBase>
      </span>
      <span className="text-[22px] font-extrabold tracking-[-0.08em] text-[#2f6df6]">
        {locale === "ko" ? "오피셜메일" : "OfficialMail"}
      </span>
    </div>
  );
}

function HeaderDownloadIcon() {
  return (
    <IconBase className="h-[19px] w-[19px] sm:h-5 sm:w-5">
      <path d="M12 4v10" />
      <path d="m8.5 10.5 3.5 3.5 3.5-3.5" />
      <path d="M5 18.5h14" />
    </IconBase>
  );
}

function CircleIcon({
  type,
  soft = false,
}: {
  type:
    | "mail"
    | "domain"
    | "setup"
    | "shield"
    | "check";
  soft?: boolean;
}) {
  const wrapperClass = soft
    ? "bg-[radial-gradient(circle_at_top,#f7fbff_0%,#e8f0ff_100%)] text-[#2f6df6]"
    : "bg-[#f3f7ff] text-[#2f6df6]";

  return (
    <div
      className={`flex h-14 w-14 items-center justify-center rounded-full border border-[#dce7ff] shadow-[0_10px_24px_rgba(47,109,246,0.08)] ${wrapperClass}`}
    >
      {type === "mail" ? (
        <IconBase className="h-6 w-6">
          <rect x="4.5" y="5.5" width="15" height="13" rx="2.2" />
          <path d="m5.4 7 6.6 5 6.6-5" />
        </IconBase>
      ) : null}
      {type === "domain" ? (
        <IconBase className="h-6 w-6">
          <circle cx="12" cy="12" r="4.8" />
          <path d="M4.5 12h15" />
          <path d="M12 4.5c2.2 2.4 3.3 4.9 3.3 7.5 0 2.6-1.1 5.1-3.3 7.5-2.2-2.4-3.3-4.9-3.3-7.5 0-2.6 1.1-5.1 3.3-7.5Z" />
        </IconBase>
      ) : null}
      {type === "setup" ? (
        <IconBase className="h-6 w-6">
          <path d="M12 4v4" />
          <path d="M12 16v4" />
          <path d="M4 12h4" />
          <path d="M16 12h4" />
          <circle cx="12" cy="12" r="3.6" />
        </IconBase>
      ) : null}
      {type === "shield" ? (
        <IconBase className="h-6 w-6">
          <path d="M12 3.8 18.5 6v5.8c0 3.8-2.6 6.6-6.5 8.4-3.9-1.8-6.5-4.6-6.5-8.4V6z" />
          <path d="m9.6 11.9 1.6 1.8 3.4-3.9" />
        </IconBase>
      ) : null}
      {type === "check" ? (
        <IconBase className="h-7 w-7">
          <circle cx="12" cy="12" r="8.2" />
          <path d="m8.8 12.2 2.1 2.2 4.2-4.4" />
        </IconBase>
      ) : null}
    </div>
  );
}

function SparkArrow() {
  return (
    <svg
      viewBox="0 0 90 120"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className="h-[102px] w-[76px] text-[#2f6df6]"
    >
      <path
        d="M44 6c10 10 13 20 11 32-2 12-9 18-15 24-8 8-10 18-3 31"
        stroke="currentColor"
        strokeWidth="3.2"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeDasharray="6 8"
      />
      <path
        d="M37 93c4 8 5 15 1 23M29 107l9 9 9-9"
        stroke="currentColor"
        strokeWidth="3.2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function HeroPreview({ locale }: { locale: SupportedLocale }) {
  const translated = (row: PublicRow) => localizedCopy(locale, row);
  const ui = (korean: string, row: PublicRow) => locale === "ko" ? korean : translated(row);
  const menuItems = ["받은 메일함", "보낸 메일함", "임시 보관함", "휴지통", "스팸 메일함"];
  const messages = [
    ["고객 문의", "브랜드 협업 관련 미팅 일정...", "10:30"],
    ["파트너사 A", "제안서 공유드립니다", "어제"],
    ["세금계산서 전송", "6월 청구서 메일입니다", "어제"],
    ["디자인 외뢰 건", "디자인 제안 드립니다", "10:22"],
    ["마케팅 제안", "신규 파트너십 제안서", "10:22"],
  ];
  const localizedMenuItems = locale === "ko" ? menuItems : [
    translated(homeCopy.benefitTitles[0]),
    translated(homeCopy.benefitTitles[1]),
    translated(homeCopy.benefitTitles[2]),
    translated(homeCopy.benefitTitles[3]),
    translated(shared.businessEmail),
  ];
  const localizedMessages = locale === "ko" ? messages : messages.map((message, index) => [
    translated(homeCopy.benefitTitles[index % homeCopy.benefitTitles.length]),
    translated(homeCopy.useBodies[index % homeCopy.useBodies.length]),
    message[2],
  ]);

  return (
    <div className="relative mx-auto flex h-[310px] w-full max-w-[390px] items-start justify-center overflow-hidden sm:h-[460px] sm:max-w-none sm:overflow-visible md:h-[580px] min-[900px]:h-[650px] lg:h-[390px] xl:h-[500px] 2xl:h-[580px]">
      <div className="relative h-[540px] w-[660px] origin-top overflow-visible -translate-x-[8px] scale-[0.45] min-[360px]:scale-[0.5] min-[390px]:-translate-x-[10px] min-[390px]:scale-[0.54] sm:translate-x-0 sm:scale-[0.82] md:scale-[1] min-[900px]:scale-[1.18] lg:scale-[0.66] xl:scale-[0.88] 2xl:scale-[1]">
        <div className="absolute inset-x-[46px] top-[60px] h-[360px] rounded-[38px] bg-[radial-gradient(circle_at_top,#dce8ff_0%,rgba(220,232,255,0)_68%)] blur-2xl" />

        <div className="absolute left-[18px] top-[96px] w-[520px] rounded-[30px] border border-white/80 bg-[linear-gradient(180deg,rgba(255,255,255,0.96),rgba(244,248,255,0.9))] shadow-[0_30px_80px_rgba(63,103,200,0.18)] backdrop-blur-xl sm:left-[40px] sm:top-[82px] sm:w-[506px] sm:rounded-[34px]">
          <div className="flex items-center gap-3 border-b border-[#edf2fc] px-5 py-4">
            <div className="flex items-center gap-2">
              <span className="h-2.5 w-2.5 rounded-full bg-[#f8c3c2]" />
              <span className="h-2.5 w-2.5 rounded-full bg-[#f5d687]" />
              <span className="h-2.5 w-2.5 rounded-full bg-[#b5ebc8]" />
            </div>
            <div className="flex h-10 flex-1 items-center gap-2 rounded-full border border-[#eef3ff] bg-white px-4 text-[12px] text-[#91a0ba]">
              <IconBase className="h-4 w-4">
                <circle cx="11" cy="11" r="5.4" />
                <path d="m19 19-3.6-3.6" />
              </IconBase>
              {ui("메일 검색", ["메일 검색", "Search mail", "搜索邮件", "メール検索", "Tìm kiếm email", "Поиск писем"])}
            </div>
          </div>

          <div className="grid grid-cols-[134px_minmax(0,1fr)]">
            <div className="border-r border-[#edf2fc] px-4 py-5">
              <div className="flex h-11 items-center justify-center rounded-[14px] bg-[#2f6df6] text-[13px] font-semibold text-white shadow-[0_12px_28px_rgba(47,109,246,0.24)]">
                {ui("메일 답변", ["메일 답변", "Reply to mail", "回复邮件", "メールに返信", "Trả lời email", "Ответить на письмо"])}
              </div>
              <div className="mt-4 space-y-2">
                {localizedMenuItems.map((item, index) => (
                  <div
                    key={item}
                    className={`flex items-center gap-2 whitespace-nowrap rounded-[12px] px-3 py-2 text-[11px] ${
                      index === 0
                        ? "bg-[#edf3ff] font-semibold text-[#2f6df6]"
                        : "text-[#7d8aa6]"
                    }`}
                  >
                    <span className="h-3 w-3 rounded-full border border-current" />
                    {item}
                  </div>
                ))}
              </div>
            </div>

            <div className="px-5 py-5">
              <div className="grid grid-cols-[54px_1fr_48px] border-b border-[#eff3fb] pb-3 text-[11px] text-[#9aa7bf]">
                <span>{ui("이름", ["이름", "Name", "名称", "名前", "Tên", "Имя"])}</span>
                <span>{ui("제목", ["제목", "Subject", "主题", "件名", "Tiêu đề", "Тема"])}</span>
                <span className="text-right">{ui("시간", ["시간", "Time", "时间", "時刻", "Thời gian", "Время"])}</span>
              </div>
              <div className="space-y-1.5 pt-3">
                {localizedMessages.map(([name, subject, time]) => (
                  <div
                    key={`${name}-${time}`}
                    className="grid grid-cols-[54px_1fr_48px] items-center rounded-[12px] px-2 py-2 transition-colors hover:bg-[#f8fbff]"
                  >
                    <div className="flex items-center gap-2">
                      <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#eef3ff] text-[11px] font-semibold text-[#2f6df6]">
                        {name.slice(0, 1)}
                      </span>
                    </div>
                    <div className="min-w-0">
                      <p className="truncate text-[12px] font-semibold text-[#10203f]">{name}</p>
                      <p className="truncate text-[11px] text-[#8695b2]">{subject}</p>
                    </div>
                    <span className="text-right text-[11px] text-[#9aa7bf]">{time === "어제" ? ui("어제", ["어제", "Yesterday", "昨天", "昨日", "Hôm qua", "Вчера"]) : time}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="absolute right-[-18px] top-[154px] flex h-[326px] w-[244px] flex-col items-center rounded-[36px] border border-white/90 bg-[linear-gradient(180deg,rgba(255,255,255,0.98),rgba(244,247,255,0.94))] px-6 py-8 shadow-[0_28px_80px_rgba(63,103,200,0.24)] sm:right-0 sm:top-[130px] sm:h-[350px] sm:w-[266px] sm:rounded-[40px] sm:px-7 sm:py-10">
          <div className="mt-1">
            <CircleIcon type="mail" />
          </div>
          <div className="mt-10 text-center sm:mt-14">
            <p className="inline-block whitespace-nowrap text-[16px] font-semibold leading-[1.28] tracking-[-0.03em] text-[#10203f]">
              {ui("contact@내도메인.com", ["contact@내도메인.com", "contact@mydomain.com", "contact@我的域名.com", "contact@mydomain.com", "contact@tenmiencuatoi.com", "contact@мойдомен.рф"])}
            </p>
            <p className="mt-3 text-[14px] text-[#9ba7be]">{translated(homeCopy.free)}</p>
          </div>
          <p className="mt-8 text-[26px] font-semibold tracking-[-0.04em] text-[#2f6df6] sm:mt-11 sm:text-[28px]">
            {ui("무료 사용 중", ["무료 사용 중", "Using free plan", "正在使用免费方案", "無料プラン利用中", "Đang dùng gói miễn phí", "Используется бесплатный тариф"])}
          </p>
          <div className="mt-5 sm:mt-6">
            <CircleIcon type="check" />
          </div>
        </div>

        <div className="absolute right-[-22px] top-[146px] flex h-[68px] w-[68px] items-center justify-center rounded-full bg-[#2f6df6] text-[22px] font-semibold tracking-[-0.04em] text-white shadow-[0_18px_44px_rgba(47,109,246,0.34)] sm:right-[-6px] sm:top-[124px] sm:h-[74px] sm:w-[74px] sm:text-[25px]">
          FREE
        </div>

        <div className="absolute right-[46px] top-[18px] flex flex-col items-center text-[#2f6df6] sm:right-[28px] sm:top-[12px]">
          <p className={`rotate-[-8deg] text-right text-[22px] font-semibold leading-[1.16] tracking-[-0.04em] sm:text-[24px] ${locale === "ko" ? "whitespace-nowrap" : "max-w-[440px]"}`}>
            {translated(homeCopy.title)}
          </p>
          <div className="mt-1 translate-x-2 sm:translate-x-3">
            <SparkArrow />
          </div>
        </div>
      </div>
    </div>
  );
}

function StatItem({ value, label }: { value: string; label: string }) {
  return (
    <div className="flex flex-col items-center gap-2 text-center">
      <p className="text-[36px] font-semibold tracking-[-0.06em] text-[#2f6df6] sm:text-[44px]">{value}</p>
      <p className="text-[15px] leading-6 text-[#5d6b86] sm:text-[17px]">{label}</p>
    </div>
  );
}

function ReviewCard({
  ariaHidden = false,
  point,
  quote,
  role,
}: {
  ariaHidden?: boolean;
  point: string;
  quote: string;
  role: string;
}) {
  return (
    <article
      aria-hidden={ariaHidden}
      className="w-[310px] shrink-0 rounded-[22px] border border-[#e1e9f8] bg-white/86 px-5 py-5 shadow-[0_18px_44px_rgba(47,109,246,0.09)] backdrop-blur-xl sm:w-[360px] sm:px-6 sm:py-6"
    >
      <div className="flex items-center justify-between gap-3">
        <div aria-label="별점 5점" className="flex text-[14px] tracking-[0.08em] text-[#2f6df6]">
          {"★★★★★"}
        </div>
      </div>
      <p className="mt-4 line-clamp-4 text-[15px] font-semibold leading-[1.55] tracking-[-0.035em] text-[#16213d] sm:text-[16px]">
        “{quote}”
      </p>
      <div className="mt-5 flex items-end justify-between gap-4">
        <p className="text-[13px] font-semibold text-[#2f6df6]">{role}</p>
        <p className="text-right text-[12px] leading-5 text-[#7a89a3]">{point}</p>
      </div>
    </article>
  );
}

function RepresentativeSocialProof({
  count,
  locale,
}: {
  count: number | null;
  locale: SupportedLocale;
}) {
  const translated = (row: PublicRow) => localizedCopy(locale, row);
  const formattedCount = count?.toLocaleString(getLocaleOption(locale).htmlLang);

  return (
    <div className="mx-auto flex max-w-[780px] flex-col items-center text-center">
      <div aria-hidden="true" className="flex -space-x-2.5">
        {["#2f6df6", "#7098fb", "#a7c0ff"].map((color) => (
          <span
            key={color}
            className="flex h-10 w-10 items-center justify-center rounded-full border-[3px] border-[#fbfcff] text-white shadow-[0_6px_16px_rgba(47,109,246,0.16)] sm:h-11 sm:w-11"
            style={{ backgroundColor: color }}
          >
            <svg viewBox="0 0 24 24" className="h-[18px] w-[18px]" fill="none">
              <circle cx="12" cy="8" r="3.2" fill="currentColor" />
              <path d="M5.8 19c.7-4 2.8-6 6.2-6s5.5 2 6.2 6" fill="currentColor" />
            </svg>
          </span>
        ))}
        <span className="relative flex h-10 w-10 items-center justify-center rounded-full border-[3px] border-[#fbfcff] bg-white text-[#2f6df6] shadow-[0_6px_18px_rgba(47,109,246,0.18)] sm:h-11 sm:w-11">
          <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none">
            <path d="m7.5 12.3 3 3 6.3-7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </span>
      </div>

      <p className="mt-4 text-[20px] font-semibold leading-[1.42] tracking-[-0.045em] text-[#17233f] sm:text-[25px]">
        {count !== null && formattedCount ? (
          <>
            {translated(["지금 ", "Join ", "已有 ", "現在 ", "Đã có ", "Уже "])}
            <strong className="font-semibold text-[#2f6df6]">{formattedCount}</strong>
            {translated([
              "명의 대표님이 오피셜메일과 함께하고 있습니다.",
              " business owners already using Official Mail.",
              " 位企业负责人正在使用 Official Mail。",
              "名の事業者がOfficial Mailを利用しています。",
              " chủ doanh nghiệp đang sử dụng Official Mail.",
              " владельцев бизнеса уже используют Official Mail.",
            ])}
          </>
        ) : (
          translated([
            "대표님들이 오피셜메일과 함께하고 있습니다.",
            "Business owners are already using Official Mail.",
            "企业负责人正在使用 Official Mail。",
            "事業者の皆さまがOfficial Mailを利用しています。",
            "Các chủ doanh nghiệp đang sử dụng Official Mail.",
            "Владельцы бизнеса уже используют Official Mail.",
          ])
        )}
      </p>
      <p className="mt-2 text-[12px] leading-5 text-[#8290a8] sm:text-[13px]">
        {translated([
          "도메인을 등록한 대표 계정을 기준으로 집계됩니다.",
          "Counted from representative accounts with a registered domain.",
          "按已注册域名的负责人账号统计。",
          "ドメインを登録した代表者アカウントを集計しています。",
          "Số liệu dựa trên tài khoản đại diện đã đăng ký tên miền.",
          "Учитываются основные аккаунты с зарегистрированным доменом.",
        ])}
      </p>
    </div>
  );
}

function ReviewMarquee({
  representativeCount,
  locale,
  reviews,
}: {
  representativeCount: number | null;
  locale: SupportedLocale;
  reviews: typeof customerReviews;
}) {
  const rollingReviews = [...reviews, ...reviews];

  return (
    <div className="fade-up mt-10 sm:mt-12">
      <RepresentativeSocialProof count={representativeCount} locale={locale} />
      <div className="review-marquee-mask -mx-4 overflow-hidden px-4 pb-[76px] pt-8 sm:-mx-8 sm:px-8 sm:pt-9 xl:-mx-10 xl:px-10">
        <div className="review-marquee-track flex w-max gap-4">
          {rollingReviews.map((review, index) => (
            <ReviewCard
              key={`${review.role}-${index}`}
              ariaHidden={index >= reviews.length}
              point={review.point}
              quote={review.quote}
              role={review.role}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

function PrimaryCta({
  href,
  children,
  size = "md",
}: {
  href: string;
  children: ReactNode;
  size?: "sm" | "md" | "lg";
}) {
  const sizeClass =
    size === "sm"
      ? "h-12 rounded-[14px] px-6 text-[16px]"
      : size === "lg"
        ? "h-[58px] rounded-[14px] px-8 text-[20px]"
        : "h-[54px] rounded-[14px] px-7 text-[18px]";

  const className = `om-btn-primary ${sizeClass}`;

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

  return (
    <Link href={href} className={className}>
      {children}
    </Link>
  );
}

export default async function Home() {
  const locale = await resolveRequestLocale();
  const requestHeaders = await headers();
  const visitorCountryLocale = resolveLocaleFromCountry(
    getRequestCountryCode(requestHeaders),
  );
  const billingProvider = resolveMailBillingProvider(requestHeaders);
  const polarPrice = resolvePolarLocalizedPrice(requestHeaders);
  const growthPrice = billingProvider === "toss-pay"
    ? { amount: MAIL_GROWTH_PLAN_NET_PRICE_PER_MEMBER, currency: "krw" }
    : polarPrice;
  const growthPriceLabel =
    billingProvider === "toss-pay" && locale === "ko"
      ? `${growthPrice.amount.toLocaleString("ko-KR")}원`
      : formatPolarPrice(growthPrice.amount, growthPrice.currency, locale);
  const landingPriceCopy = getLandingPriceCopy(
    locale,
    growthPriceLabel,
    billingProvider === "toss-pay",
  );
  const translated = (row: PublicRow) => localizedCopy(locale, row);
  const text = (korean: string, row: PublicRow) =>
    locale === "ko" ? korean : translated(row);
  const localizedNavItems = navItems.map((item) => ({
    href: item.href,
    label: translated(item.label),
  }));
  const localizedHeroPerks = locale === "ko" ? heroPerks : [
    translated(homeCopy.free),
    translated(homeCopy.noCard),
    translated(homeCopy.ownDomain),
  ];
  const localizedFeatureRail = locale === "ko" ? featureRail : featureRail.map((feature, index) => ({
    ...feature,
    title: translated(homeCopy.benefitTitles[index]),
    description: translated(homeCopy.benefitBodies[index]),
  }));
  const localizedWhyItems = locale === "ko" ? whyItems : whyItems.map((item, index) => ({
    ...item,
    title: translated(homeCopy.benefitTitles[index]),
    description: translated(homeCopy.benefitBodies[index]),
  }));
  const localizedStats = locale === "ko"
    ? stats.map((item, index) => index === 1
      ? { value: growthPriceLabel, label: landingPriceCopy.statLabel }
      : item)
    : [
        { value: "0", label: translated(homeCopy.free) },
        { value: growthPriceLabel, label: landingPriceCopy.statLabel },
        { value: "4", label: translated(homeCopy.stepsTitle) },
        { value: "AI", label: translated(homeCopy.benefitTitles[3]) },
      ];
  const localizedResources = locale === "ko" ? businessEmailResources : [
    { href: "/business-email", label: translated(shared.businessEmail), title: translated(homeCopy.title), description: translated(homeCopy.lead) },
    { href: "/blog/company-email-address-guide", label: translated(shared.blog), title: translated(homeCopy.useTitle), description: translated(homeCopy.useBodies[0]) },
    { href: "/guide#domain", label: translated(shared.guide), title: translated(homeCopy.stepsTitle), description: translated(seoGenericCopy.summaryItems[1]) },
    { href: "/domain-mail-check", label: translated(shared.freeCheck), title: translated(seoGenericCopy.howTitle), description: translated(seoGenericCopy.how[1]) },
  ];
  const localizedSuccessStories = locale === "ko" ? successStories : successStories.map((story, index) => ({
    ...story,
    category: translated(homeCopy.benefitTitles[index]),
    title: translated(homeCopy.useBodies[index]),
    description: translated(homeCopy.benefitBodies[index]),
    result: translated(seoGenericCopy.summaryItems[index]),
  }));
  const localizedCustomerReviews = locale === "ko" ? customerReviews : customerReviews.map((review, index) => ({
    ...review,
    role: translated(homeCopy.benefitTitles[index % homeCopy.benefitTitles.length]),
    quote: translated(homeCopy.useBodies[index % homeCopy.useBodies.length]),
    point: translated(homeCopy.benefitBodies[index % homeCopy.benefitBodies.length]),
  }));

  const [user, representativeCount] = await Promise.all([
    getSessionUser(),
    getPublicRepresentativeAccountCount(),
  ]);
  const mailEntryUrl = await getMailEntryUrlForCurrentRequest(user);
  const loginHref = user
    ? mailEntryUrl
    : await getMailAuthUrlForCurrentRequest("/login");
  const primaryHref = user
    ? mailEntryUrl
    : await getMailAuthUrlForCurrentRequest("/login");
  const loginLabel = user
    ? translated(["메일 홈", "Mail home", "邮件主页", "メールホーム", "Trang thư", "Почта"])
    : translated(shared.login);
  const primaryLabel = user
    ? translated(["메일 홈 열기", "Open mail", "打开邮箱", "メールを開く", "Mở hộp thư", "Открыть почту"])
    : translated(shared.start);
  const compactPrimaryLabel = user
    ? primaryLabel
    : translated(["시작하기", "Get started", "开始使用", "始める", "Bắt đầu", "Начать"]);
  const windowsDownloadLabel = translated([
    "Windows 앱 다운로드",
    "Download Windows app",
    "下载 Windows 应用",
    "Windowsアプリをダウンロード",
    "Tải ứng dụng Windows",
    "Скачать приложение Windows",
  ]);
  const windowsDownloadHref = getMailAbsoluteUrl(
    "/api/app/releases/windows/download/latest?channel=stable",
  );
  const schemas = buildHomeSchemas(locale);

  return (
    <ServerStaticUiLocalizer locale={locale}>
    <div className="min-h-screen bg-[#fbfcff] text-[#101a34]" style={{ overflowX: "clip" }}>
      {schemas.map((schema) => (
        <JsonLd key={schema["@type"] as string} data={schema} />
      ))}
      <div className="pointer-events-none absolute inset-x-0 top-0 h-[960px] bg-[radial-gradient(circle_at_50%_12%,rgba(47,109,246,0.16),rgba(47,109,246,0)_42%),radial-gradient(circle_at_15%_15%,rgba(145,183,255,0.16),rgba(145,183,255,0)_28%),radial-gradient(circle_at_80%_28%,rgba(194,214,255,0.22),rgba(194,214,255,0)_24%)]" />

      <div className="relative z-50 bg-gradient-to-r from-[#2563eb] to-[#1d4ed8] px-3 py-2 text-center text-[11px] font-medium text-white sm:px-4 sm:text-sm">
        <div className="mx-auto flex max-w-[1420px] items-center justify-center gap-2">
          <span className="rounded-full bg-yellow-400 px-2 py-0.5 text-[10px] font-bold uppercase text-slate-900">
            NEW
          </span>
          <span className="leading-[1.3] sm:leading-normal">
            <span>{translated(homeCopy.free)} · {landingPriceCopy.banner} · </span>
            <span className="block sm:inline">도메인 연결 후 바로 사용</span>
          </span>
          <a
            href="#pricing"
            className="ml-4 hidden items-center gap-1 font-bold underline transition-colors hover:text-yellow-300 md:inline-flex"
          >
            요금제 보기
          </a>
        </div>
      </div>

      <div className="sticky top-0 z-40">
        {locale === "ko" ? (
          <PublicLocaleSuggestion countryLocale={visitorCountryLocale} />
        ) : null}

        <div className="border-b border-black/5 bg-white/65 shadow-sm backdrop-blur-xl backdrop-saturate-150">
        <header className="fade-up mx-auto flex h-[62px] w-full max-w-[1420px] items-center justify-between px-4 sm:h-20 sm:px-8 xl:px-10">
          <Link href={getLocalizedPublicPath("/", locale)} className="shrink-0">
            <LogoMark locale={locale} />
          </Link>

          <nav className="hidden items-center gap-8 text-[15px] font-medium text-[#5a6882] lg:flex lg:gap-10 xl:text-[16px]">
            {localizedNavItems.map((item) => (
              <a key={item.href} href={item.href} className="transition-colors hover:text-[#2f6df6]">
                {item.label}
              </a>
            ))}
          </nav>

          <div className="flex items-center gap-2 sm:gap-3">
            <PublicLanguageMenu currentLocale={locale} />
            <a
              href={windowsDownloadHref}
              aria-label={windowsDownloadLabel}
              title={windowsDownloadLabel}
              className="hidden h-10 w-10 shrink-0 items-center justify-center rounded-[12px] border border-[#dbe5f7] bg-white/80 text-[#2f6df6] shadow-[0_8px_22px_rgba(47,109,246,0.08)] transition-all hover:-translate-y-0.5 hover:border-[#b9cdf8] hover:bg-[#f4f8ff] hover:shadow-[0_12px_28px_rgba(47,109,246,0.14)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2f6df6]/35 sm:inline-flex sm:h-11 sm:w-11"
            >
              <HeaderDownloadIcon />
              <span className="sr-only">{windowsDownloadLabel}</span>
            </a>
            <span className="hidden sm:inline-flex">
              {/^https?:\/\//.test(loginHref) ? (
                <a
                  href={loginHref}
                  className="om-btn-secondary h-10 rounded-[12px] px-3.5 text-[13px] sm:h-11 sm:px-5 sm:text-base"
                >
                  {loginLabel}
                </a>
              ) : (
                <Link
                  href={loginHref}
                  className="om-btn-secondary h-10 rounded-[12px] px-3.5 text-[13px] sm:h-11 sm:px-5 sm:text-base"
                >
                  {loginLabel}
                </Link>
              )}
            </span>
            {/^https?:\/\//.test(primaryHref) ? (
              <a
                href={primaryHref}
                className="om-btn-primary h-10 rounded-[12px] px-3.5 text-[13px] sm:h-11 sm:px-5 sm:text-base"
              >
                <span className="sm:hidden">
                  {compactPrimaryLabel}
                </span>
                <span className="hidden sm:inline">{primaryLabel}</span>
              </a>
            ) : (
              <Link
                href={primaryHref}
                className="om-btn-primary h-10 rounded-[12px] px-3.5 text-[13px] sm:h-11 sm:px-5 sm:text-base"
              >
                <span className="sm:hidden">
                  {compactPrimaryLabel}
                </span>
                <span className="hidden sm:inline">{primaryLabel}</span>
              </Link>
            )}
          </div>
        </header>
        </div>
      </div>

      <main className="relative z-10 mx-auto flex w-full max-w-[1420px] flex-col px-4 pb-20 pt-8 sm:px-8 sm:pb-24 sm:pt-10 xl:px-10">

        <section
          id="about"
          className="grid gap-10 pb-12 pt-8 sm:gap-12 sm:pb-16 sm:pt-10 lg:grid-cols-2 lg:items-center lg:gap-10 xl:grid-cols-[minmax(0,620px)_minmax(0,660px)] xl:gap-16 xl:pt-[68px] 2xl:grid-cols-[minmax(0,660px)_minmax(0,700px)]"
        >
          <div className="flex max-w-[660px] flex-col lg:max-w-[580px] xl:max-w-[620px] 2xl:max-w-[660px]">
            <p className="fade-up text-[20px] font-semibold tracking-[-0.04em] text-[#2f6df6] sm:text-[24px]">
              {text("사업 시작하셨나요?", homeCopy.eyebrow)}
            </p>
            <h1
              className="fade-up mt-4 text-[28px] font-semibold leading-[1.16] tracking-[-0.06em] text-[#111a33] sm:mt-5 sm:text-[38px] lg:text-[46px]"
              style={{ animationDelay: "80ms" }}
            >
              {text("대표님 혼자 운영하시는 동안 기업메일은 무료입니다.", homeCopy.title)}
            </h1>
            <p
              className="fade-up mt-6 text-[16px] leading-[1.72] text-[#4e5d79] sm:mt-8 sm:text-[19px]"
              style={{ animationDelay: "140ms" }}
            >
              {text("도메인은 이미 샀는데 메일 때문에 매달 비용을 내고 있었다면, 오피셜메일이 대표 메일 하나를 가장 빠르게 열어드립니다.", homeCopy.lead)}
            </p>

            <div
              className="fade-up mt-8 sm:mt-10"
              style={{ animationDelay: "180ms" }}
            >
              <PrimaryCta href={primaryHref} size="lg">
                {primaryLabel}
                <span aria-hidden className="text-white/95">→</span>
              </PrimaryCta>
            </div>

            <div
              className="fade-up mt-8 grid grid-cols-2 gap-x-4 gap-y-3 text-[14px] text-[#2f6df6] sm:mt-10 sm:flex sm:flex-wrap sm:gap-6 sm:text-[17px]"
              style={{ animationDelay: "220ms" }}
            >
              {localizedHeroPerks.map((perk) => (
                <div key={perk} className="flex items-center gap-3">
                  <span className="flex h-6 w-6 items-center justify-center rounded-full border border-[#d8e6ff] bg-white text-[#2f6df6]">
                    <IconBase className="h-3.5 w-3.5">
                      <path d="m6 12.4 3.1 3.2L18 7.8" />
                    </IconBase>
                  </span>
                  <span className="font-medium text-[#32508d]">{perk}</span>
                </div>
              ))}
            </div>
          </div>

          <div
            className="fade-up flex items-center justify-center lg:justify-end"
            style={{ animationDelay: "120ms" }}
          >
            <div className="w-full max-w-[420px] sm:max-w-[500px] xl:max-w-[660px] 2xl:max-w-[700px]">
              <HeroPreview locale={locale} />
            </div>
          </div>
        </section>

        <section
          id="features"
          className="fade-up rounded-[26px] border border-white/90 bg-white/88 p-4 shadow-[0_24px_70px_rgba(37,99,235,0.08)] backdrop-blur-xl sm:rounded-[30px] sm:p-6"
          style={{ animationDelay: "120ms" }}
        >
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            {localizedFeatureRail.map((feature) => (
              <div key={feature.title} className="flex items-start gap-4 rounded-[24px] px-3 py-3 sm:px-4 sm:py-4">
                <CircleIcon type={feature.icon as "mail" | "domain" | "setup" | "shield"} />
                <div className="pt-1">
                  <p className="text-[17px] font-semibold tracking-[-0.04em] text-[#1b2540] sm:text-[19px]">
                    {feature.title}
                  </p>
                  <p className="mt-2 whitespace-pre-line text-[14px] leading-[1.65] text-[#66748d] sm:mt-3 sm:text-[16px]">
                    {feature.description}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </section>

        <LandingStorySections locale={locale} />

        <section id="why" className="pb-6 pt-[60px] text-center sm:pt-[72px]">
          <p className="fade-up text-[15px] font-semibold tracking-[0.16em] text-[#2f6df6]">
            WHY OFFICIAL MAIL
          </p>
          <h2
            className="fade-up mt-4 text-[28px] font-semibold tracking-[-0.06em] text-[#111a33] sm:mt-5 sm:text-[38px] lg:text-[46px]"
            style={{ animationDelay: "80ms" }}
          >
            {text("왜 오피셜메일인가요?", homeCopy.whyTitle)}
          </h2>

          <WhyOfficialCarousel
            items={localizedWhyItems}
            label={text("오피셜메일의 주요 장점", homeCopy.whyTitle)}
          />
        </section>

        <section id="domain" className="pb-10 pt-[72px] text-center">
          <p className="fade-up text-[18px] text-[#5f6e88] sm:text-[20px]">
            {text("대표 메일부터 팀 확장까지, 필요한 만큼만 운영하세요", homeCopy.priceTitle)}
          </p>

          <div className="mt-10 grid gap-6 sm:mt-14 sm:grid-cols-2 lg:grid-cols-4">
            {localizedStats.map((item, index) => (
              <div
                key={item.label}
                className={`fade-up px-4 py-2 sm:px-6 sm:py-4 ${index > 0 ? "lg:border-l lg:border-[#edf1fa]" : ""}`}
                style={{ animationDelay: `${80 + index * 70}ms` }}
              >
                <StatItem value={item.value} label={item.label} />
              </div>
            ))}
          </div>
        </section>

        <section className="pb-10 pt-8 sm:pb-14 sm:pt-12">
          <div className="grid gap-8 border-t border-[#e9eef8] pt-9 sm:pt-12 lg:grid-cols-[minmax(0,360px)_minmax(0,1fr)] lg:gap-14">
            <div className="fade-up">
              <p className="text-[14px] font-semibold tracking-[-0.02em] text-[#2f6df6]">
                {text("성공사례", homeCopy.useTitle)}
              </p>
              <h2 className="mt-4 text-[28px] font-semibold leading-[1.15] tracking-[-0.06em] text-[#111a33] sm:text-[38px]">
                {text("작은 팀이 먼저 정리하는 메일 운영 방식", homeCopy.useTitle)}
              </h2>
              <p className="mt-5 text-[15px] leading-[1.72] text-[#64718c] sm:text-[17px]">
                {text("오피셜메일은 거창한 그룹웨어보다 먼저 필요한 공식 주소, 팀 계정, AI 요약 릴레이를 빠르게 붙이는 방식에 집중합니다.", homeCopy.whyLead)}
              </p>
            </div>

            <div className="divide-y divide-[#e9eef8] border-y border-[#e9eef8]">
              {localizedSuccessStories.map((story, index) => (
                <article
                  key={story.title}
                  className="fade-up grid gap-4 py-6 sm:gap-6 sm:py-7 lg:grid-cols-[116px_minmax(0,1fr)] 2xl:grid-cols-[126px_minmax(0,1fr)_150px]"
                  style={{ animationDelay: `${100 + index * 80}ms` }}
                >
                  <div>
                    <p className="text-[13px] font-semibold text-[#2f6df6] sm:text-[14px]">
                      {story.category}
                    </p>
                  </div>
                  <div className="min-w-0">
                    <h3 className="text-[19px] font-semibold leading-[1.35] tracking-[-0.04em] text-[#16213d] sm:text-[22px]">
                      {story.title}
                    </h3>
                    <p className="mt-3 text-[14px] leading-[1.75] text-[#65738e] sm:text-[16px]">
                      {story.description}
                    </p>
                  </div>
                  <div className="flex items-start lg:col-start-2 2xl:col-start-auto 2xl:justify-end">
                    <span className="text-[13px] font-semibold leading-6 text-[#2f6df6] 2xl:text-right">
                      {story.result}
                    </span>
                  </div>
                </article>
              ))}
            </div>
          </div>

          <ReviewMarquee
            locale={locale}
            representativeCount={representativeCount}
            reviews={localizedCustomerReviews}
          />
        </section>

        <section
          aria-labelledby="business-email-resources-title"
          className="border-t border-[#e9eef8] py-14 sm:py-18"
        >
          <div className="grid gap-9 lg:grid-cols-[minmax(0,360px)_minmax(0,1fr)] lg:gap-14">
            <div className="fade-up lg:sticky lg:top-28 lg:self-start">
              <p className="text-[13px] font-semibold tracking-[-0.02em] text-[#2f6df6]">
                {text("기업메일 시작 가이드", shared.guide)}
              </p>
              <h2
                id="business-email-resources-title"
                className="mt-3 max-w-[420px] text-[28px] font-semibold leading-[1.18] tracking-[-0.06em] text-[#111a33] sm:text-[38px]"
              >
                {text("회사 이메일을 만들 때 필요한 답부터 확인하세요", homeCopy.stepsTitle)}
              </h2>
              <p className="mt-5 max-w-[420px] text-[15px] leading-[1.75] text-[#64718c] sm:text-[16px]">
                {text("무료 기업메일의 범위, 대표 주소 선택, 도메인 연결과 DNS 진단까지 실제 시작 순서에 맞춰 정리했습니다.", homeCopy.lead)}
              </p>
            </div>

            <nav
              aria-label="기업메일 시작 자료"
              className="divide-y divide-[#e5ecf7] border-y border-[#e5ecf7]"
            >
              {localizedResources.map((resource, index) => (
                <Link
                  key={resource.href}
                  href={getLocalizedPublicPath(resource.href, locale)}
                  className="group grid gap-3 py-6 transition-colors hover:bg-[#f8faff] sm:grid-cols-[110px_minmax(0,1fr)_auto] sm:items-center sm:gap-5 sm:px-3 sm:py-7"
                >
                  <span className="text-[12px] font-semibold text-[#2f6df6]">
                    {String(index + 1).padStart(2, "0")} · {resource.label}
                  </span>
                  <span className="min-w-0">
                    <span className="block text-[18px] font-semibold tracking-[-0.04em] text-[#243451] transition-colors group-hover:text-[#2f6df6] sm:text-[20px]">
                      {resource.title}
                    </span>
                    <span className="mt-2 block text-[13px] leading-6 text-[#71809a] sm:text-[14px]">
                      {resource.description}
                    </span>
                  </span>
                  <span
                    aria-hidden="true"
                    className="text-[18px] text-[#9aa8bd] transition-transform duration-200 group-hover:translate-x-1 group-hover:text-[#2f6df6]"
                  >
                    →
                  </span>
                </Link>
              ))}
            </nav>
          </div>
        </section>

        <LandingPricingSection
          growthPriceLabel={growthPriceLabel}
          growthPriceDescription={landingPriceCopy.description}
          growthPriceTaxNote={landingPriceCopy.taxNote}
          locale={locale}
          primaryHref={primaryHref}
        />

      </main>

      <SiteFooter className="border-t-0 bg-transparent pb-10 pt-2" />
    </div>
    </ServerStaticUiLocalizer>
  );
}
