import type { CSSProperties } from "react";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { SiteFooter } from "@/components/site-footer";
import { getPublicSiteUrl } from "@/lib/mail-urls";
import { getSeoPage, seoPages, type SeoPage } from "@/lib/seo-pages";

type SeoLandingPageProps = {
  params: Promise<{ slug: string }>;
};

export const dynamicParams = false;

type VariantTone = {
  accent: string;
  bg: string;
  glow: string;
  line: string;
  muted: string;
  soft: string;
  text: string;
};

const variantTone: Record<SeoPage["variant"], VariantTone> = {
  ai: {
    accent: "#2f6df6",
    bg: "#f7fbff",
    glow: "rgba(47,109,246,0.16)",
    line: "#d9e7ff",
    muted: "#64748b",
    soft: "#edf4ff",
    text: "#16233c",
  },
  business: {
    accent: "#1f66ff",
    bg: "#ffffff",
    glow: "rgba(47,102,255,0.14)",
    line: "#dce8ff",
    muted: "#65758d",
    soft: "#f0f6ff",
    text: "#15223a",
  },
  domain: {
    accent: "#0f8f8b",
    bg: "#fbfffd",
    glow: "rgba(15,143,139,0.14)",
    line: "#cfeeea",
    muted: "#5f756f",
    soft: "#effbf8",
    text: "#102d2a",
  },
  faq: {
    accent: "#2f6df6",
    bg: "#ffffff",
    glow: "rgba(25,38,72,0.12)",
    line: "#e2e8f0",
    muted: "#64748b",
    soft: "#f6f9ff",
    text: "#16233c",
  },
  secure: {
    accent: "#1764d8",
    bg: "#f9fbff",
    glow: "rgba(23,100,216,0.14)",
    line: "#dce7fa",
    muted: "#627287",
    soft: "#eef5ff",
    text: "#14223a",
  },
  team: {
    accent: "#3165e8",
    bg: "#ffffff",
    glow: "rgba(49,101,232,0.14)",
    line: "#dfe8fa",
    muted: "#65748d",
    soft: "#f2f7ff",
    text: "#16233c",
  },
};

const seoFrameClass = "mx-auto w-full max-w-[1420px] px-4 sm:px-8 xl:px-10";

function siteUrl(path = "/") {
  return new URL(path, getPublicSiteUrl()).toString();
}

function buildOgImage() {
  return {
    url: siteUrl("/images/officialmail-og.png"),
    width: 1200,
    height: 630,
    alt: "오피셜메일 - 무료로 시작하는 기업메일",
  };
}

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

function Logo() {
  return (
    <Link href="/" className="flex shrink-0 items-center justify-center gap-2.5 text-center sm:gap-3">
      <span className="flex items-center justify-center text-[#2f6df6]">
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.8"
          strokeLinecap="round"
          strokeLinejoin="round"
          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" />
        </svg>
      </span>
      <span className="text-[22px] font-extrabold tracking-[-0.08em] text-[#2f6df6]">
        오피셜메일
      </span>
    </Link>
  );
}

function SeoHeader({
  currentSlug,
  mailEntryUrl,
}: {
  currentSlug: string;
  mailEntryUrl: string;
}) {
  const primaryPages = ["business-email", "domain-email", "ai-email-summary", "faq"];

  return (
    <>
      <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>대표 메일 1개 무료 · 성장 플랜은 팀 인원당 월 3,900원 · </span>
            <span className="block sm:inline">도메인 연결 후 바로 사용</span>
          </span>
          <Link
            href="/#pricing"
            className="ml-4 hidden items-center gap-1 font-bold underline transition-colors hover:text-yellow-300 md:inline-flex"
          >
            요금제 보기
          </Link>
        </div>
      </div>

      <div className="sticky top-0 z-40 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">
          <Logo />
          <nav className="hidden items-center gap-8 text-[15px] font-medium text-[#5a6882] md:flex lg:gap-10 xl:text-[16px]">
            {seoPages
              .filter((page) => primaryPages.includes(page.slug))
              .map((page) => (
                <Link
                  key={page.slug}
                  href={`/${page.slug}`}
                  className={`transition-colors hover:text-[#2f6df6] ${
                    page.slug === currentSlug ? "text-[#2f6df6]" : ""
                  }`}
                >
                  {page.navTitle}
                </Link>
              ))}
            <Link href="/blog" className="transition-colors hover:text-[#2f6df6]">
              정보 가이드
            </Link>
          </nav>
          <div className="flex items-center gap-2 sm:gap-3">
            <a
              href={mailEntryUrl}
              className="om-btn-secondary hidden h-10 rounded-[12px] px-3.5 text-[13px] sm:inline-flex sm:h-11 sm:px-5 sm:text-base"
            >
              로그인
            </a>
            <a
              href={mailEntryUrl}
              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">시작하기</span>
              <span className="hidden sm:inline">오피셜메일 시작하기</span>
            </a>
          </div>
        </header>
      </div>
    </>
  );
}

function TopicNav({ currentSlug }: { currentSlug: string }) {
  return (
    <nav className="mt-10 flex w-full flex-wrap justify-center gap-x-5 gap-y-3 text-[13px] font-semibold text-[#64748b]">
      {seoPages.map((item) => (
        <Link
          key={item.slug}
          href={`/${item.slug}`}
          className={`transition-colors hover:text-[#2f6df6] ${
            item.slug === currentSlug ? "text-[#2f6df6]" : ""
          }`}
        >
          {item.navTitle}
        </Link>
      ))}
    </nav>
  );
}

export function generateStaticParams() {
  return seoPages.map((page) => ({ slug: page.slug }));
}

export async function generateMetadata({
  params,
}: SeoLandingPageProps): Promise<Metadata> {
  const { slug } = await params;
  const page = getSeoPage(slug);

  if (!page) {
    return {};
  }

  const url = siteUrl(`/${page.slug}`);
  const title = `${page.navTitle} | 오피셜메일`;

  return {
    title,
    description: page.description,
    keywords: page.keywords,
    alternates: {
      canonical: url,
      languages: {
        "ko-KR": url,
        "x-default": url,
      },
    },
    openGraph: {
      title,
      description: page.description,
      images: [buildOgImage()],
      url,
      siteName: "오피셜메일",
      locale: "ko_KR",
      type: "website",
    },
    robots: {
      follow: true,
      index: true,
    },
    twitter: {
      card: "summary_large_image",
      title,
      description: page.description,
      images: [siteUrl("/images/officialmail-og.png")],
    },
  };
}

function SectionHeading({
  body,
  eyebrow,
  title,
}: {
  body?: string;
  eyebrow?: string;
  title: string;
}) {
  return (
    <div className="max-w-[820px]">
      {eyebrow ? (
        <p className="mb-4 text-[14px] font-extrabold tracking-[-0.02em] text-[#2f6df6]">
          {eyebrow}
        </p>
      ) : null}
      <h2 className="text-balance text-[34px] font-extrabold leading-[1.12] tracking-[-0.075em] text-[#16233c] sm:text-[48px]">
        {title}
      </h2>
      {body ? (
        <p className="mt-5 max-w-[680px] text-[16px] leading-8 text-[#64748b] sm:text-[17px]">
          {body}
        </p>
      ) : null}
    </div>
  );
}

function MailIcon({ className = "h-6 w-6" }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
    >
      <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 HeroVisual({ page, tone }: { page: SeoPage; tone: VariantTone }) {
  if (page.variant === "domain") {
    return (
      <div className="relative min-h-[390px] overflow-hidden">
        <div
          className="absolute inset-8 rounded-[46%] opacity-80 blur-3xl"
          style={{ background: tone.glow }}
        />
        <div className="relative mx-auto max-w-[500px] pt-8">
          <div className="grid grid-cols-[1fr_90px_1fr] items-center gap-4">
            <div className="space-y-4 text-right">
              {["MX", "SPF", "DKIM"].map((record) => (
                <div key={record} className="border-t pt-3" style={{ borderColor: tone.line }}>
                  <p className="text-[28px] font-extrabold tracking-[-0.08em]" style={{ color: tone.accent }}>
                    {record}
                  </p>
                  <p className="text-[12px] font-semibold text-[#6b7c90]">DNS record</p>
                </div>
              ))}
            </div>
            <div className="flex h-[300px] items-center justify-center">
              <div
                className="h-full w-px"
                style={{
                  background: `linear-gradient(180deg, transparent, ${tone.accent}, transparent)`,
                }}
              />
            </div>
            <div className="space-y-4">
              {["수신 경로", "발신 인증", "도메인 신뢰"].map((item) => (
                <div key={item} className="rounded-[22px] bg-white px-5 py-4 shadow-[0_20px_55px_rgba(25,38,72,0.08)]">
                  <p className="text-[15px] font-extrabold tracking-[-0.04em]" style={{ color: tone.text }}>
                    {item}
                  </p>
                </div>
              ))}
            </div>
          </div>
          <div className="mt-5 text-center text-[15px] font-extrabold tracking-[-0.04em]" style={{ color: tone.accent }}>
            yourbrand.com
          </div>
        </div>
      </div>
    );
  }

  if (page.variant === "ai") {
    return (
      <div className="relative min-h-[410px] overflow-hidden">
        <div className="absolute left-6 top-12 h-[230px] w-[230px] rounded-full bg-[#dbeafe] blur-3xl" />
        <div className="relative mx-auto flex max-w-[520px] flex-col gap-5 pt-8">
          <div className="ml-2 max-w-[360px] rounded-[28px] bg-white p-5 shadow-[0_24px_70px_rgba(25,38,72,0.10)]">
            <div className="h-3 w-28 rounded-full bg-[#d9e7ff]" />
            <div className="mt-5 space-y-3">
              <div className="h-3 rounded-full bg-[#e8eef8]" />
              <div className="h-3 w-10/12 rounded-full bg-[#e8eef8]" />
              <div className="h-3 w-7/12 rounded-full bg-[#e8eef8]" />
            </div>
          </div>
          <div className="ml-auto max-w-[390px] rounded-[30px] bg-[#16233c] p-6 text-white shadow-[0_28px_80px_rgba(25,38,72,0.22)]">
            <p className="text-[13px] font-bold text-[#9db8ff]">AI 요약</p>
            <p className="mt-4 text-[25px] font-extrabold leading-[1.15] tracking-[-0.07em]">
              요청, 확인할 일, 답장 방향을 먼저 확인합니다.
            </p>
            <div className="mt-6 grid grid-cols-3 gap-2 text-center text-[11px] font-bold text-[#cbd8ff]">
              <span>핵심</span>
              <span>첨부</span>
              <span>답장</span>
            </div>
          </div>
          <div className="max-w-[320px] rounded-[24px] bg-white p-5 shadow-[0_20px_60px_rgba(25,38,72,0.09)]">
            <p className="text-[13px] font-bold text-[#2f6df6]">릴레이 완료</p>
            <p className="mt-2 text-[15px] font-semibold leading-6 text-[#2b3c58]">
              담당자가 메일함을 열기 전에 요약을 받아봅니다.
            </p>
          </div>
        </div>
      </div>
    );
  }

  if (page.variant === "faq") {
    return (
      <div className="relative min-h-[390px] overflow-hidden">
        <div className="absolute inset-x-8 top-8 h-[260px] rounded-full bg-[#eef4ff] blur-3xl" />
        <div className="relative mx-auto grid max-w-[460px] grid-cols-2 gap-4 pt-10">
          {["무료 시작", "도메인 연결", "AI 요약", "팀 확장"].map((item, index) => (
            <div
              key={item}
              className={`min-h-[138px] rounded-[30px] bg-white p-5 shadow-[0_22px_64px_rgba(25,38,72,0.09)] ${
                index % 2 === 0 ? "translate-y-5" : ""
              }`}
            >
              <p className="text-[42px] font-extrabold leading-none tracking-[-0.1em] text-[#2f6df6]">
                Q
              </p>
              <p className="mt-4 text-[16px] font-extrabold tracking-[-0.05em] text-[#16233c]">
                {item}
              </p>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="relative min-h-[390px] overflow-hidden">
      <div className="absolute inset-8 rounded-full blur-3xl" style={{ background: tone.glow }} />
      <div className="relative mx-auto flex h-[390px] max-w-[500px] items-center justify-center">
        <div className="absolute h-[320px] w-[320px] rounded-full border" style={{ borderColor: tone.line }} />
        <div className="absolute h-[230px] w-[230px] rounded-full border" style={{ borderColor: tone.line }} />
        <div className="flex h-[152px] w-[152px] items-center justify-center rounded-full bg-white shadow-[0_30px_80px_rgba(32,52,89,0.12)]">
          <MailIcon className="h-16 w-16" />
        </div>
        {page.keywords.slice(0, 4).map((keyword, index) => (
          <div
            key={keyword}
            className="absolute rounded-full bg-white px-4 py-2 text-[13px] font-extrabold shadow-[0_18px_42px_rgba(32,52,89,0.1)]"
            style={{
              color: tone.accent,
              left: ["3%", "58%", "7%", "62%"][index],
              top: ["18%", "23%", "70%", "66%"][index],
            }}
          >
            {keyword}
          </div>
        ))}
      </div>
    </div>
  );
}

function HeroSection({
  mailEntryUrl,
  page,
}: {
  mailEntryUrl: string;
  page: SeoPage;
}) {
  const tone = variantTone[page.variant];
  const reverse = page.variant === "domain";
  const sectionStyle: CSSProperties = {
    background:
      page.variant === "business"
        ? "linear-gradient(180deg,#ffffff 0%,#f8fbff 100%)"
        : `radial-gradient(circle at 72% 8%, ${tone.glow}, transparent 34%), ${tone.bg}`,
  };

  return (
    <section className="relative overflow-hidden" style={sectionStyle}>
      <div className={`relative z-10 flex flex-col pb-18 pt-8 sm:pt-10 lg:pb-24 lg:pt-14 ${seoFrameClass}`}>
        <div
          className={`grid items-center gap-12 ${
            reverse ? "lg:grid-cols-[1fr_1fr]" : "lg:grid-cols-[1fr_1fr]"
          }`}
        >
          <div className={reverse ? "lg:order-2" : ""}>
            <h1
              className="max-w-[640px] text-balance text-[30px] font-extrabold leading-[1.12] tracking-[-0.065em] sm:text-[38px] lg:text-[44px]"
              style={{ color: tone.text }}
            >
              {page.title}
            </h1>
            <p className="mt-5 max-w-[620px] text-balance text-[18px] font-semibold leading-[1.5] tracking-[-0.035em] text-[#263753] sm:text-[22px]">
              {page.hero}
            </p>
            <p className="mt-5 max-w-[620px] text-[15px] leading-8 text-[#64748b] sm:text-[16px]">
              {page.description}
            </p>
            <div className="mt-9 flex flex-wrap items-center gap-3">
              <a href={mailEntryUrl} className="om-btn-primary h-12 rounded-[16px] px-6 text-[15px]">
                오피셜메일 시작하기
              </a>
              <Link href="/faq" className="om-btn-secondary h-12 rounded-[16px] px-6 text-[15px]">
                자주 묻는 질문
              </Link>
            </div>
          </div>
          <div className={reverse ? "lg:order-1" : ""}>
            <HeroVisual page={page} tone={tone} />
          </div>
        </div>
        <TopicNav currentSlug={page.slug} />
      </div>
    </section>
  );
}

function DefinitionSection({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24">
      <div className={`${seoFrameClass} grid gap-12 lg:grid-cols-[0.78fr_1.22fr]`}>
        <div>
          <p className="text-[14px] font-extrabold" style={{ color: tone.accent }}>
            {page.navTitle}의 기준
          </p>
          <h2 className="mt-4 text-balance text-[34px] font-extrabold leading-[1.12] tracking-[-0.075em] text-[#16233c] sm:text-[48px]">
            먼저 의미가 분명해야 도입 기준도 선명해집니다.
          </h2>
        </div>
        <div className="border-y py-10" style={{ borderColor: tone.line }}>
          <p className="text-[24px] font-semibold leading-[1.55] tracking-[-0.055em] text-[#253653] sm:text-[32px]">
            {page.definition}
          </p>
          <div className="mt-10 grid gap-6 md:grid-cols-3">
            {page.takeaways.map((item, index) => (
              <div key={item} className="border-t pt-5" style={{ borderColor: tone.line }}>
                <span className="text-[15px] font-extrabold" style={{ color: tone.accent }}>
                  {String(index + 1).padStart(2, "0")}
                </span>
                <p className="mt-3 text-[16px] font-semibold leading-7 tracking-[-0.035em] text-[#33425d]">
                  {item}
                </p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function ComparisonSection({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24">
      <div className={seoFrameClass}>
        <SectionHeading
          title={
            page.variant === "domain"
              ? "도메인만 있는 상태와 도메인 메일을 운영하는 상태는 다릅니다."
              : page.variant === "ai"
                ? "요약 전후의 차이는 처리 속도에서 바로 드러납니다."
                : page.variant === "faq"
                  ? "도입 전에 확인할 것과 도입 후 운영할 것을 나눠보세요."
                : "공식 메일을 갖추면 고객 응대의 기준이 달라집니다."
          }
          body="업무 메일은 단순한 수신함이 아니라 고객과 회사 사이의 기록, 신뢰, 처리 책임을 남기는 채널입니다."
        />
        <div className="mt-12 grid gap-8 lg:grid-cols-2">
          {[
            { items: page.comparison.before, title: page.comparison.beforeTitle },
            { items: page.comparison.after, title: page.comparison.afterTitle },
          ].map((group, groupIndex) => (
            <div
              key={group.title}
              className="relative overflow-hidden rounded-[34px] px-6 py-8 sm:px-8"
              style={{
                background: groupIndex === 0 ? "#f8fafc" : tone.soft,
              }}
            >
              <h3 className="text-[26px] font-extrabold tracking-[-0.065em]" style={{ color: tone.text }}>
                {group.title}
              </h3>
              <div className="mt-7 space-y-5">
                {group.items.map((item) => (
                  <p key={item} className="border-t pt-5 text-[17px] font-semibold leading-8 tracking-[-0.035em] text-[#3a4a66]" style={{ borderColor: groupIndex === 0 ? "#e2e8f0" : tone.line }}>
                    {item}
                  </p>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProcessTimeline({
  page,
  vertical = false,
}: {
  page: SeoPage;
  vertical?: boolean;
}) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24">
      <div className={seoFrameClass}>
        <SectionHeading
          title={
            page.variant === "domain"
              ? "도메인 메일 연결은 DNS 흐름을 순서대로 확인하면 됩니다."
              : page.variant === "ai"
                ? "수신부터 답장 연결까지 한 흐름으로 이어집니다."
                : "처음부터 복잡하게 시작할 필요는 없습니다."
          }
          body="작은 팀이 실제로 운영할 수 있는 순서로 시작하고, 필요해지는 시점에 기능과 계정을 확장합니다."
        />
        <div className={`mt-14 ${vertical ? "space-y-6" : "grid gap-8 md:grid-cols-2 lg:grid-cols-4"}`}>
          {page.process.map((step, index) => (
            <article
              key={step.title}
              className={`${vertical ? "grid gap-5 border-t py-7 md:grid-cols-[160px_1fr]" : "border-t pt-7"}`}
              style={{ borderColor: tone.line }}
            >
              <span className="text-[34px] font-extrabold leading-none tracking-[-0.09em]" style={{ color: tone.accent }}>
                {String(index + 1).padStart(2, "0")}
              </span>
              <div>
                <h3 className="text-[24px] font-extrabold tracking-[-0.06em] text-[#16233c]">
                  {step.title}
                </h3>
                <p className="mt-4 text-[16px] leading-8 text-[#64748b]">
                  {step.body}
                </p>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function DetailMatrix({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24" style={{ background: tone.bg }}>
      <div className={seoFrameClass}>
        <SectionHeading
          title={
            page.variant === "domain"
              ? "DNS 용어는 역할만 알면 판단하기 쉽습니다."
              : page.variant === "ai"
                ? "요약은 짧지만 판단에 필요한 항목은 분리해서 보여야 합니다."
                : "운영 기준은 세 가지 축으로 나눠 볼 수 있습니다."
          }
        />
        <div className="mt-12 grid gap-6 lg:grid-cols-3">
          {page.details.map((detail) => (
            <article key={detail.title} className="border-t pt-8" style={{ borderColor: tone.line }}>
              <h3 className="text-[32px] font-extrabold tracking-[-0.085em]" style={{ color: tone.accent }}>
                {detail.title}
              </h3>
              <p className="mt-5 text-[17px] leading-8 text-[#4d5e78]">
                {detail.body}
              </p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function UseCaseSection({
  page,
  title,
}: {
  page: SeoPage;
  title?: string;
}) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24">
      <div className={seoFrameClass}>
        <SectionHeading
          title={title ?? "어떤 업무에 바로 적용할 수 있나요?"}
          body="공식 메일 주소는 외부에 보이는 연락처이면서 내부에서 업무를 분류하는 기준이 됩니다."
        />
        <div className="mt-12 grid gap-10 lg:grid-cols-3">
          {page.useCases.map((useCase) => (
            <article key={useCase.title} className="relative min-h-[260px] border-t pt-8" style={{ borderColor: tone.line }}>
              <h3 className="text-[27px] font-extrabold tracking-[-0.07em]" style={{ color: tone.text }}>
                {useCase.title}
              </h3>
              <p className="mt-5 text-[16px] leading-8 text-[#64748b]">
                {useCase.body}
              </p>
              <div className="absolute bottom-0 left-0 h-1 w-16 rounded-full" style={{ background: tone.accent }} />
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function PainSection({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24">
      <div className={`${seoFrameClass} grid gap-12 lg:grid-cols-[0.7fr_1.3fr]`}>
        <SectionHeading title="도입을 미루게 만드는 문제는 대부분 운영 기준의 부재에서 시작됩니다." />
        <div className="space-y-7">
          {page.pains.map((pain, index) => (
            <div key={pain} className="grid gap-4 border-t pt-7 sm:grid-cols-[76px_1fr]" style={{ borderColor: tone.line }}>
              <span className="text-[20px] font-extrabold" style={{ color: tone.accent }}>
                {String(index + 1).padStart(2, "0")}
              </span>
              <p className="text-[20px] font-semibold leading-8 tracking-[-0.04em] text-[#243555]">
                {pain}
              </p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function BenefitRail({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="overflow-hidden py-18 lg:py-24" style={{ background: tone.soft }}>
      <div className={seoFrameClass}>
        <SectionHeading title="오피셜메일을 쓰면 달라지는 것" />
        <div className="mt-12 grid gap-px overflow-hidden rounded-[32px] bg-white/40 md:grid-cols-2">
          {page.benefits.map((benefit) => (
            <div key={benefit} className="min-h-[170px] bg-white p-7">
              <MailIcon className="h-7 w-7" />
              <p className="mt-6 text-[18px] font-semibold leading-8 tracking-[-0.04em] text-[#2b3d59]">
                {benefit}
              </p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function AiRelaySection({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24">
      <div className={`${seoFrameClass} grid gap-12 lg:grid-cols-[0.95fr_1.05fr]`}>
        <SectionHeading
          title="메일을 읽기 전에 처리 방향부터 잡습니다."
          body={page.definition}
        />
        <div className="relative min-h-[460px]">
          <div className="absolute left-8 top-0 h-[280px] w-[280px] rounded-full bg-[#eaf2ff] blur-3xl" />
          <div className="relative space-y-5">
            {page.details.map((detail, index) => (
              <article
                key={detail.title}
                className={`rounded-[28px] p-6 shadow-[0_22px_64px_rgba(25,38,72,0.08)] ${
                  index === 1 ? "ml-auto max-w-[420px] bg-[#16233c] text-white" : "max-w-[420px] bg-white"
                }`}
              >
                <p className="text-[15px] font-extrabold" style={{ color: index === 1 ? "#9db8ff" : tone.accent }}>
                  {detail.title}
                </p>
                <p className={`mt-4 text-[20px] font-semibold leading-8 tracking-[-0.05em] ${index === 1 ? "text-white" : "text-[#263753]"}`}>
                  {detail.body}
                </p>
              </article>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function DomainBlueprintSection({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24" style={{ background: tone.soft }}>
      <div className={seoFrameClass}>
        <SectionHeading
          title="도메인 메일은 DNS 레코드가 각자 맡은 역할을 하면서 완성됩니다."
          body="수신 경로와 발신 인증을 분리해 보면 어떤 값을 왜 설정해야 하는지 명확해집니다."
        />
        <div className="mt-14 grid gap-7 lg:grid-cols-3">
          {page.details.map((detail, index) => (
            <article key={detail.title} className="relative min-h-[280px] overflow-hidden rounded-[36px] bg-white p-8 shadow-[0_22px_70px_rgba(25,38,72,0.07)]">
              <p className="text-[58px] font-extrabold leading-none tracking-[-0.12em]" style={{ color: tone.accent }}>
                {detail.title}
              </p>
              <p className="mt-8 text-[18px] font-semibold leading-8 tracking-[-0.04em] text-[#243d3a]">
                {detail.body}
              </p>
              <div
                className="absolute -bottom-10 -right-8 h-28 w-28 rounded-full"
                style={{ background: index === 1 ? "#dff7ef" : "#dcefeb" }}
              />
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function FaqSection({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];

  return (
    <section className="py-18 lg:py-24">
      <div className={`${seoFrameClass} grid gap-12 lg:grid-cols-[0.74fr_1.26fr]`}>
        <SectionHeading
          title="자주 묻는 질문"
          body="도입 전에 가장 많이 확인하는 질문에 바로 답합니다."
        />
        <div className="divide-y border-y" style={{ borderColor: tone.line }}>
          {page.faqs.map((faq) => (
            <article key={faq.question} className="py-8">
              <h3 className="text-[21px] font-extrabold tracking-[-0.055em] text-[#16233c]">
                {faq.question}
              </h3>
              <p className="mt-4 text-[16px] leading-8 text-[#64748b]">
                {faq.answer}
              </p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function FaqHub({ page }: { page: SeoPage }) {
  const tone = variantTone[page.variant];
  const groups = [
    { items: page.faqs.slice(0, 2), title: "시작" },
    { items: page.faqs.slice(2, 4), title: "도메인과 AI" },
    { items: page.faqs.slice(4), title: "팀 운영과 결제" },
  ].filter((group) => group.items.length > 0);

  return (
    <section className="py-18 lg:py-24">
      <div className={seoFrameClass}>
        <SectionHeading
          title="도입 전에 확인해야 할 질문을 주제별로 나눴습니다."
          body="무료 시작, 도메인 연결, AI 요약, 멤버 확장까지 실제 운영 기준에 맞춰 확인하세요."
        />
        <div className="mt-14 space-y-14">
          {groups.map((group) => (
            <div key={group.title} className="grid gap-8 lg:grid-cols-[220px_1fr]">
              <h2 className="text-[34px] font-extrabold tracking-[-0.08em]" style={{ color: tone.accent }}>
                {group.title}
              </h2>
              <div className="divide-y" style={{ borderColor: tone.line }}>
                {group.items.map((faq) => (
                  <article key={faq.question} className="py-7 first:pt-0">
                    <h3 className="text-[24px] font-extrabold tracking-[-0.065em] text-[#16233c]">
                      {faq.question}
                    </h3>
                    <p className="mt-4 text-[16px] leading-8 text-[#64748b]">
                      {faq.answer}
                    </p>
                  </article>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function RelatedPages({ page }: { page: SeoPage }) {
  const related = seoPages.filter((item) => item.slug !== page.slug).slice(0, 4);

  return (
    <section className="py-18 lg:py-24">
      <div className={seoFrameClass}>
        <SectionHeading title="함께 보면 좋은 주제" />
        <div className="mt-10 grid gap-5 md:grid-cols-2 lg:grid-cols-4">
          {related.map((item) => (
            <Link key={item.slug} href={`/${item.slug}`} className="group border-t border-[#e5ecf7] pt-6">
              <p className="text-[22px] font-extrabold tracking-[-0.06em] text-[#16233c] transition-colors group-hover:text-[#2f6df6]">
                {item.navTitle}
              </p>
              <p className="mt-3 text-[14px] leading-6 text-[#64748b]">
                {item.hero}
              </p>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}

function ClosingCta({ mailEntryUrl, page }: { mailEntryUrl: string; page: SeoPage }) {
  return (
    <section className="py-24 text-center">
      <div className={seoFrameClass}>
        <h2 className="mx-auto max-w-[860px] text-balance text-[36px] font-extrabold leading-[1.12] tracking-[-0.08em] text-[#16233c] sm:text-[56px]">
          공식 메일은 고객이 회사를 판단하는 첫 접점입니다.
        </h2>
        <p className="mx-auto mt-6 max-w-[660px] text-[17px] leading-8 text-[#64748b]">
          {page.variant === "ai"
            ? "긴 문의를 놓치지 않고 빠르게 처리할 수 있도록 대표 메일과 AI 요약 흐름을 함께 운영하세요."
            : "대표 메일을 먼저 만들고, 도메인 연결과 팀 확장을 필요한 순서대로 더해보세요."}
        </p>
        <div className="mt-9 flex justify-center">
          <a href={mailEntryUrl} className="om-btn-primary h-12 rounded-[16px] px-7 text-[15px]">
            오피셜메일 시작하기
          </a>
        </div>
      </div>
    </section>
  );
}

function BusinessPage({ page }: { page: SeoPage }) {
  return (
    <>
      <DefinitionSection page={page} />
      <PainSection page={page} />
      <ComparisonSection page={page} />
      <BenefitRail page={page} />
      <ProcessTimeline page={page} />
      <UseCaseSection page={page} title="작은 회사의 업무 흐름에 바로 붙습니다." />
      <FaqSection page={page} />
    </>
  );
}

function DomainPage({ page }: { page: SeoPage }) {
  return (
    <>
      <DefinitionSection page={page} />
      <DomainBlueprintSection page={page} />
      <ProcessTimeline page={page} vertical />
      <ComparisonSection page={page} />
      <UseCaseSection page={page} title="도메인 메일은 외부 접점마다 같은 브랜드 신호를 남깁니다." />
      <FaqSection page={page} />
    </>
  );
}

function AiPage({ page }: { page: SeoPage }) {
  return (
    <>
      <AiRelaySection page={page} />
      <ProcessTimeline page={page} />
      <ComparisonSection page={page} />
      <BenefitRail page={page} />
      <UseCaseSection page={page} title="긴 메일이 자주 들어오는 업무에서 효과가 큽니다." />
      <FaqSection page={page} />
    </>
  );
}

function FaqPage({ page }: { page: SeoPage }) {
  return (
    <>
      <FaqHub page={page} />
      <ComparisonSection page={page} />
      <DetailMatrix page={page} />
      <ProcessTimeline page={page} />
      <RelatedPages page={page} />
    </>
  );
}

function DefaultPage({ page }: { page: SeoPage }) {
  return (
    <>
      <DefinitionSection page={page} />
      <PainSection page={page} />
      <DetailMatrix page={page} />
      <ComparisonSection page={page} />
      <ProcessTimeline page={page} />
      <UseCaseSection page={page} />
      <FaqSection page={page} />
    </>
  );
}

function SeoBody({ page }: { page: SeoPage }) {
  if (page.variant === "business") {
    return <BusinessPage page={page} />;
  }

  if (page.variant === "domain") {
    return <DomainPage page={page} />;
  }

  if (page.variant === "ai") {
    return <AiPage page={page} />;
  }

  if (page.variant === "faq") {
    return <FaqPage page={page} />;
  }

  return <DefaultPage page={page} />;
}

function buildSchemas(page: SeoPage, canonicalUrl: string) {
  const imageUrl = siteUrl("/images/officialmail-og.png");

  return {
    breadcrumb: {
      "@context": "https://schema.org",
      "@type": "BreadcrumbList",
      itemListElement: [
        {
          "@type": "ListItem",
          item: siteUrl("/"),
          name: "오피셜메일",
          position: 1,
        },
        {
          "@type": "ListItem",
          item: canonicalUrl,
          name: page.navTitle,
          position: 2,
        },
      ],
    },
    faq: {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: page.faqs.map((faq) => ({
        "@type": "Question",
        acceptedAnswer: {
          "@type": "Answer",
          text: faq.answer,
        },
        name: faq.question,
      })),
    },
    organization: {
      "@context": "https://schema.org",
      "@type": "Organization",
      brand: "OfficialMail",
      logo: siteUrl("/officialmail-icon.svg"),
      name: "오피셜메일",
      url: siteUrl("/"),
    },
    software: {
      "@context": "https://schema.org",
      "@type": "SoftwareApplication",
      applicationCategory: "BusinessApplication",
      description: page.description,
      image: imageUrl,
      name: "오피셜메일",
      offers: {
        "@type": "Offer",
        description: "대표 메일 1개 무료 시작",
        price: "0",
        priceCurrency: "KRW",
      },
      operatingSystem: "Web",
      url: canonicalUrl,
    },
    webPage: {
      "@context": "https://schema.org",
      "@type": "WebPage",
      about: page.keywords,
      description: page.description,
      headline: page.title,
      image: imageUrl,
      inLanguage: "ko-KR",
      mainEntity: page.faqs.map((faq) => faq.question),
      name: page.navTitle,
      url: canonicalUrl,
    },
  };
}

export default async function SeoLandingPage({ params }: SeoLandingPageProps) {
  const { slug } = await params;
  const page = getSeoPage(slug);

  if (!page) {
    notFound();
  }

  const mailEntryUrl = "/login";
  const canonicalUrl = siteUrl(`/${page.slug}`);
  const schemas = buildSchemas(page, canonicalUrl);

  return (
    <main className="min-h-screen bg-white text-[#16233c]">
      <JsonLd data={schemas.organization} />
      <JsonLd data={schemas.software} />
      <JsonLd data={schemas.webPage} />
      <JsonLd data={schemas.breadcrumb} />
      <JsonLd data={schemas.faq} />
      <SeoHeader currentSlug={page.slug} mailEntryUrl={mailEntryUrl} />
      <HeroSection page={page} mailEntryUrl={mailEntryUrl} />
      <SeoBody page={page} />
      <ClosingCta page={page} mailEntryUrl={mailEntryUrl} />
      <SiteFooter className="bg-white" />
    </main>
  );
}
