
import React, { useState, useEffect } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { useAuth } from '@/contexts/auth';
import { useIsMobile } from '@/hooks/use-mobile';
import { isIOSPlatform } from '@/utils/platform';
import NotificationPopover from './notification/NotificationPopover';
import useNotifications from '@/hooks/useNotifications';

const Header: React.FC = () => {
  const {
    user
  } = useAuth();
  const userName = user?.user_metadata?.username || '익명';
  const [imageLoaded, setImageLoaded] = useState(false);
  const [imageError, setImageError] = useState(false);
  const isMobile = useIsMobile();
  const [isIOS, setIsIOS] = useState(false);
  const { notifications, clearAllNotifications, markAsRead } = useNotifications();

  // 플랫폼 감지
  useEffect(() => {
    setIsIOS(isIOSPlatform());
  }, []);

  // 이미지 프리로딩 처리
  useEffect(() => {
    const preloadImage = new Image();
    preloadImage.src = '/zellyy.png';
    preloadImage.onload = () => {
      setImageLoaded(true);
    };
    preloadImage.onerror = () => {
      console.error('아바타 이미지 로드 실패');
      setImageError(true);
    };
  }, []);

  return (
    <header className={`py-4 ${isIOS ? 'ios-header' : ''}`}>
      <div className="flex justify-between items-center">
        <div className="flex items-center">
          <Avatar className="h-12 w-12 mr-3">
            {!imageLoaded && !imageError ? (
              <div className="h-full w-full flex items-center justify-center">
                <Skeleton className="h-full w-full rounded-full" />
              </div>
            ) : (
              <>
                <AvatarImage 
                  src="/zellyy.png" 
                  alt="Zellyy" 
                  className={imageLoaded ? 'opacity-100' : 'opacity-0'} 
                  onLoad={() => setImageLoaded(true)} 
                  onError={() => setImageError(true)} 
                />
                {(imageError || !imageLoaded) && <AvatarFallback delayMs={100}>ZY</AvatarFallback>}
              </>
            )}
          </Avatar>
          <div>
            <h1 className="font-bold neuro-text text-xl">
              {user ? `${userName}님, 반갑습니다` : '반갑습니다'}
            </h1>
            <p className="text-gray-500 text-left">젤리의 적자탈출</p>
          </div>
        </div>
        <div className="neuro-flat p-2.5 rounded-full">
          <NotificationPopover 
            notifications={notifications}
            onClearAll={clearAllNotifications}
            onReadNotification={markAsRead}
          />
        </div>
      </div>
    </header>
  );
};

export default Header;
