import { useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper/modules';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Calendar, Clock, MapPin, Link2, PartyPopper, ExternalLink,
  ChevronLeft, ChevronRight, GraduationCap, X,
} from 'lucide-react';
import 'swiper/css';
import 'swiper/css/navigation';
import { Lightbox, KakaoMap } from '@/components/common';
import { decodeHtmlEntities, formatFullDate, formatTime } from './utils';

const ACCENT = '#f59e0b';

/**
 * 행사(대학 축제 등) 일정 섹션 — 단일 히어로 통합 디자인
 */
function EventSection({ 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 kakaoMapUrl = venue && venue.lat && venue.lng
    ? `https://map.kakao.com/link/map/${encodeURIComponent(venue.name)},${venue.lat},${venue.lng}`
    : null;

  const [lightbox, setLightbox] = useState({ open: false, index: 0 });
  const [mapOpen, setMapOpen] = useState(false);
  const lightboxImages = posters.map((p) => p.originalUrl || p.mediumUrl);
  const openLightbox = (index) => setLightbox({ open: true, index });

  const linkLabel = (url) => {
    try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return url; }
  };

  // 골드 배경 위 텍스트 가독성/입체감용 그림자
  const titleShadow = { textShadow: '0 2px 14px 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)' };

  return (
    <div>
      {/* ===== 히어로 (모든 정보 통합) ===== */}
      <div className="relative rounded-[28px] overflow-hidden shadow-xl">
        {/* 골드 그라데이션 배경 */}
        <div className="absolute inset-0" style={{
          background: 'linear-gradient(130deg, #fcd34d 0%, #f59e0b 52%, #d97706 100%)',
        }} />
        <div className="absolute -top-16 -right-12 w-64 h-64 rounded-full bg-amber-200/40 blur-3xl" />
        <div className="absolute -bottom-20 -left-12 w-72 h-72 rounded-full bg-yellow-100/30 blur-3xl" />
        <PartyPopper className="absolute -bottom-6 right-6 text-white/10" size={200} strokeWidth={1} />

        <div className="relative flex gap-8 p-8 md:p-10">
          {/* 포스터 (있을 때만) */}
          {posters.length > 0 && (
            <div className="flex-shrink-0 w-[280px]">
              <div className="relative group rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/25">
                <Swiper
                  modules={[Navigation]}
                  navigation={posters.length > 1 ? { prevEl: '.fest-prev', nextEl: '.fest-next' } : false}
                  slidesPerView={1}
                  loop={posters.length > 1}
                  className="w-full"
                >
                  {posters.map((p, idx) => (
                    <SwiperSlide key={p.id}>
                      <button type="button" onClick={() => openLightbox(idx)} className="block w-full cursor-pointer">
                        <img src={p.mediumUrl || p.originalUrl} alt={`${schedule.title} 포스터 ${idx + 1}`} className="w-full h-auto object-cover" />
                      </button>
                    </SwiperSlide>
                  ))}
                </Swiper>
                {posters.length > 1 && (
                  <>
                    <button className="fest-prev absolute left-2 top-1/2 -translate-y-1/2 z-10 w-9 h-9 rounded-full bg-white/85 hover:bg-white shadow flex items-center justify-center text-gray-700 opacity-0 group-hover:opacity-100 transition-opacity" aria-label="이전 포스터">
                      <ChevronLeft size={18} />
                    </button>
                    <button className="fest-next absolute right-2 top-1/2 -translate-y-1/2 z-10 w-9 h-9 rounded-full bg-white/85 hover:bg-white shadow flex items-center justify-center text-gray-700 opacity-0 group-hover:opacity-100 transition-opacity" aria-label="다음 포스터">
                      <ChevronRight size={18} />
                    </button>
                    <div className="absolute bottom-2 right-2 px-2 py-0.5 rounded-full bg-black/40 text-white text-xs font-medium">{posters.length}장</div>
                  </>
                )}
              </div>
            </div>
          )}

          {/* 정보 */}
          <div className="flex-1 min-w-0 flex flex-col justify-center py-2 text-white">
            <div className="flex items-center gap-2 mb-5 flex-wrap">
              <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-bold tracking-wider uppercase bg-white text-amber-700 shadow-sm">
                <PartyPopper size={13} />
                {typeLabel}
              </span>
              {isUniversity && schedule.schoolName && (
                <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-bold bg-white/90 text-amber-700 shadow-sm">
                  <GraduationCap size={13} />
                  {schedule.schoolName}
                </span>
              )}
            </div>

            <h1 className="text-3xl md:text-[38px] font-black leading-[1.1] tracking-tight mb-6" style={titleShadow}>
              {decodeHtmlEntities(schedule.title)}
            </h1>

            <div className="space-y-3">
              <div className="flex items-center gap-2.5">
                <Calendar size={19} className="text-amber-100" />
                <span className="text-lg font-bold" style={textShadow}>{formatFullDate(schedule.date)}</span>
                {schedule.time && (
                  <>
                    <span className="text-white/45">·</span>
                    <Clock size={17} className="text-amber-100" />
                    <span className="text-lg font-bold" style={textShadow}>{formatTime(schedule.time)}</span>
                  </>
                )}
              </div>
              {venue && (
                <button
                  type="button"
                  onClick={() => venue.lat && venue.lng && setMapOpen(true)}
                  className={`flex items-center gap-2.5 ${venue.lat && venue.lng ? 'group' : 'cursor-default'}`}
                >
                  <MapPin size={19} className="text-amber-100" />
                  <span className="text-lg font-bold group-hover:underline underline-offset-4 decoration-white/40" style={textShadow}>{venue.name}</span>
                  {venue.lat && venue.lng && <ChevronRight size={17} className="text-white/55 group-hover:text-white transition-colors" />}
                </button>
              )}
            </div>

            {members.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-6">
                {isFullGroup ? (
                  <span className="px-3.5 py-1.5 rounded-full text-sm font-bold bg-white/90 text-amber-700 shadow-sm">프로미스나인</span>
                ) : (
                  members.map((m) => (
                    <span key={m.id} className="px-3.5 py-1.5 rounded-full text-sm 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-2 mt-6 pt-5 border-t border-white/25">
                <span className="inline-flex items-center gap-1.5 text-sm font-semibold text-amber-50">
                  <Link2 size={15} />
                  링크
                </span>
                {postUrls.map((url, idx) => (
                  <a key={idx} href={url} target="_blank" rel="noopener noreferrer"
                    className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-bold bg-white/90 text-amber-700 shadow-sm hover:bg-white transition-colors">
                    {linkLabel(url)}
                    <ExternalLink size={12} />
                  </a>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ===== 장소 지도 다이얼로그 ===== */}
      <AnimatePresence>
        {mapOpen && venue && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              className="absolute inset-0 bg-black/50" onClick={() => setMapOpen(false)} />
            <motion.div
              initial={{ opacity: 0, scale: 0.96, y: 10 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.96, y: 10 }}
              transition={{ duration: 0.18 }}
              className="relative bg-white rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden"
            >
              <div className="flex items-start justify-between p-5 pb-4">
                <div className="flex items-start gap-2.5">
                  <MapPin size={20} className="text-amber-500 mt-0.5 flex-shrink-0" />
                  <div>
                    <p className="font-bold text-gray-900 text-lg">{venue.name}</p>
                    {venue.address && <p className="text-sm text-gray-500 mt-0.5">{venue.address}</p>}
                  </div>
                </div>
                <button onClick={() => setMapOpen(false)} className="p-1.5 rounded-lg hover:bg-gray-100 transition-colors">
                  <X size={18} className="text-gray-400" />
                </button>
              </div>
              <div className="px-5 pb-5">
                <KakaoMap lat={Number(venue.lat)} lng={Number(venue.lng)} name={venue.name}
                  className="w-full h-64 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-2.5 rounded-xl text-sm font-semibold text-white transition-opacity hover:opacity-90"
                    style={{ backgroundColor: ACCENT }}>
                    카카오맵에서 길찾기<ExternalLink size={14} />
                  </a>
                )}
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Lightbox */}
      {posters.length > 0 && (
        <Lightbox
          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>
  );
}

export default EventSection;
