import { createPortal } from 'react-dom';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { useEffect, useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Calendar, Clock, ChevronLeft, Link2, X, ChevronRight, ChevronDown, Tv, ExternalLink, Play, MapPin, PartyPopper, ShoppingBag, Ticket, Disc3, GraduationCap } from 'lucide-react';
import { getSchedule } from '@/api';
import { KakaoMap, MobileLightbox } from '@/components/common';
import { decodeHtmlEntities, formatFullDate, formatTime, formatXDateTimeWithTime } from '@/utils';
import Birthday from './Birthday';

/**
 * URL을 링크로 변환하는 함수
 */
function linkifyText(text) {
  if (!text) return null;

  // 해시태그 또는 URL 매칭
  const pattern = /(#[^\s#]+)|(https?:\/\/[^\s]+|(?:bit\.ly|youtu\.be|t\.co|goo\.gl|tinyurl\.com)\/[^\s]+)/gi;

  const parts = [];
  let lastIndex = 0;
  let match;

  while ((match = pattern.exec(text)) !== null) {
    if (match.index > lastIndex) {
      parts.push(text.slice(lastIndex, match.index));
    }

    const matched = match[0];

    if (matched.startsWith('#')) {
      // 해시태그
      const tag = matched.slice(1);
      parts.push(
        <a key={match.index} href={`https://x.com/hashtag/${encodeURIComponent(tag)}?src=hashtag_click`} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
          {matched}
        </a>
      );
    } else {
      // URL
      const href = matched.startsWith('http') ? matched : `https://${matched}`;
      parts.push(
        <a key={match.index} href={href} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline">
          {matched}
        </a>
      );
    }

    lastIndex = match.index + match[0].length;
  }

  if (lastIndex < text.length) {
    parts.push(text.slice(lastIndex));
  }

  return parts.length > 0 ? parts : text;
}

/**
 * 특수 일정 ID 파싱
 * @param {string} id - 일정 ID
 * @returns {object|null} { type, year, nameEn } 또는 null
 */
function parseSpecialId(id) {
  // birthday-{year}-{nameEn} 형식
  const birthdayMatch = id.match(/^birthday-(\d{4})-(.+)$/);
  if (birthdayMatch) {
    return { type: 'birthday', year: birthdayMatch[1], nameEn: birthdayMatch[2] };
  }

  // debut-{year} 형식
  const debutMatch = id.match(/^debut-(\d{4})$/);
  if (debutMatch) {
    return { type: 'debut', year: debutMatch[1] };
  }

  // anniversary-{year} 형식
  const anniversaryMatch = id.match(/^anniversary-(\d{4})$/);
  if (anniversaryMatch) {
    return { type: 'anniversary', year: anniversaryMatch[1] };
  }

  return null;
}

/**
 * 전체화면 시 자동 가로 회전 훅 (숏츠가 아닐 때만)
 */
function useFullscreenOrientation(isShorts) {
  useEffect(() => {
    if (isShorts) return;

    const handleFullscreenChange = async () => {
      const isFullscreen = !!document.fullscreenElement;

      if (isFullscreen) {
        try {
          if (screen.orientation && screen.orientation.lock) {
            await screen.orientation.lock('landscape');
          }
        } catch (e) {
          // 지원하지 않는 브라우저
        }
      } else {
        try {
          if (screen.orientation && screen.orientation.unlock) {
            screen.orientation.unlock();
          }
        } catch (e) {
          // 무시
        }
      }
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);

    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
      document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
    };
  }, [isShorts]);
}

/**
 * Mobile 예정 일정 Placeholder 컴포넌트
 */
function MobileScheduledPlaceholder({ bannerUrl }) {
  return (
    <div className="relative aspect-video bg-gradient-to-br from-gray-800 to-gray-900 rounded-xl overflow-hidden shadow-lg">
      {/* 배경: 배너 이미지 또는 패턴 */}
      {bannerUrl ? (
        <div
          className="absolute inset-0 bg-cover bg-center"
          style={{ backgroundImage: `url(${bannerUrl})` }}
        >
          <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent" />
        </div>
      ) : (
        <div className="absolute inset-0 opacity-5">
          <div className="absolute inset-0" style={{
            backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
          }} />
        </div>
      )}

      {/* 하단 텍스트 */}
      <div className="absolute bottom-0 left-0 right-0 p-4">
        <div className="flex items-center gap-2 text-white/90">
          <Clock size={16} className="text-amber-400" />
          <span className="text-base font-medium">업로드 예정</span>
        </div>
      </div>
    </div>
  );
}

/**
 * Mobile 유튜브 섹션
 */
function MobileYoutubeSection({ schedule }) {
  const videoId = schedule.videoId;
  const isShorts = schedule.videoType === 'shorts';
  const isScheduled = !videoId; // videoId가 없으면 예정 일정

  // 숏츠가 아닐 때만 가로 회전 (숏츠는 전체화면에서 세로 유지)
  useFullscreenOrientation(isShorts);
  const members = schedule.members || [];
  const isFullGroup = members.length === 5;

  return (
    <div className="space-y-4">
      {/* 영상 임베드 또는 예정 Placeholder */}
      <motion.div initial={{ opacity: 0, scale: 0.98 }} animate={{ opacity: 1, scale: 1 }} transition={{ delay: 0.1 }}>
        {isScheduled ? (
          <MobileScheduledPlaceholder bannerUrl={schedule.bannerUrl} />
        ) : (
          <div className="relative bg-gray-900 rounded-xl overflow-hidden shadow-lg aspect-video">
            <iframe
              src={`https://www.youtube.com/embed/${videoId}?rel=0`}
              title={schedule.title}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen; web-share"
              allowFullScreen
              className="absolute inset-0 w-full h-full"
            />
          </div>
        )}
      </motion.div>

      {/* 영상 정보 */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.2 }}
        className="bg-gradient-to-br from-gray-100 to-gray-200/80 rounded-xl p-4"
      >
        <div className="flex items-center gap-2 mb-3">
          <h1 className="font-bold text-gray-900 text-base leading-relaxed">{decodeHtmlEntities(schedule.title)}</h1>
          {isScheduled && (
            <span className="flex-shrink-0 px-2 py-0.5 bg-amber-100 text-amber-700 text-xs font-semibold rounded-full">
              예정
            </span>
          )}
        </div>

        {/* 메타 정보 */}
        <div className={`flex flex-wrap items-center gap-3 text-xs text-gray-500 ${members.length > 0 || !isScheduled ? 'mb-3' : ''}`}>
          <div className="flex items-center gap-1">
            <Calendar size={12} />
            <span>{formatXDateTimeWithTime(schedule.date, schedule.time)}</span>
          </div>
          {schedule.channelName && (
            <div className="flex items-center gap-1">
              <Link2 size={12} />
              <span>{schedule.channelName}</span>
            </div>
          )}
        </div>

        {/* 멤버 목록 */}
        {members.length > 0 && (
          <div className="flex flex-wrap gap-1.5 mb-4">
            {isFullGroup ? (
              <span className="px-2.5 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full">
                프로미스나인
              </span>
            ) : (
              members.map((member) => (
                <span key={member.id} className="px-2.5 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full">
                  {member.name}
                </span>
              ))
            )}
          </div>
        )}

        {/* 유튜브에서 보기 버튼 (예정 일정이 아닐 때만) */}
        {!isScheduled && (
          <div className="pt-4 border-t border-gray-300/50">
            <a
              href={schedule.videoUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center justify-center gap-2 w-full py-3 bg-red-500 active:bg-red-600 text-white rounded-xl font-medium transition-colors"
            >
              <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
                <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
              </svg>
              YouTube에서 보기
            </a>
          </div>
        )}
      </motion.div>
    </div>
  );
}

/**
 * 카드 이미지 (로드 실패 시 fallback 아이콘 — 인스타 등 CDN 만료 대비)
 */
function CardImage({ src, className }) {
  const [error, setError] = useState(false);
  if (!src || error) {
    return (
      <div className={`${className} flex items-center justify-center bg-gray-100 text-gray-300`}>
        <svg className="w-7 h-7" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
          <rect x="3" y="3" width="18" height="18" rx="2" />
          <circle cx="8.5" cy="8.5" r="1.5" />
          <path d="M21 15l-5-5L5 21" />
        </svg>
      </div>
    );
  }
  return <img src={src} alt="" className={`${className} object-cover bg-gray-100`} onError={() => setError(true)} />;
}

/**
 * Mobile X(트위터) 섹션
 */
function MobileXSection({ schedule }) {
  const profile = schedule.profile;
  const username = profile?.username || 'realfromis_9';
  const displayName = profile?.displayName || username;
  const avatarUrl = profile?.avatarUrl;

  // 라이트박스 상태
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxIndex, setLightboxIndex] = useState(0);
  const historyPushedRef = useRef(false);

  const openLightbox = (index) => {
    setLightboxIndex(index);
    setLightboxOpen(true);
    window.history.pushState({ lightbox: true }, '');
    historyPushedRef.current = true;
  };

  const closeLightbox = () => {
    setLightboxOpen(false);
    if (historyPushedRef.current) {
      historyPushedRef.current = false;
      window.history.back();
    }
  };

  const goToPrev = () => {
    if (schedule.imageUrls?.length > 1) {
      setLightboxIndex((lightboxIndex - 1 + schedule.imageUrls.length) % schedule.imageUrls.length);
    }
  };

  const goToNext = () => {
    if (schedule.imageUrls?.length > 1) {
      setLightboxIndex((lightboxIndex + 1) % schedule.imageUrls.length);
    }
  };

  // 라이트박스 열릴 때 body 스크롤 방지
  useEffect(() => {
    if (lightboxOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [lightboxOpen]);

  // 뒤로가기 처리 (하드웨어 백버튼)
  useEffect(() => {
    const handlePopState = () => {
      if (lightboxOpen) {
        historyPushedRef.current = false;
        setLightboxOpen(false);
      }
    };

    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, [lightboxOpen]);


  return (
    <>
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
        className="bg-white rounded-xl border border-gray-200 overflow-hidden"
      >
        {/* 헤더 */}
        <div className="p-4 pb-0">
          <div className="flex items-center gap-3">
            {avatarUrl ? (
              <img src={avatarUrl} alt={displayName} className="w-10 h-10 rounded-full object-cover" />
            ) : (
              <div className="w-10 h-10 rounded-full bg-gradient-to-br from-gray-700 to-gray-900 flex items-center justify-center">
                <span className="text-white font-bold">{displayName.charAt(0).toUpperCase()}</span>
              </div>
            )}
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-1.5">
                <span className="font-bold text-gray-900 text-sm truncate">{displayName}</span>
                <svg className="w-4 h-4 text-blue-500 flex-shrink-0" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M22.25 12c0-1.43-.88-2.67-2.19-3.34.46-1.39.2-2.9-.81-3.91s-2.52-1.27-3.91-.81c-.66-1.31-1.91-2.19-3.34-2.19s-2.67.88-3.34 2.19c-1.39-.46-2.9-.2-3.91.81s-1.27 2.52-.81 3.91C2.63 9.33 1.75 10.57 1.75 12s.88 2.67 2.19 3.34c-.46 1.39-.2 2.9.81 3.91s2.52 1.27 3.91.81c.66 1.31 1.91 2.19 3.34 2.19s2.67-.88 3.34-2.19c1.39.46 2.9.2 3.91-.81s1.27-2.52.81-3.91c1.31-.67 2.19-1.91 2.19-3.34zm-11.07 4.57l-3.84-3.84 1.27-1.27 2.57 2.57 5.39-5.39 1.27 1.27-6.66 6.66z" />
                </svg>
              </div>
              <span className="text-xs text-gray-500 -mt-0.5 block">@{username}</span>
            </div>
          </div>
        </div>

        {/* 본문 */}
        <div className="p-4">
          <p className="text-gray-900 text-[15px] leading-relaxed whitespace-pre-wrap">
            {linkifyText(decodeHtmlEntities(schedule.content || schedule.title))}
          </p>
        </div>

        {/* 이미지 */}
        {schedule.imageUrls?.length > 0 && (
          <div className="px-4 pb-3">
            {schedule.imageUrls.length === 1 ? (
              <img
                src={schedule.imageUrls[0]}
                alt=""
                className="w-full rounded-xl border border-gray-100 cursor-pointer active:opacity-80 transition-opacity"
                onClick={() => openLightbox(0)}
              />
            ) : (
              <div className="grid gap-1 rounded-xl overflow-hidden border border-gray-100 grid-cols-2">
                {schedule.imageUrls.slice(0, 4).map((url, i) => (
                  <img
                    key={i}
                    src={url}
                    alt=""
                    className={`w-full object-cover cursor-pointer active:opacity-80 transition-opacity ${
                      schedule.imageUrls.length === 3 && i === 0 ? 'row-span-2 h-full' : 'aspect-square'
                    }`}
                    onClick={() => openLightbox(i)}
                  />
                ))}
              </div>
            )}
          </div>
        )}

        {/* 영상 썸네일 (재생 버튼 → 원본 트윗으로 이동) */}
        {schedule.videoThumbnails?.length > 0 && (
          <div className="px-4 pb-3 space-y-2">
            {schedule.videoThumbnails.map((url, i) => (
              <a
                key={i}
                href={schedule.postUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="relative block rounded-xl overflow-hidden border border-gray-100"
              >
                <img src={url} alt="" className="w-full object-cover" />
                <div className="absolute inset-0 flex items-center justify-center bg-black/10">
                  <div className="w-14 h-14 rounded-full bg-black/60 flex items-center justify-center">
                    <svg className="w-6 h-6 text-white ml-0.5" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M8 5v14l11-7z" />
                    </svg>
                  </div>
                </div>
                {/* 외부(X) 재생 표시 배지 */}
                <div className="absolute bottom-2.5 right-2.5 flex items-center gap-1 px-2 py-1 rounded-full bg-black/70 text-white text-[11px] font-medium backdrop-blur-sm">
                  <svg className="w-2.5 h-2.5" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                  </svg>
                  X에서 재생
                </div>
              </a>
            ))}
          </div>
        )}

        {/* 링크 미리보기 카드 (Open Graph) — 자체 이미지/영상이 있으면 숨김 */}
        {schedule.card?.url && !(schedule.videoThumbnails?.length > 0) && !(schedule.imageUrls?.length > 0) && (
          <div className="px-4 pb-3">
            <a
              href={schedule.card.url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-stretch rounded-xl border border-gray-200 overflow-hidden active:bg-gray-50 transition-colors"
            >
              {schedule.card.image && (
                <CardImage src={schedule.card.image} className="w-24 flex-shrink-0" />
              )}
              <div className="flex-1 min-w-0 p-2.5 flex flex-col justify-center">
                {schedule.card.destination && (
                  <p className="text-[11px] text-gray-400 mb-0.5">{schedule.card.destination}</p>
                )}
                {schedule.card.title && (
                  <p className="text-sm font-medium text-gray-900 line-clamp-2">
                    {decodeHtmlEntities(schedule.card.title)}
                  </p>
                )}
                {schedule.card.description && (
                  <p className="text-xs text-gray-500 line-clamp-2 mt-0.5">
                    {decodeHtmlEntities(schedule.card.description)}
                  </p>
                )}
              </div>
            </a>
          </div>
        )}

        {/* 날짜/시간 */}
        <div className="px-4 py-3 border-t border-gray-100">
          <span className="text-gray-500 text-sm">{formatXDateTimeWithTime(schedule.date, schedule.time)}</span>
        </div>

        {/* X에서 보기 버튼 */}
        <div className="px-4 py-3 border-t border-gray-100 bg-gray-50/50">
          <a
            href={schedule.postUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center justify-center gap-2 w-full py-2.5 bg-gray-900 active:bg-black text-white rounded-full font-medium transition-colors"
          >
            <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
              <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
            </svg>
            X에서 보기
          </a>
        </div>
      </motion.div>

      {/* 모바일 라이트박스 */}
      <AnimatePresence>
        {lightboxOpen && schedule.imageUrls?.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black z-50 flex items-center justify-center"
            onClick={closeLightbox}
          >
            <button className="absolute top-4 right-4 p-2 text-white/70 z-10" onClick={closeLightbox}>
              <X size={28} />
            </button>

            <motion.img
              key={lightboxIndex}
              src={schedule.imageUrls[lightboxIndex]}
              alt=""
              className="max-w-full max-h-full object-contain"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              onClick={(e) => e.stopPropagation()}
            />

            {schedule.imageUrls.length > 1 && (
              <>
                <button
                  className="absolute left-2 top-1/2 -translate-y-1/2 p-2 text-white/70"
                  onClick={(e) => {
                    e.stopPropagation();
                    goToPrev();
                  }}
                >
                  <ChevronLeft size={32} />
                </button>
                <button
                  className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-white/70"
                  onClick={(e) => {
                    e.stopPropagation();
                    goToNext();
                  }}
                >
                  <ChevronRight size={32} />
                </button>
              </>
            )}

            {schedule.imageUrls.length > 1 && (
              <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex gap-2">
                {schedule.imageUrls.map((_, i) => (
                  <button
                    key={i}
                    className={`w-2 h-2 rounded-full transition-colors ${i === lightboxIndex ? 'bg-white' : 'bg-white/40'}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      setLightboxIndex(i);
                    }}
                  />
                ))}
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

/**
 * Mobile 행사 섹션 (학교 행사 등)
 */
function MobileEventSection({ schedule }) {
  const members = schedule.members || [];
  const isFullGroup = members.length === 5;
  const posters = schedule.posters || [];
  const postUrls = schedule.postUrls || [];
  const venue = schedule.venue || null;
  const isUniversity = schedule.subtype === 'university';
  const typeLabel = isUniversity ? '대학 축제' : (schedule.category?.name || '행사');
  const ACCENT = '#f59e0b';
  const kakaoMapUrl = venue && venue.lat && venue.lng
    ? `https://map.kakao.com/link/map/${encodeURIComponent(venue.name)},${venue.lat},${venue.lng}`
    : null;
  const [mapOpen, setMapOpen] = useState(false);
  const [lightbox, setLightbox] = useState({ open: false, index: 0 });
  const lightboxImages = posters.map((p) => p.originalUrl || p.mediumUrl);
  const openLightbox = (index) => {
    setLightbox({ open: true, index });
    window.history.pushState({ lightbox: true }, '');
  };
  const linkLabel = (url) => {
    try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return url; }
  };
  const titleShadow = { textShadow: '0 2px 12px rgba(120,53,15,0.45), 0 1px 2px rgba(120,53,15,0.35)' };
  const textShadow = { textShadow: '0 1px 6px rgba(120,53,15,0.4)' };

  // 포스터 패럴랙스 + 페이드 (스크롤 시 천천히 따라오며 흐려짐)
  const posterRef = useRef(null);
  useEffect(() => {
    if (posters.length === 0) return;
    const container = document.querySelector('.mobile-content');
    if (!container) return;
    const onScroll = () => {
      const el = posterRef.current;
      if (!el) return;
      const y = container.scrollTop;
      const fadeDist = 320;
      el.style.transform = `translateY(${(y * 0.4).toFixed(1)}px) scale(${(1 - Math.min(y, fadeDist) / fadeDist * 0.06).toFixed(3)})`;
      el.style.opacity = String(Math.max(0, 1 - y / fadeDist));
    };
    onScroll();
    container.addEventListener('scroll', onScroll, { passive: true });
    return () => container.removeEventListener('scroll', onScroll);
  }, [posters.length]);

  return (
    <div className="space-y-3">
      {/* 포스터 (크게, 분리) — 패럴랙스/페이드 */}
      {posters.length > 0 && (
        <button ref={posterRef} type="button" onClick={() => openLightbox(0)}
          className="block w-full rounded-2xl overflow-hidden shadow-lg origin-top"
          style={{ willChange: 'transform, opacity' }}>
          <img src={posters[0].mediumUrl || posters[0].originalUrl} alt={schedule.title} className="w-full h-auto object-cover" />
        </button>
      )}

      {/* 정보 카드 (그라데이션) */}
      <div className="relative rounded-2xl overflow-hidden shadow-lg">
        <div className="absolute inset-0" style={{ background: 'linear-gradient(150deg, #fcd34d 0%, #f59e0b 52%, #d97706 100%)' }} />
        <div className="absolute -top-10 -right-8 w-44 h-44 rounded-full bg-amber-200/40 blur-3xl" />
        <div className="absolute -bottom-12 -left-8 w-48 h-48 rounded-full bg-yellow-100/30 blur-3xl" />
        <PartyPopper className="absolute -bottom-3 right-3 text-white/10" size={120} strokeWidth={1} />

        <div className="relative p-5 text-white">
          <div className="flex items-center gap-1.5 mb-3 flex-wrap">
            <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-white text-amber-700 shadow-sm">
              <PartyPopper size={11} />
              {typeLabel}
            </span>
            {isUniversity && schedule.schoolName && (
              <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-white/90 text-amber-700 shadow-sm">
                <GraduationCap size={11} />
                {schedule.schoolName}
              </span>
            )}
          </div>

          <h1 className="text-xl font-black leading-snug tracking-tight mb-3" style={titleShadow}>
            {decodeHtmlEntities(schedule.title)}
          </h1>

          <div className="space-y-1.5">
            <div className="flex items-center gap-2">
              <Calendar size={15} className="text-amber-100 flex-shrink-0" />
              <span className="text-[15px] font-bold" style={textShadow}>{formatFullDate(schedule.date)}{schedule.time && ` · ${formatTime(schedule.time)}`}</span>
            </div>
            {venue && (
              <button type="button" onClick={() => venue.lat && venue.lng && setMapOpen(true)}
                className="flex items-center gap-2 max-w-full">
                <MapPin size={15} className="text-amber-100 flex-shrink-0" />
                <span className="text-[15px] font-bold truncate" style={textShadow}>{venue.name}</span>
                {venue.lat && venue.lng && <ChevronRight size={14} className="text-white/55 flex-shrink-0" />}
              </button>
            )}
          </div>

          {members.length > 0 && (
            <div className="flex flex-wrap gap-1.5 mt-3">
              {isFullGroup ? (
                <span className="px-2.5 py-1 rounded-full text-[11px] font-bold bg-white/90 text-amber-700 shadow-sm">프로미스나인</span>
              ) : (
                members.map((m) => (
                  <span key={m.id} className="px-2.5 py-1 rounded-full text-[11px] font-bold bg-white/90 text-amber-700 shadow-sm">{m.name}</span>
                ))
              )}
            </div>
          )}

          {/* 관련 링크 */}
          {postUrls.length > 0 && (
            <div className="flex flex-wrap items-center gap-1.5 mt-4 pt-3 border-t border-white/25">
              <span className="inline-flex items-center gap-1 text-xs font-semibold text-amber-50">
                <Link2 size={13} />링크
              </span>
              {postUrls.map((url, idx) => (
                <a key={idx} href={url} target="_blank" rel="noopener noreferrer"
                  className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-white/90 text-amber-700 shadow-sm active:bg-white">
                  {linkLabel(url)}<ExternalLink size={11} />
                </a>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 추가 포스터 */}
      {posters.length > 1 && (
        <div className="grid grid-cols-4 gap-1.5">
          {posters.slice(1).map((p, idx) => (
            <button key={p.id} type="button" onClick={() => openLightbox(idx + 1)}
              className="block aspect-square rounded-md overflow-hidden border border-gray-100">
              <img src={p.thumbUrl || p.mediumUrl} alt="" className="w-full h-full object-cover" />
            </button>
          ))}
        </div>
      )}

      {/* 장소 지도 바텀시트 */}
      {createPortal(
        <AnimatePresence>
          {mapOpen && venue && (
            <div className="fixed inset-0 z-[60] flex items-end">
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                className="absolute inset-0 bg-black/50" onClick={() => setMapOpen(false)} />
              <motion.div initial={{ y: '100%' }} animate={{ y: 0 }} exit={{ y: '100%' }}
                transition={{ type: 'spring', damping: 30, stiffness: 300 }}
                className="relative w-full bg-white rounded-t-3xl p-4">
                <div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />
                <div className="flex items-start gap-2 mb-3 px-1">
                  <MapPin size={16} className="text-amber-500 mt-0.5 flex-shrink-0" />
                  <div>
                    <p className="text-sm font-bold text-gray-900">{venue.name}</p>
                    {venue.address && <p className="text-xs text-gray-500 mt-0.5">{venue.address}</p>}
                  </div>
                </div>
                <KakaoMap lat={Number(venue.lat)} lng={Number(venue.lng)} name={venue.name} className="w-full h-56 rounded-2xl overflow-hidden border border-gray-100" />
                {kakaoMapUrl && (
                  <a href={kakaoMapUrl} target="_blank" rel="noopener noreferrer"
                    className="mt-3 flex items-center justify-center gap-1.5 py-3 rounded-xl text-sm font-semibold text-white"
                    style={{ backgroundColor: ACCENT }}>
                    카카오맵에서 길찾기<ExternalLink size={14} />
                  </a>
                )}
              </motion.div>
            </div>
          )}
        </AnimatePresence>,
        document.body
      )}

      {/* Lightbox */}
      <MobileLightbox
        images={lightboxImages}
        currentIndex={lightbox.index}
        isOpen={lightbox.open}
        onClose={() => setLightbox((prev) => ({ ...prev, open: false }))}
        onIndexChange={(index) => setLightbox((prev) => ({ ...prev, index }))}
        showCounter={posters.length > 1}
        showDownload
      />
    </div>
  );
}

/**
 * Mobile 예능 섹션
 */
function MobileVarietySection({ schedule }) {
  const members = schedule.members || [];
  const isFullGroup = members.length === 5;
  const hasThumbnail = !!schedule.thumbnailUrl;
  const hasReplayUrl = !!schedule.replayUrl;
  const isYoutubeReplay = hasReplayUrl && /youtu\.?be/i.test(schedule.replayUrl);
  const categoryColor = schedule.category?.color || '#06b6d4';

  return (
    <div className="space-y-3">
      {/* 썸네일 카드 */}
      <div className="rounded-xl overflow-hidden shadow-sm h-52 relative">
        {hasThumbnail ? (
          <>
            {/* 블러 배경 */}
            <img
              src={schedule.thumbnailUrl}
              alt=""
              className="absolute inset-0 w-full h-full object-cover scale-110 blur-2xl opacity-60"
            />
            {/* 메인 이미지 */}
            <img
              src={schedule.thumbnailUrl}
              alt={schedule.title}
              className="relative w-full h-full object-contain"
            />
          </>
        ) : (
          <div
            className="w-full h-full flex items-center justify-center"
            style={{ backgroundColor: `${categoryColor}10` }}
          >
            <Tv size={36} style={{ color: categoryColor }} strokeWidth={1.5} />
          </div>
        )}
      </div>

      {/* 정보 카드 */}
      <div className="bg-white rounded-xl shadow-sm p-4">
        {/* 방송사 + 날짜 */}
        <div className="flex items-center gap-2 mb-2">
          {schedule.broadcaster && (
            <span
              className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold rounded-md"
              style={{ backgroundColor: `${categoryColor}15`, color: categoryColor }}
            >
              <Tv size={10} />
              {schedule.broadcaster}
            </span>
          )}
          <span className="text-xs text-gray-400">
            {formatFullDate(schedule.date)}
            {schedule.time && ` · ${formatTime(schedule.time)}`}
          </span>
        </div>

        {/* 제목 */}
        <h1 className="font-bold text-gray-900 text-base leading-snug mb-3">
          {decodeHtmlEntities(schedule.title)}
        </h1>

        {/* 멤버 */}
        {members.length > 0 && (
          <div className="flex flex-wrap gap-1.5 mb-3">
            {isFullGroup ? (
              <span className="px-2.5 py-0.5 bg-primary/10 text-primary text-xs font-medium rounded-full">
                프로미스나인
              </span>
            ) : (
              members.map((member) => (
                <span key={member.id} className="px-2.5 py-0.5 bg-primary/10 text-primary text-xs font-medium rounded-full">
                  {member.name}
                </span>
              ))
            )}
          </div>
        )}

        {/* 다시보기 */}
        {hasReplayUrl && (
          <div className="pt-3 border-t border-gray-100">
            <a
              href={schedule.replayUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-gray-900 text-white text-xs font-medium rounded-full"
            >
              {isYoutubeReplay ? <Play size={12} fill="currentColor" /> : <ExternalLink size={12} />}
              다시보기
            </a>
          </div>
        )}
      </div>
    </div>
  );
}

/**
 * Mobile 콘서트 섹션
 */
function MobileConcertSection({ schedule }) {
  const navigate = useNavigate();
  const poster = schedule.poster || null;
  const venue = schedule.venue || null;
  const setlist = schedule.setlist || [];
  const merchandise = schedule.merchandise || [];
  const otherRounds = schedule.otherRounds || [];
  const activeCount = schedule.activeMemberCount || 5;
  const ACCENT = '#f97316';
  const COLLAPSE_COUNT = 5;
  const kakaoMapUrl = venue && venue.lat && venue.lng
    ? `https://map.kakao.com/link/map/${encodeURIComponent(venue.name)},${venue.lat},${venue.lng}`
    : null;
  const isUnit = (m) => m.length > 0 && m.length < activeCount;
  const posterImg = poster ? (poster.mediumUrl || poster.originalUrl) : null;

  const [mapOpen, setMapOpen] = useState(false);
  const [roundsOpen, setRoundsOpen] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [lightbox, setLightbox] = useState({ open: false, images: [], index: 0 });
  const openLightbox = (images, index) => {
    setLightbox({ open: true, images, index });
    window.history.pushState({ lightbox: true }, '');
  };

  // 세트리스트 높이 (1열, 행 52px) — 펼치기/접기 애니메이션
  const ROW_H = 52;
  const collapsible = setlist.length > COLLAPSE_COUNT;
  const collapsedHeight = COLLAPSE_COUNT * ROW_H;
  const fullHeight = setlist.length * ROW_H;

  const days = ['일', '월', '화', '수', '목', '금', '토'];
  const shortDate = (ds) => {
    const d = new Date(ds);
    return `${d.getMonth() + 1}.${d.getDate()} (${days[d.getDay()]})`;
  };
  const allRounds = [
    { scheduleId: schedule.id, date: schedule.date, time: schedule.time, current: true },
    ...otherRounds.map((r) => ({ ...r, current: false })),
  ].sort((a, b) => a.date.localeCompare(b.date));
  const hasMultiRounds = allRounds.length > 1;
  const currentRoundNum = allRounds.findIndex((r) => r.current) + 1;

  return (
    <div className="space-y-3">
      {/* 히어로 (모바일 전용 세로형) */}
      <div className="relative rounded-2xl overflow-hidden shadow-lg">
        {posterImg ? (
          <div className="absolute inset-0">
            <img src={posterImg} alt="" className="w-full h-full object-cover scale-110 blur-xl opacity-80" />
            <div className="absolute inset-0" style={{ background: 'linear-gradient(180deg, rgba(15,11,8,0.45) 0%, rgba(15,11,8,0.72) 58%, rgba(15,11,8,0.9) 100%)' }} />
          </div>
        ) : (
          <div className="absolute inset-0" style={{ background: 'linear-gradient(180deg, #1a1410 0%, #3a1d0c 100%)' }} />
        )}

        <div className="relative px-5 pt-7 pb-7 text-white flex flex-col items-center text-center">
          {/* 포스터 (중앙, 크게) */}
          <button
            type="button"
            onClick={() => posterImg && openLightbox([poster.originalUrl || poster.mediumUrl], 0)}
            className="w-52 mb-5"
          >
            {posterImg ? (
              <span className="block rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/15">
                <img src={posterImg} alt={schedule.title} className="w-full h-auto object-cover" />
              </span>
            ) : (
              <span className="flex w-full aspect-[3/4] rounded-2xl bg-white/5 ring-1 ring-white/10 items-center justify-center">
                <Ticket size={48} className="text-white/30" strokeWidth={1.5} />
              </span>
            )}
          </button>

          {/* 제목 */}
          <h1 className="text-xl font-black leading-snug tracking-tight mb-4 px-2">
            {decodeHtmlEntities(schedule.title)}
          </h1>

          {/* 날짜(+회차) · 장소 */}
          <div className="flex flex-col items-center gap-2.5 text-white">
            <div className="flex items-center gap-2">
              <Calendar size={16} className="text-white/55" />
              <span className="text-base font-bold">{shortDate(schedule.date)}{schedule.time && ` · ${formatTime(schedule.time)}`}</span>
              {hasMultiRounds && (
                <button type="button" onClick={() => setRoundsOpen(true)}
                  className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-white/15 text-xs font-bold border border-white/20">
                  {currentRoundNum}회차<ChevronDown size={12} />
                </button>
              )}
            </div>
            {venue && (
              <button
                type="button"
                onClick={() => venue.lat && venue.lng && setMapOpen(true)}
                className="flex items-center gap-2 max-w-full"
              >
                <MapPin size={16} className="text-white/55 flex-shrink-0" />
                <span className="text-base font-bold truncate">{venue.name}</span>
                {venue.lat && venue.lng && <ChevronRight size={15} className="text-white/45 flex-shrink-0" />}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* 세트리스트 */}
      {setlist.length > 0 && (
        <div className="bg-white rounded-xl shadow-sm p-4">
          <div className="flex items-center gap-1.5 mb-3">
            <Disc3 size={16} style={{ color: ACCENT }} />
            <h2 className="text-sm font-bold text-gray-900">세트리스트</h2>
            <span className="text-xs text-gray-400 ml-auto">{setlist.length}곡</span>
          </div>
          <motion.div
            initial={false}
            animate={{ height: collapsible && !expanded ? collapsedHeight : fullHeight }}
            transition={{ duration: 0.4, ease: [0.4, 0, 0.2, 1] }}
            className="overflow-hidden"
          >
            {setlist.map((song, idx) => (
              <div key={song.id} className="flex items-center gap-2.5 h-[52px] px-1">
                <span className="flex-shrink-0 w-7 text-right text-lg font-black tabular-nums text-gray-200 leading-none">
                  {String(idx + 1).padStart(2, '0')}
                </span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-900 truncate">{song.songName}</p>
                  {song.albumName && <p className="text-[11px] text-gray-400 truncate mt-0.5">{song.albumName}</p>}
                </div>
                {isUnit(song.members) && (
                  <div className="flex-shrink-0 flex flex-wrap justify-end gap-1 max-w-[110px]">
                    {song.members.map((m) => (
                      <span key={m.id} className="px-2 py-0.5 rounded-full text-[11px] font-semibold bg-orange-100 text-orange-700">{m.name}</span>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </motion.div>
          {collapsible && (
            <button
              type="button"
              onClick={() => setExpanded((v) => !v)}
              className="mt-2 w-full flex items-center justify-center gap-1 py-2.5 rounded-lg text-xs font-semibold text-gray-500 bg-gray-50 active:bg-gray-100"
            >
              {expanded ? '접기' : `${setlist.length - COLLAPSE_COUNT}곡 더 보기`}
              <ChevronDown size={14} className={`transition-transform ${expanded ? 'rotate-180' : ''}`} />
            </button>
          )}
        </div>
      )}

      {/* 굿즈 (원본 비율 유지, masonry) */}
      {merchandise.length > 0 && (
        <div className="bg-white rounded-xl shadow-sm p-4">
          <div className="flex items-center gap-1.5 mb-3">
            <ShoppingBag size={16} style={{ color: ACCENT }} />
            <h2 className="text-sm font-bold text-gray-900">MD</h2>
            <span className="text-xs text-gray-400">{merchandise.length}</span>
          </div>
          <div className="columns-2 gap-2">
            {merchandise.map((md, idx) => (
              <button key={md.id} type="button"
                onClick={() => openLightbox(merchandise.map((x) => x.originalUrl || x.mediumUrl), idx)}
                className="block w-full mb-2 break-inside-avoid rounded-lg overflow-hidden border border-gray-100">
                <img src={md.mediumUrl || md.thumbUrl} alt="" className="w-full h-auto" />
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 회차 선택 바텀시트 */}
      {createPortal(
        <AnimatePresence>
        {roundsOpen && hasMultiRounds && (
          <div className="fixed inset-0 z-[60] flex items-end">
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              className="absolute inset-0 bg-black/50" onClick={() => setRoundsOpen(false)} />
            <motion.div
              initial={{ y: '100%' }} animate={{ y: 0 }} exit={{ y: '100%' }}
              transition={{ type: 'spring', damping: 30, stiffness: 300 }}
              className="relative w-full bg-white rounded-t-3xl p-4"
            >
              <div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />
              <p className="text-sm font-bold text-gray-900 mb-3 px-1">공연 일정</p>
              <div className="space-y-1">
                {allRounds.map((round, i) => (
                  round.current ? (
                    <div key={round.scheduleId} className="flex items-center justify-between px-3 py-3 rounded-xl font-bold"
                      style={{ backgroundColor: `${ACCENT}14`, color: '#9a3412' }}>
                      <span className="flex items-center gap-2.5">
                        <span className="text-xs font-bold tabular-nums w-9" style={{ color: ACCENT }}>{i + 1}회차</span>
                        {shortDate(round.date)}
                      </span>
                      {round.time && <span className="text-xs">{formatTime(round.time)}</span>}
                    </div>
                  ) : (
                    <button key={round.scheduleId} type="button"
                      onClick={() => { setRoundsOpen(false); navigate(`/schedule/${round.scheduleId}`, { replace: true }); }}
                      className="w-full flex items-center justify-between px-3 py-3 rounded-xl text-gray-600 active:bg-gray-50">
                      <span className="flex items-center gap-2.5">
                        <span className="text-xs font-bold tabular-nums w-9 text-gray-400">{i + 1}회차</span>
                        {shortDate(round.date)}
                      </span>
                      {round.time && <span className="text-xs text-gray-400">{formatTime(round.time)}</span>}
                    </button>
                  )
                ))}
              </div>
            </motion.div>
          </div>
        )}
        </AnimatePresence>,
        document.body
      )}

      {/* 장소 지도 다이얼로그 */}
      {createPortal(
        <AnimatePresence>
        {mapOpen && venue && (
          <div className="fixed inset-0 z-[60] flex items-end">
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              className="absolute inset-0 bg-black/50" onClick={() => setMapOpen(false)} />
            <motion.div
              initial={{ y: '100%' }} animate={{ y: 0 }} exit={{ y: '100%' }}
              transition={{ type: 'spring', damping: 30, stiffness: 300 }}
              className="relative w-full bg-white rounded-t-3xl p-4"
            >
              <div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />
              <div className="flex items-start gap-2 mb-3 px-1">
                <MapPin size={16} style={{ color: ACCENT }} className="mt-0.5 flex-shrink-0" />
                <div>
                  <p className="text-sm font-bold text-gray-900">{venue.name}</p>
                  {venue.address && <p className="text-xs text-gray-500 mt-0.5">{venue.address}</p>}
                </div>
              </div>
              <KakaoMap lat={Number(venue.lat)} lng={Number(venue.lng)} name={venue.name} className="w-full h-56 rounded-2xl overflow-hidden border border-gray-100" />
              {kakaoMapUrl && (
                <a href={kakaoMapUrl} target="_blank" rel="noopener noreferrer"
                  className="mt-3 flex items-center justify-center gap-1.5 py-3 rounded-xl text-sm font-semibold text-white"
                  style={{ backgroundColor: ACCENT }}>
                  카카오맵에서 길찾기<ExternalLink size={14} />
                </a>
              )}
            </motion.div>
          </div>
        )}
        </AnimatePresence>,
        document.body
      )}

      {/* Lightbox */}
      <MobileLightbox
        images={lightbox.images}
        currentIndex={lightbox.index}
        isOpen={lightbox.open}
        onClose={() => setLightbox((prev) => ({ ...prev, open: false }))}
        onIndexChange={(index) => setLightbox((prev) => ({ ...prev, index }))}
        showCounter={lightbox.images.length > 1}
        showDownload
      />
    </div>
  );
}

/**
 * Mobile 기본 섹션
 */
function MobileDefaultSection({ schedule }) {
  return (
    <div className="bg-white rounded-xl p-4 shadow-sm">
      <h1 className="font-bold text-gray-900 text-base mb-3">{decodeHtmlEntities(schedule.title)}</h1>
      <div className="flex items-center gap-3 text-xs text-gray-500">
        <div className="flex items-center gap-1">
          <Calendar size={12} />
          <span>{formatFullDate(schedule.date)}</span>
        </div>
        {schedule.time && (
          <div className="flex items-center gap-1">
            <Clock size={12} />
            <span>{formatTime(schedule.time)}</span>
          </div>
        )}
      </div>
      {schedule.description && (
        <p className="mt-3 text-sm text-gray-600 whitespace-pre-wrap">{decodeHtmlEntities(schedule.description)}</p>
      )}
    </div>
  );
}

/**
 * Mobile 일정 상세 페이지
 */
function MobileScheduleDetail() {
  const { id } = useParams();

  // 특수 일정 ID 체크
  const specialId = parseSpecialId(id);
  if (specialId?.type === 'birthday') {
    return <Birthday year={specialId.year} nameEn={specialId.nameEn} />;
  }

  // 모바일 레이아웃 활성화
  useEffect(() => {
    document.documentElement.classList.add('mobile-layout');
    return () => {
      document.documentElement.classList.remove('mobile-layout');
    };
  }, []);

  const {
    data: schedule,
    isLoading,
    error,
  } = useQuery({
    queryKey: ['schedule', id],
    queryFn: () => getSchedule(id),
    placeholderData: keepPreviousData,
    retry: false,
  });

  if (isLoading && !schedule) {
    return (
      <div className="mobile-layout-container bg-gray-50">
        <div className="mobile-content flex items-center justify-center">
          <div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
        </div>
      </div>
    );
  }

  if (error || !schedule) {
    return (
      <div className="mobile-layout-container bg-gradient-to-br from-gray-50 to-gray-100">
        <div className="mobile-content flex items-center justify-center px-6">
          <div className="text-center">
            <motion.div
              initial={{ opacity: 0, scale: 0.5 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.5, type: 'spring', stiffness: 100 }}
              className="mb-6"
            >
              <div className="w-24 h-24 mx-auto bg-gradient-to-br from-primary/10 to-primary/5 rounded-2xl flex items-center justify-center">
                <Calendar size={48} className="text-primary/40" />
              </div>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2, duration: 0.5 }}
              className="mb-6"
            >
              <h2 className="text-xl font-bold text-gray-800 mb-2">일정을 찾을 수 없습니다</h2>
              <p className="text-gray-500 text-sm leading-relaxed">
                요청하신 일정이 존재하지 않거나
                <br />
                삭제되었을 수 있습니다.
              </p>
            </motion.div>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4, duration: 0.5 }}
              className="flex justify-center gap-1.5 mb-8"
            >
              {[...Array(5)].map((_, i) => (
                <motion.div
                  key={i}
                  className="w-1.5 h-1.5 rounded-full bg-primary"
                  animate={{
                    y: [0, -6, 0],
                    opacity: [0.3, 1, 0.3],
                  }}
                  transition={{
                    duration: 1.2,
                    repeat: Infinity,
                    delay: i * 0.15,
                    ease: 'easeInOut',
                  }}
                />
              ))}
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5, duration: 0.5 }}
              className="flex flex-col gap-3"
            >
              <button
                onClick={() => window.history.back()}
                className="flex items-center justify-center gap-2 w-full px-6 py-3 border-2 border-primary text-primary rounded-full font-medium active:bg-primary active:text-white transition-colors"
              >
                <ChevronLeft size={18} />
                이전 페이지
              </button>
              <Link
                to="/schedule"
                className="flex items-center justify-center gap-2 w-full px-6 py-3 bg-gradient-to-r from-primary to-primary-dark text-white rounded-full font-medium active:opacity-90 transition-opacity"
              >
                <Calendar size={18} />
                일정 목록
              </Link>
            </motion.div>
          </div>
        </div>
      </div>
    );
  }

  // 카테고리별 섹션 렌더링
  const categoryName = schedule.category?.name;
  const renderCategorySection = () => {
    switch (categoryName) {
      case '유튜브':
        return <MobileYoutubeSection schedule={schedule} />;
      case 'X':
        return <MobileXSection schedule={schedule} />;
      case '예능':
        return <MobileVarietySection schedule={schedule} />;
      case '행사':
        return <MobileEventSection schedule={schedule} />;
      case '콘서트':
        return <MobileConcertSection schedule={schedule} />;
      default:
        return <MobileDefaultSection schedule={schedule} />;
    }
  };

  return (
    <div className="mobile-layout-container bg-gray-50">
      {/* 헤더 */}
      <div className="flex-shrink-0 bg-white border-b border-gray-100">
        <div className="flex items-center h-14 px-2">
          <button onClick={() => window.history.back()} className="p-2 -ml-0.5 rounded-lg active:bg-gray-100 text-gray-600">
            <ChevronLeft size={22} />
          </button>
          <span className="flex-1 text-center text-base font-bold" style={{ color: schedule.category?.color }}>
            {schedule.category?.name}
          </span>
          <div className="w-9" />
        </div>
      </div>

      {/* 메인 컨텐츠 */}
      <div className="mobile-content p-4">{renderCategorySection()}</div>
    </div>
  );
}

export default MobileScheduleDetail;
