/**
 * BrandAppliedPreview — 브랜드(컬러/타이포/로고)가 실제로 적용된 모습을
 * 인스타 포스트 + 유튜브 썸네일 두 가지 미니 mockup 으로 보여주는 컴포넌트.
 *
 * 외부 자산(병원 사진, 의사 사진 등) 없이 컬러+폰트+이니셜만으로 구성되어
 * 어느 병원이든 즉시 미리보기가 가능합니다.
 */
import { motion } from 'motion/react';
import { Heart, MessageCircle, Send, Bookmark, Play, Sparkles } from 'lucide-react';
import {
  InstagramFilled,
  YoutubeFilled,
} from '@/shared/icons/FilledIcons';
import type { BrandGuide } from '@/features/plan/types/plan';

interface BrandAppliedPreviewProps {
  data: BrandGuide;
  clinicName: string;
  /** 미리보기 헤드라인. 없으면 toneOfVoice 의 personality 첫 단어 + 병원명 조합 */
  headline?: string;
  /** 미리보기 태그라인. 없으면 communicationStyle 일부 */
  tagline?: string;
}

function getHeadingFont(data: BrandGuide): string | undefined {
  const heading = data.fonts.find(
    (f) =>
      f.usage.toLowerCase().includes('heading') ||
      f.usage.toLowerCase().includes('headline') ||
      f.weight.toLowerCase().includes('bold'),
  );
  return heading?.family ?? data.fonts[0]?.family;
}

function getBodyFont(data: BrandGuide): string | undefined {
  const body = data.fonts.find(
    (f) =>
      f.usage.toLowerCase().includes('body') ||
      f.usage.toLowerCase().includes('text'),
  );
  return body?.family ?? data.fonts[data.fonts.length - 1]?.family;
}

/** 첫 2자만 이니셜로 (한글이면 1자) */
function getInitial(name: string): string {
  const trimmed = name.trim();
  if (!trimmed) return '?';
  const isKorean = /[가-힣]/.test(trimmed[0]);
  return isKorean ? trimmed[0] : trimmed.slice(0, 2).toUpperCase();
}

/** hex → 텍스트가 흰색 vs 검정 어느 쪽이 더 잘 보일지 결정 */
function pickTextOn(hex: string): 'light' | 'dark' {
  const cleaned = hex.replace('#', '');
  if (cleaned.length !== 6) return 'light';
  const r = parseInt(cleaned.slice(0, 2), 16);
  const g = parseInt(cleaned.slice(2, 4), 16);
  const b = parseInt(cleaned.slice(4, 6), 16);
  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return luminance > 0.6 ? 'dark' : 'light';
}

export function BrandAppliedPreview({
  data,
  clinicName,
  headline,
  tagline,
}: BrandAppliedPreviewProps) {
  const primary = data.colors[0]?.hex ?? '#4F1DA1';
  const accent = data.colors[1]?.hex ?? '#6C5CE7';
  const tertiary = data.colors[2]?.hex ?? '#021341';
  const headingFont = getHeadingFont(data);
  const bodyFont = getBodyFont(data);
  const initial = getInitial(clinicName);

  const computedHeadline =
    headline ??
    `${data.toneOfVoice?.personality?.[0] ?? '자연스러운'}\n${clinicName}`;
  const computedTagline =
    tagline ?? data.toneOfVoice?.communicationStyle?.slice(0, 40) ?? `${clinicName} · 프리미엄 케어`;

  const onPrimary = pickTextOn(primary);

  return (
    <div>
      <h3 className="font-serif font-bold text-2xl text-brand-navy mb-2">
        Brand in Action
      </h3>
      <p className="text-sm text-slate-500 mb-5">
        등록된 컬러·타이포가 실제 콘텐츠에 적용됐을 때의 모습입니다.
      </p>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-2xl items-start">
        {/* ── Instagram Post Mockup ─────────────────────────── */}
        <motion.figure
          initial={{ opacity: 0, y: 12 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5 }}
          className="rounded-2xl border border-slate-200 bg-white overflow-hidden shadow-[3px_4px_18px_rgba(15,23,42,0.06)]"
        >
          {/* IG 헤더 */}
          <div className="flex items-center justify-between px-3 py-2 border-b border-slate-100">
            <div className="flex items-center gap-2">
              <div
                className="w-6 h-6 rounded-full flex items-center justify-center text-[9px] font-bold ring-1 ring-white"
                style={{
                  background: `linear-gradient(135deg, ${primary}, ${accent})`,
                  color: onPrimary === 'light' ? '#fff' : '#0A1128',
                }}
              >
                {initial}
              </div>
              <span className="text-[10px] font-semibold text-brand-navy">
                {clinicName.toLowerCase().replace(/\s+/g, '_')}
              </span>
            </div>
            <InstagramFilled size={12} />
          </div>

          {/* IG 본문 (1:1) */}
          <div
            className="relative aspect-square flex items-center justify-center px-4 overflow-hidden"
            style={{
              background: `radial-gradient(circle at 30% 20%, ${accent}, ${primary} 60%, ${tertiary})`,
            }}
          >
            <div
              className="absolute -top-12 -right-12 w-32 h-32 rounded-full blur-2xl opacity-30"
              style={{ backgroundColor: accent }}
              aria-hidden
            />
            <div
              className="absolute -bottom-10 -left-10 w-28 h-28 rounded-full blur-2xl opacity-20"
              style={{ backgroundColor: '#fff' }}
              aria-hidden
            />

            <div className="relative text-center max-w-[85%]">
              <p
                className={`text-[8px] uppercase tracking-[0.25em] mb-1.5 ${
                  onPrimary === 'light' ? 'text-white/70' : 'text-black/60'
                }`}
                style={{ fontFamily: bodyFont }}
              >
                {clinicName} · Story
              </p>
              <h4
                className={`text-lg font-bold leading-tight whitespace-pre-line ${
                  onPrimary === 'light' ? 'text-white' : 'text-brand-navy'
                }`}
                style={{ fontFamily: headingFont }}
              >
                {computedHeadline}
              </h4>
              <p
                className={`mt-2 text-[10px] leading-relaxed line-clamp-2 ${
                  onPrimary === 'light' ? 'text-white/85' : 'text-black/75'
                }`}
                style={{ fontFamily: bodyFont }}
              >
                {computedTagline}
              </p>
            </div>
          </div>

          {/* IG 액션바 */}
          <div className="flex items-center justify-between px-3 py-2">
            <div className="flex items-center gap-2 text-slate-700">
              <Heart size={14} />
              <MessageCircle size={14} />
              <Send size={14} />
            </div>
            <Bookmark size={14} className="text-slate-700" />
          </div>
          <figcaption className="px-3 pb-2 text-[9px] uppercase tracking-wider text-slate-400">
            Instagram Feed · 1:1
          </figcaption>
        </motion.figure>

        {/* ── YouTube Thumbnail Mockup ──────────────────────── */}
        <motion.figure
          initial={{ opacity: 0, y: 12 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5, delay: 0.1 }}
          className="rounded-2xl border border-slate-200 bg-white overflow-hidden shadow-[3px_4px_18px_rgba(15,23,42,0.06)]"
        >
          {/* 썸네일 (16:9) */}
          <div
            className="relative aspect-video flex items-end p-3 overflow-hidden"
            style={{
              background: `linear-gradient(135deg, ${primary} 0%, ${tertiary} 100%)`,
            }}
          >
            <div
              className="absolute top-0 right-0 w-40 h-40 rounded-full blur-3xl opacity-25"
              style={{ backgroundColor: accent }}
              aria-hidden
            />

            {/* 코너 브랜드 마크 */}
            <div className="absolute top-2 left-2 flex items-center gap-1.5">
              <div
                className="w-5 h-5 rounded flex items-center justify-center text-[8px] font-bold backdrop-blur"
                style={{
                  backgroundColor: 'rgba(255,255,255,0.15)',
                  color: '#fff',
                }}
              >
                {initial}
              </div>
              <span className="text-[8px] uppercase tracking-[0.2em] text-white/60 font-medium">
                {clinicName}
              </span>
            </div>

            <div className="absolute top-2 right-2 text-white/40">
              <Sparkles size={10} />
            </div>

            {/* 헤드라인 */}
            <div className="relative max-w-[85%]">
              <span
                className="inline-block text-[8px] uppercase tracking-[0.25em] text-white/60 mb-1"
                style={{ fontFamily: bodyFont }}
              >
                Episode 01
              </span>
              <h4
                className="text-white text-base font-bold leading-snug whitespace-pre-line"
                style={{ fontFamily: headingFont }}
              >
                {computedHeadline}
              </h4>
            </div>

            {/* Play 버튼 */}
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
              <div
                className="w-9 h-9 rounded-full flex items-center justify-center backdrop-blur"
                style={{ backgroundColor: 'rgba(255,255,255,0.25)' }}
              >
                <Play size={14} className="text-white fill-white ml-0.5" />
              </div>
            </div>

            <div className="absolute bottom-2 right-2 px-1 py-0.5 rounded text-[8px] font-medium text-white bg-black/60">
              03:24
            </div>
          </div>

          {/* 유튜브 메타 */}
          <div className="flex items-start gap-2 px-3 py-2">
            <div
              className="w-7 h-7 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0"
              style={{
                background: `linear-gradient(135deg, ${primary}, ${accent})`,
                color: '#fff',
              }}
            >
              {initial}
            </div>
            <div className="min-w-0 flex-1">
              <p
                className="text-xs font-semibold text-brand-navy line-clamp-2 leading-snug"
                style={{ fontFamily: headingFont }}
              >
                {computedHeadline.replace(/\n/g, ' · ')}
              </p>
              <div className="flex items-center gap-1 mt-0.5 text-[9px] text-slate-500">
                <YoutubeFilled size={9} />
                <span>{clinicName}</span>
                <span>·</span>
                <span>조회수 12K</span>
              </div>
            </div>
          </div>
          <figcaption className="px-3 pb-2 text-[9px] uppercase tracking-wider text-slate-400">
            YouTube Thumbnail · 16:9
          </figcaption>
        </motion.figure>
      </div>
    </div>
  );
}
