/**
 * PricingPage — INFINITH Product 1.0 가격 안내 페이지.
 *
 * 구조 (plan 섹션 15-A):
 *  1. Hero (타이틀 + 한 줄 태그라인)
 *  2. Billing Toggle (월간 / 연간 20% 할인)
 *  3. 3 Tier Cards (INSIGHT / INTELLIGENCE⭐ / INTELLIGENCE+)
 *  4. Feature Comparison Table  ← Step 3에서 구현
 *  5. Free Trial 강조 박스
 *  6. Launch Promotion 배너
 *  7. FAQ                        ← Step 3에서 구현
 *  8. Enterprise Contact CTA
 *
 * 유입 추적:
 *  - `?from=header | footer | cta | hero` 파라미터 읽어 console.log
 *    (analytics 연동은 Supabase `analytics_events` 테이블 도입 후 후속 작업)
 *
 * 핵심 데이터 소스:
 *  - src/data/pricingTiers.ts ← (이 파일 내부에 임시 정의, Step 3에서 분리 고려)
 */
import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router';
import { motion } from 'motion/react';
import { ArrowRight } from 'lucide-react';
import {
  CheckFilled,
  RocketFilled,
  BoltFilled,
  PrismFilled,
} from '@/shared/icons/FilledIcons';
import Badge from '@/features/landing/components/Badge';
import FeatureComparisonTable from '../components/FeatureComparisonTable';
import FAQ from '../components/FAQ';
import { buildContactMailto } from '@/shared/lib/contact';
import { Button } from '@/shared/ui/button';
import { PageContainer } from '@/shared/ui/page-container';
import { tiers, type Tier } from '../data/pricingTiers';

// ─── 가격 포맷터 ──────────────────────────────────────────────────
// 29_0000원 → "29만원" 포맷. 1000원 단위까지는 표기 안 함 (B2B 가격은 만원 단위)
function formatKRW(amount: number): string {
  const man = amount / 10_000;
  // 소수점 없는 정수 표기 우선. 999,999 아래면 만원, 이상이면 억 단위까지 확장 가능.
  if (Number.isInteger(man)) return `${man.toLocaleString('ko-KR')}만원`;
  return `${man.toLocaleString('ko-KR', { maximumFractionDigits: 1 })}만원`;
}

// ─── Billing Toggle 컴포넌트 ──────────────────────────────────────
interface BillingToggleProps {
  value: 'monthly' | 'annual';
  onChange: (v: 'monthly' | 'annual') => void;
}

const BillingToggle: React.FC<BillingToggleProps> = ({ value, onChange }) => {
  return (
    <div className="inline-flex items-center gap-1 p-1 rounded-full bg-white/70 border border-slate-200 backdrop-blur-sm shadow-sm">
      <Button
        variant="ghost"
        onClick={() => onChange('monthly')}
        className={`px-5 py-2 h-auto rounded-full text-sm font-semibold transition-all ${
          value === 'monthly'
            ? 'bg-primary-900 text-white shadow hover:bg-primary-900 hover:text-white'
            : 'text-slate-600 hover:text-primary-900'
        }`}
      >
        월간 결제
      </Button>
      <Button
        variant="ghost"
        onClick={() => onChange('annual')}
        className={`px-5 py-2 h-auto rounded-full text-sm font-semibold transition-all flex items-center gap-2 ${
          value === 'annual'
            ? 'bg-primary-900 text-white shadow hover:bg-primary-900 hover:text-white'
            : 'text-slate-600 hover:text-primary-900'
        }`}
      >
        연간 결제
        <span
          className={`text-xs px-2 py-0.5 rounded-full font-bold ${
            value === 'annual'
              ? 'bg-white/20 text-white'
              : 'bg-accent/10 text-accent'
          }`}
        >
          20% 할인
        </span>
      </Button>
    </div>
  );
};

// ─── Tier Card 컴포넌트 ──────────────────────────────────────────
interface TierCardProps {
  tier: Tier;
  billing: 'monthly' | 'annual';
  onSelect: (tier: Tier) => void;
}

const TierCard: React.FC<TierCardProps> = ({ tier, billing, onSelect }) => {
  const price = billing === 'monthly' ? tier.monthlyKRW : tier.annualMonthlyKRW;
  const isAnnual = billing === 'annual';

  return (
    <motion.div
      initial={{ opacity: 0, y: 30 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5 }}
      className={`relative flex flex-col rounded-3xl p-8 bg-white border shadow-sm transition-all hover:shadow-xl ${
        tier.isPopular
          ? 'border-accent/40 ring-2 ring-accent/30 shadow-lg scale-[1.02]'
          : 'border-slate-200'
      }`}
    >
      {/* Popular 배지 */}
      {tier.isPopular && (
        <div className="absolute -top-3 left-1/2 -translate-x-1/2">
          <Badge variant="popular" size="md" />
        </div>
      )}

      {/* 이름 + 태그라인 */}
      <div className="mb-6">
        <h3 className="text-2xl font-serif font-bold text-primary-900 mb-2">{tier.name}</h3>
        <p className="text-sm text-slate-500 leading-relaxed break-keep">{tier.tagline}</p>
      </div>

      {/* 가격 */}
      <div className="mb-6">
        <div className="flex items-baseline gap-2">
          <span className="text-4xl font-bold text-primary-900 tracking-tight">
            {formatKRW(price)}
          </span>
          <span className="text-slate-500 text-sm">/월</span>
        </div>
        {isAnnual && (
          <p className="text-xs text-accent font-semibold mt-2">
            연 {formatKRW(tier.annualTotalKRW)} · 20% 절약
          </p>
        )}
        {!isAnnual && (
          <p className="text-xs text-slate-400 mt-2">
            연 결제 시 월 {formatKRW(tier.annualMonthlyKRW)}
          </p>
        )}
      </div>

      {/* CTA — DS Primary: gradient + rounded-full (pill) */}
      <Button
        onClick={() => onSelect(tier)}
        className={`w-full h-auto px-8 py-3.5 rounded-full font-medium text-sm text-white transition-shadow duration-150 shadow-md hover:shadow-xl flex items-center justify-center gap-2 group bg-gradient-to-r from-brand-purple to-brand-purple-deep hover:from-[#AF90FF] hover:to-[#AF90FF] active:scale-[0.98] mb-6 ${
          tier.isPopular ? 'shadow-lg' : ''
        }`}
      >
        {tier.ctaLabel}
        <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
      </Button>

      {/* Bullet points — DS FilledIcon(CheckFilled) */}
      <ul className="space-y-3 flex-grow">
        {tier.bullets.map((bullet, i) => (
          <li key={i} className="flex items-start gap-2.5 text-sm text-slate-700">
            <CheckFilled size={16} className="text-accent shrink-0 mt-0.5" />
            <span className="leading-relaxed break-keep">{bullet}</span>
          </li>
        ))}
      </ul>

      {/* Footnote */}
      {tier.footnote && (
        <p className="mt-6 pt-4 border-t border-slate-100 text-xs text-slate-400 text-center">
          {tier.footnote}
        </p>
      )}
    </motion.div>
  );
};

// ─── 먼저 문의하기 강조 카드 ─────────────────────────────────────
// DS 레퍼런스: CTA 카드 배경에 3-stop warm gradient (Section 2.2)
// + 상단 filled 아이콘 squircle + Primary/Secondary pill 버튼 병렬
//
// PART III 피봇: "첫 리포트 무료 / 카드 등록 불필요" 표현 삭제 → 계약 기반 영업으로 일원화.
function ContactFirstBox() {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5 }}
      className="relative w-full rounded-3xl p-8 md:p-12 text-center overflow-hidden bg-gradient-to-r from-brand-grad-peach via-brand-grad-violet to-brand-grad-sky border border-white/40 shadow-[3px_4px_12px_rgba(0,0,0,0.06)]"
    >
      {/* 상단 아이콘 squircle — DS filled icon 규칙 */}
      <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-white/60 backdrop-blur-sm border border-white/50 mb-6">
        <BoltFilled size={26} className="text-accent" />
      </div>

      <h3 className="text-2xl md:text-3xl font-serif font-bold text-primary-900 mb-3">
        먼저 대화부터 시작하세요
      </h3>
      <p className="text-slate-600 leading-relaxed max-w-xl mx-auto mb-8 break-keep">
        계약 전에 병원 규모·마케팅 현황을 공유해 주시면, 전담 담당자가 적합한 플랜과
        리포트 샘플을 정리해 회신 드립니다.
      </p>

      {/* DS 듀얼 버튼: Primary + Secondary — 모두 rounded-full (pill) */}
      <div className="flex flex-col sm:flex-row items-center justify-center gap-3">
        <Button
          asChild
          className="h-auto px-8 py-3.5 rounded-full font-medium text-sm text-white transition-shadow duration-150 shadow-md hover:shadow-xl group bg-gradient-to-r from-brand-purple to-brand-purple-deep hover:from-[#AF90FF] hover:to-[#AF90FF] active:scale-[0.98]"
        >
          <a href={buildContactMailto('도입 상담 문의')}>
            상담 문의하기
            <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
          </a>
        </Button>
        <Button
          asChild
          variant="outline"
          className="h-auto px-8 py-3.5 rounded-full font-medium text-sm bg-white border-slate-200 text-brand-purple-deep hover:bg-slate-50"
        >
          <a href="#tiers">
            플랜 비교 보기
          </a>
        </Button>
      </div>
    </motion.div>
  );
}

// ─── Launch Promotion 배너 ───────────────────────────────────────
// DS: 🎁 이모지 금지(Principle: No Emoji) → RocketFilled 대체
//     dark primary gradient card + Secondary pill 버튼
function PromotionBanner() {
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.98 }}
      whileInView={{ opacity: 1, scale: 1 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5 }}
      className="w-full rounded-3xl bg-gradient-to-r from-brand-purple to-brand-purple-deep text-white p-6 md:p-8 flex flex-col md:flex-row items-center gap-4 md:gap-6"
    >
      {/* Filled icon squircle — 🎁 대체 */}
      <div className="inline-flex items-center justify-center w-12 h-12 rounded-2xl bg-white/10 backdrop-blur-sm shrink-0">
        <RocketFilled size={24} className="text-white" />
      </div>
      <div className="flex-1 text-center md:text-left">
        <p className="text-xs font-semibold text-purple-200 mb-1 tracking-wide">
          런칭 프로모션 · 선착순 20병원
        </p>
        <p className="text-base md:text-lg font-serif">
          INTELLIGENCE · INTELLIGENCE+ <strong>3개월 30% 할인</strong>
        </p>
      </div>
      <Button
        asChild
        variant="outline"
        className="h-auto px-6 py-2.5 rounded-full bg-white border-slate-200 text-brand-purple-deep font-medium text-sm hover:bg-slate-50 whitespace-nowrap"
      >
        <a href={buildContactMailto('런칭 프로모션 문의')}>
          혜택 문의
        </a>
      </Button>
    </motion.div>
  );
}

// ─── Enterprise Contact CTA ──────────────────────────────────────
// DS: outlined 패턴은 DS에 없음 → Primary pill(gradient + rounded-full)
function EnterpriseContact() {
  return (
    // outer: w-full로 섹션 정렬 / inner 콘텐츠만 max-w-2xl로 가독성 유지
    <div className="w-full text-center">
      <div className="max-w-2xl mx-auto">
        <h3 className="text-2xl font-serif font-bold text-primary-900 mb-3">
          더 많은 분원, 커스텀 플랜이 필요하신가요?
        </h3>
        <p className="text-slate-600 mb-8 break-keep">
          4개 이상 분원을 운영하시거나 데이터 커스터마이징이 필요한 경우, 전담 담당자가 상담해 드립니다.
        </p>
        <Button
          asChild
          className="h-auto px-8 py-3.5 rounded-full font-medium text-sm text-white transition-shadow duration-150 shadow-md hover:shadow-xl group bg-gradient-to-r from-brand-purple to-brand-purple-deep hover:from-[#AF90FF] hover:to-[#AF90FF] active:scale-[0.98]"
        >
          <a href={buildContactMailto('커스텀 플랜 문의')}>
            커스텀 플랜 문의
            <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
          </a>
        </Button>
      </div>
    </div>
  );
}

// ─── PricingPage 본체 ────────────────────────────────────────────
export default function PricingPage() {
  const [searchParams] = useSearchParams();
  const [billing, setBilling] = useState<'monthly' | 'annual'>('monthly');

  // 유입 소스 추적 — 추후 Supabase `analytics_events` 테이블로 전송
  useEffect(() => {
    const from = searchParams.get('from');
    if (from) {
      // TODO(analytics): Supabase analytics_events insert
      console.info(`[pricing] referred from: ${from}`);
    }
  }, [searchParams]);

  /**
   * Tier 선택 핸들러 — 계약 기반 영업.
   * 온라인 결제 없이 모든 Tier를 상담 문의 mailto로 통일.
   * Subject에 Tier 이름을 넣어 영업팀이 유입 경로를 구분.
   */
  const handleTierSelect = (tier: Tier) => {
    window.location.href = buildContactMailto(`${tier.name} 플랜 상담 문의`);
  };

  return (
    <main className="relative pt-28 md:pt-32 pb-24 overflow-hidden">
      {/* Background — 랜딩 Hero와 톤 통일 */}
      <div className="absolute inset-0 -z-10 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-indigo-100 via-purple-50 to-pink-50 opacity-60" />

      {/* ── Section 1 · Hero ─────────────────────────── */}
      <section className="px-6 text-center max-w-4xl mx-auto mb-12">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/70 border border-white/40 text-xs font-bold text-accent mb-6">
            <PrismFilled size={14} className="text-accent" />
            Pricing · 가격 안내
          </div>
          <h1 className="text-4xl md:text-6xl font-serif font-bold text-primary-900 leading-[1.1] tracking-[-0.02em] mb-5">
            Strategic Planning,<br className="hidden md:block" />
            <span className="text-gradient">At Your Scale.</span>
          </h1>
          <p className="text-lg text-slate-600 max-w-2xl mx-auto mb-10 break-keep">
            병원 규모에 맞는 전략 파트너를 선택하세요. 계약·결제·운영 조건은 상담에서 맞춤 설계됩니다.
          </p>
        </motion.div>

        {/* ── Section 2 · Billing Toggle ────────────── */}
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.15 }}
        >
          <BillingToggle value={billing} onChange={setBilling} />
        </motion.div>
      </section>

      {/* ── Section 3 · 3 Tier Cards ─────────────────── */}
      <PageContainer asChild className="mb-20 scroll-mt-24">
        <section id="tiers">
          <div className="grid md:grid-cols-3 gap-6 md:gap-8 items-stretch">
            {tiers.map((tier) => (
              <TierCard key={tier.id} tier={tier} billing={billing} onSelect={handleTierSelect} />
            ))}
          </div>
        </section>
      </PageContainer>

      {/* ── Section 4 · Feature Comparison Table ─── */}
      <PageContainer asChild className="mb-20">
        <section>
          <FeatureComparisonTable />
        </section>
      </PageContainer>

      {/* ── Section 5 · 먼저 문의하기 강조 ───────────── */}
      {/* outer max-w-7xl로 Tier Cards 섹션과 동일 정렬 (반응형 자동 축소) */}
      <PageContainer asChild className="mb-16">
        <section>
          <ContactFirstBox />
        </section>
      </PageContainer>

      {/* ── Section 6 · Launch Promotion ───────────── */}
      <PageContainer asChild className="mb-20">
        <section>
          <PromotionBanner />
        </section>
      </PageContainer>

      {/* ── Section 7 · FAQ ─────────────────────────── */}
      <PageContainer asChild className="mb-20">
        <section>
          <FAQ />
        </section>
      </PageContainer>

      {/* ── Section 8 · Enterprise Contact ─────────── */}
      <PageContainer asChild>
        <section>
          <EnterpriseContact />
        </section>
      </PageContainer>
    </main>
  );
}
