import { useMemo, useRef, useEffect, forwardRef } from 'react';
import { Cake, Instagram } from 'lucide-react';
import { useMembers } from '@/hooks';

// 생일/나이 계산
const formatBirth = (birthDate) => {
  if (!birthDate) return null;
  return birthDate.slice(0, 10).replaceAll('-', '.'); // YYYY.MM.DD
};
const calcAge = (birthDate) => {
  if (!birthDate) return null;
  const b = new Date(birthDate);
  const t = new Date();
  let age = t.getFullYear() - b.getFullYear();
  const m = t.getMonth() - b.getMonth();
  if (m < 0 || (m === 0 && t.getDate() < b.getDate())) age--;
  return age;
};

/**
 * 현재 멤버 화보 카드 (스티키 스택)
 */
const MemberHeroCard = forwardRef(function MemberHeroCard({ member }, ref) {
  const birth = formatBirth(member.birth_date);
  const age = calcAge(member.birth_date);

  return (
    <div
      ref={ref}
      className="sticky top-4 rounded-[28px] overflow-hidden shadow-xl aspect-[4/5]"
      style={{ willChange: 'transform, opacity', transformOrigin: 'center top' }}
    >
      {member.image_medium || member.image_url ? (
        <img src={member.image_medium || member.image_url} alt={member.name} className="w-full h-full object-cover" />
      ) : (
        <div className="w-full h-full bg-gradient-to-br from-gray-200 to-gray-300 flex items-center justify-center text-5xl font-bold text-gray-400">
          {member.name[0]}
        </div>
      )}

      {/* 하단 그라데이션 + 정보 */}
      <div className="absolute inset-x-0 bottom-0 pt-20 pb-5 px-5"
        style={{ background: 'linear-gradient(to top, rgba(0,0,0,0.82) 0%, rgba(0,0,0,0.45) 45%, transparent 100%)' }}>
        <p className="text-white text-3xl font-black tracking-tight leading-none drop-shadow-sm">
          {member.name}
        </p>
        {birth && (
          <div className="flex items-center gap-1.5 mt-2 text-white/80">
            <Cake size={15} />
            <span className="text-[15px] font-medium">{birth}{age != null && ` · ${age}세`}</span>
          </div>
        )}

        {member.instagram && (
          <a href={member.instagram} target="_blank" rel="noopener noreferrer"
            className="mt-4 inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-white/95 active:bg-white transition-colors">
            <Instagram size={15} className="text-[#E1306C]" />
            <span className="text-sm font-bold text-gray-900">Instagram</span>
          </a>
        )}
      </div>
    </div>
  );
});

/**
 * Mobile 멤버 페이지 - 스티키 스택 (덮이며 흐려짐)
 */
function MobileMembers() {
  const { data: allMembers = [] } = useMembers();
  const currentMembers = useMemo(() => allMembers.filter((m) => !m.is_former), [allMembers]);

  const cardRefs = useRef([]);
  const spacerRef = useRef(null);
  useEffect(() => {
    const container = document.querySelector('.mobile-content');
    if (!container) return;

    // 마지막 카드가 top-3에서 딱 멈추도록 하단 여유 공간 계산
    const setSpacer = () => {
      const cards = cardRefs.current.filter(Boolean);
      if (!cards.length || !spacerRef.current) return;
      const cardH = cards[cards.length - 1].getBoundingClientRect().height;
      spacerRef.current.style.height = `${Math.max(0, container.clientHeight - cardH - 16)}px`;
    };

    const onScroll = () => {
      const cards = cardRefs.current.filter(Boolean);
      if (cards.length === 0) return;
      const rects = cards.map((c) => c.getBoundingClientRect());
      for (let i = 0; i < cards.length; i++) {
        let coverage = 0;
        if (i < cards.length - 1) {
          const cur = rects[i];
          const next = rects[i + 1];
          coverage = Math.min(1, Math.max(0, (cur.bottom - next.top) / cur.height));
        }
        cards[i].style.opacity = String(1 - coverage * 0.55);
        cards[i].style.transform = `scale(${(1 - coverage * 0.05).toFixed(3)})`;
      }
    };

    // 스크롤 멈추면, 올라오는 카드를 상단(top-4)에 덮이거나 되돌리도록 자석 스냅
    let snapTimer;
    const snapToNearest = () => {
      const cards = cardRefs.current.filter(Boolean);
      if (cards.length < 2) return;
      const line = container.getBoundingClientRect().top + 16; // top-4
      // 상단 라인 아래에서 올라오는 중인(=delta>0) 가장 가까운 카드
      let riser = null;
      let riserDelta = Infinity;
      for (const c of cards) {
        const d = c.getBoundingClientRect().top - line;
        if (d > 1 && d < riserDelta) { riserDelta = d; riser = c; }
      }
      if (!riser) return;
      const trigger = riser.getBoundingClientRect().height + 16; // rest(아래) → 덮임(상단) 이동량
      // 절반 기준: 가까운 쪽(덮임 0 / 되돌림 trigger)으로 스냅
      const target = riserDelta < trigger / 2 ? riserDelta : riserDelta - trigger;
      if (Math.abs(target) > 1) {
        container.scrollBy({ top: target, behavior: 'smooth' });
      }
    };

    const handleScroll = () => {
      onScroll();
      clearTimeout(snapTimer);
      snapTimer = setTimeout(snapToNearest, 90);
    };

    setSpacer();
    onScroll();
    container.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('resize', setSpacer);
    return () => {
      container.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', setSpacer);
      clearTimeout(snapTimer);
    };
  }, [currentMembers.length]);

  if (allMembers.length === 0) {
    return (
      <div className="flex items-center justify-center h-[calc(100vh-200px)]">
        <p className="text-gray-400">멤버 정보가 없습니다</p>
      </div>
    );
  }

  return (
    <div className="bg-gray-50 px-4 pt-4">
      <div className="space-y-4">
        {currentMembers.map((member, i) => (
          <MemberHeroCard
            key={member.id}
            member={member}
            ref={(el) => { cardRefs.current[i] = el; }}
          />
        ))}
      </div>
      {/* 마지막 카드가 top-3에서 멈추도록 동적 여유 공간 */}
      <div ref={spacerRef} />
    </div>
  );
}

export default MobileMembers;
