import React, { useEffect, useState, useCallback, useRef, memo } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom'; // Import useNavigate
import {
  pb, // Import pb instance
  getUserProfileByLogin,
  getUserAchievements,
  getReviewsByUserId,
  getFileUrl,
  updateUserProfile, // Note: This is not used for file uploads/deletions in this component
  updateUserShowcase,
  getXpForCurrentLevel,
  getXpForNextLevel,
  getAllAchievements, // Import getAllAchievements
  awardAchievement, // Import awardAchievement
  calculateLevel // Добавляем импорт calculateLevel
} from '../services/pocketbaseService';
import { useAuth } from '../contexts/AuthContext';
import { useProfileActions } from '../contexts/ProfileActionsContext';
import ReviewItem from '../components/reviews/ReviewItem';
import ReviewList from '../components/reviews/ReviewList';
import Modal from '../components/common/Modal';
import LazyImage from '../components/common/LazyImage';
import { FaEdit, FaCheckCircle, FaRegCircle, FaFire, FaTrophy, FaAward, FaPalette, FaUser, FaTelegram } from 'react-icons/fa';
import * as FaIcons from 'react-icons/fa';
import * as MdIcons from 'react-icons/md';
import * as IoIcons from 'react-icons/io5';
import * as BiIcons from 'react-icons/bi';
import * as HiIcons from 'react-icons/hi';
import * as RiIcons from 'react-icons/ri';
import { mediaTypes } from '../services/pocketbaseService';
import Squares from '../components/reactbits/Backgrounds/Squares/Squares';
import Dither from '../components/reactbits/Backgrounds/Dither/Dither';

// Мемоизированный компонент для отображения достижений
const AchievementItem = memo(({ achievement }) => {
  const getIconComponent = (iconName) => {
    if (!iconName) return FaTrophy;
    
    const prefix = iconName.substring(0, 2).toLowerCase();
    switch (prefix) {
      case 'fa': return FaIcons[iconName] || FaTrophy;
      case 'md': return MdIcons[iconName] || FaTrophy;
      case 'io': return IoIcons[iconName] || FaTrophy;
      case 'bi': return BiIcons[iconName] || FaTrophy;
      case 'hi': return HiIcons[iconName] || FaTrophy;
      case 'ri': return RiIcons[iconName] || FaTrophy;
      default: return FaTrophy;
    }
  };

  const IconComponent = getIconComponent(achievement.icon);

  return (
    <div className="group flex-none w-72 bg-campfire-charcoal/20 rounded-2xl p-4 border border-campfire-ash/10 hover:border-campfire-amber/20 transition-all duration-300">
      <div className="flex items-center space-x-4">
        <div className="w-12 h-12 rounded-xl bg-campfire-amber/10 flex items-center justify-center">
          <IconComponent className="text-campfire-amber" size={24} />
        </div>
        <div className="flex-grow">
          <h4 className="text-sm font-semibold text-campfire-light truncate">{achievement.title}</h4>
          {achievement.xp_reward > 0 && (
            <p className="text-xs text-campfire-amber mt-1 flex items-center">
              <FaFire className="mr-1" /> +{achievement.xp_reward} XP
            </p>
          )}
        </div>
      </div>
      {/* Описание при наведении */}
      <div className="absolute left-0 right-0 top-20 mt-2 p-3 bg-campfire-dark/10 rounded-lg border border-campfire-ash/20 shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50 pointer-events-none">
        <p className="text-xs text-campfire-light whitespace-normal">{achievement.description}</p>
      </div>
    </div>
  );
});

// Мемоизированный компонент для отображения статистики
const ProfileStats = memo(({ profileUser }) => (
  <div className="grid grid-cols-3 gap-4 mb-6">
    <div className="bg-campfire-charcoal p-4 rounded-lg text-center">
      <h3 className="text-lg font-bold text-campfire-amber">{profileUser.review_count || 0}</h3>
      <p className="text-sm text-campfire-ash">Рецензий</p>
    </div>
    <div className="bg-campfire-charcoal p-4 rounded-lg text-center">
      <h3 className="text-lg font-bold text-campfire-amber">{profileUser.media_count || 0}</h3>
      <p className="text-sm text-campfire-ash">Медиа</p>
    </div>
    <div className="bg-campfire-charcoal p-4 rounded-lg text-center">
      <h3 className="text-lg font-bold text-campfire-amber">{profileUser.achievement_count || 0}</h3>
      <p className="text-sm text-campfire-ash">Достижений</p>
    </div>
  </div>
));

const ProfilePage = () => {
  const { login } = useParams();
  const { user: currentUser, userProfile: currentUserProfile, loading: authLoading, isInitialized: authInitialized } = useAuth(); // currentUser is the PocketBase auth model
  const { shouldOpenEditModal, resetEditModalTrigger } = useProfileActions() || {};
  const navigate = useNavigate(); // Initialize useNavigate
  const [profileUser, setProfileUser] = useState(null);
  const [achievements, setAchievements] = useState([]);
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [achievementsScrollPosition, setAchievementsScrollPosition] = useState(0);
  const achievementsContainerRef = useRef(null);

  const [isEditingProfile, setIsEditingProfile] = useState(false);
  const [editFormData, setEditFormData] = useState({ 
    description: '', 
    profile_picture: null, 
    banner_picture: null,
    email: '' // Добавляем поле для email
  });
  const [profilePictureFile, setProfilePictureFile] = useState(null);
  const [bannerPictureFile, setBannerPictureFile] = useState(null);
  const [deleteProfilePicture, setDeleteProfilePicture] = useState(false);
  const [deleteBannerPicture, setDeleteBannerPicture] = useState(false);
  const [editFormError, setEditFormError] = useState(null);
  const [isSubmittingEdit, setIsSubmittingEdit] = useState(false);

  const [isManagingShowcase, setIsManagingShowcase] = useState(false);
  const [selectedShowcaseReviewIds, setSelectedShowcaseReviewIds] = useState([]);

  // State for Achievement Assignment Modal (New)
  const [isAssigningAchievements, setIsAssigningAchievements] = useState(false);
  const [availableAchievements, setAvailableAchievements] = useState([]); // To fetch list of all achievements
  const [userAchievementIds, setUserAchievementIds] = useState([]); // To track achievements the user already has
  const [selectedAchievementIdsToAssign, setSelectedAchievementIdsToAssign] = useState([]); // To track achievements to assign/remove

  const [showcaseTheme, setShowcaseTheme] = useState({
    type: 'none',
    background: '#1a1a1a',
    squares: {
      direction: 'down',
      speed: 0.25,
      borderColor: '#FFFFFF',
      squareSize: 20,
      hoverFillColor: '#FF6A00',
      backgroundColor: '#1a1a1a'
    },
    dither: {
      waveSpeed: 0.05,
      waveFrequency: 3,
      waveAmplitude: 0.3,
      waveColor: [0.4, 0.4, 0.4],
      colorNum: 4,
      pixelSize: 2,
      enableMouseInteraction: false,
      mouseRadius: 1
    }
  });
  const [isCustomizingTheme, setIsCustomizingTheme] = useState(false);
  const [previewTheme, setPreviewTheme] = useState(null);

  // Determine if the logged-in user is viewing their own profile
  const isOwnProfile = currentUser && profileUser && currentUser.id === profileUser.id;
  // Check if the logged-in user has the 'admin' role
  const isAdmin = currentUser?.role === 'admin';


  const loadProfileData = useCallback(async () => {
      if (!login) {
          setError('Логин пользователя не указан.');
          setLoading(false);
          return;
      }
      try {
          setLoading(true);
          setError(null);

          // Fetch user profile by login, expanding showcase relation
          const userData = await getUserProfileByLogin(login);
          if (!userData) {
              throw new Error('Пользователь не найден.');
          }
          setProfileUser(userData);
          
          // Безопасная обработка showcase_theme
          if (userData.showcase_theme) {
              try {
                  const parsedTheme = typeof userData.showcase_theme === 'string' 
                      ? JSON.parse(userData.showcase_theme)
                      : userData.showcase_theme;
                  setShowcaseTheme(parsedTheme);
              } catch (parseError) {
                  console.warn('Ошибка при парсинге showcase_theme:', parseError);
                  // Устанавливаем тему по умолчанию
                  setShowcaseTheme({
                      type: 'none',
                      background: '#1a1a1a',
                      squares: {
                          direction: 'down',
                          speed: 0.25,
                          borderColor: '#FFFFFF',
                          squareSize: 20,
                          hoverFillColor: '#FF6A00',
                          backgroundColor: '#1a1a1a'
                      },
                      dither: {
                          waveSpeed: 0.05,
                          waveFrequency: 3,
                          waveAmplitude: 0.3,
                          waveColor: [0.4, 0.4, 0.4],
                          colorNum: 4,
                          pixelSize: 2,
                          enableMouseInteraction: false,
                          mouseRadius: 1
                      }
                  });
              }
          }

          console.log('ProfilePage: User data loaded:', userData);
          console.log('ProfilePage: User showcase data:', userData.showcase, 'expanded:', userData.expand?.showcase);

          // Fetch user's achievements
          const achievementsData = await getUserAchievements(userData.id);
          setAchievements(achievementsData || []);
          console.log('ProfilePage: Achievements loaded:', achievementsData);
          // Store user's current achievement IDs for assignment modal
          setUserAchievementIds(achievementsData.map(ua => ua.achievement_id) || []);

          // Fetch user's reviews
          const reviewsData = await getReviewsByUserId(userData.id);
          setReviews(reviewsData || []);
          console.log('ProfilePage: Reviews loaded:', reviewsData);

          // Initialize showcase selection state for management modal
          setSelectedShowcaseReviewIds(userData.showcase || []);

      } catch (err) {
          console.error('Error loading profile data:', err);
          setError('Не удалось загрузить данные профиля.');
      } finally {
          setLoading(false);
      }
  }, [login]);


  useEffect(() => {
      console.log('ProfilePage mounted or dependencies changed. login:', login, 'currentUser:', !!currentUser, 'authLoading:', authLoading, 'authInitialized:', authInitialized, 'profileUser:', !!profileUser, 'isOwnProfile:', isOwnProfile); // Added profileUser and isOwnProfile to log
      // Wait for auth to be initialized before loading profile data
      if (!authLoading && authInitialized) {
          console.log('ProfilePage useEffect: Auth initialized and not loading. Loading profile data...');
          loadProfileData();
      } else {
          console.log('ProfilePage useEffect: Waiting for auth initialization or loading...');
      }
  }, [login, currentUser, authLoading, authInitialized, loadProfileData]); // Added authInitialized to dependencies


  // Effect to open edit modal if triggered by context (e.g., from Header)
  // This effect should ONLY handle the external trigger and the edit modal.
  // It should NOT interfere with modals opened by buttons on the page itself.
  useEffect(() => {
      console.log('ProfilePage useEffect [shouldOpenEditModal, isOwnProfile, profileUser]: Running for external edit trigger. shouldOpenEditModal:', shouldOpenEditModal, 'isOwnProfile:', isOwnProfile, 'profileUser:', !!profileUser);
      // Check if the trigger is set AND we are viewing the *own* profile AND profileUser data is loaded
      if (shouldOpenEditModal && isOwnProfile && profileUser) {
          console.log('ProfilePage useEffect [shouldOpenEditModal, isOwnProfile, profileUser]: Triggered to open edit modal. Opening modal...');
          handleEditProfile(); // Open the modal
          // Reset the trigger *after* the modal is successfully opened
          resetEditModalTrigger();
      } else if (shouldOpenEditModal && (!isOwnProfile || !profileUser)) {
          // If trigger is set but it's not the own profile or profile data isn't ready,
          // DO NOT reset the trigger immediately. Let the next render/useEffect run
          // when profileUser might be loaded.
          console.log('ProfilePage useEffect [shouldOpenEditModal, isOwnProfile, profileUser]: Trigger set, but not own profile or profile data not ready. Waiting for profile data...');
          // Do nothing here, let the effect potentially run again when profileUser is loaded
      }
      // REMOVED: The else if block that closed modals when shouldOpenEditModal was false.
      // Modals opened by buttons on the page should be closed by their own handlers.
  }, [shouldOpenEditModal, isOwnProfile, profileUser, resetEditModalTrigger]); // Added modal states to dependencies


  // --- Profile Edit Modal Handlers ---
  const handleEditProfile = () => {
      if (!profileUser) return;
      console.log('ProfilePage: Opening edit profile modal.');
      setEditFormData({
          description: profileUser.description || '',
          profile_picture: null,
          banner_picture: null,
          email: profileUser.email || '' // Добавляем email в начальные данные
      });
      setProfilePictureFile(null);
      setBannerPictureFile(null);
      setDeleteProfilePicture(false);
      setDeleteBannerPicture(false);
      setEditFormError(null);
      setIsEditingProfile(true);
  };

  const handleEditFormChange = (e) => {
      const { name, value } = e.target;
      setEditFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleEditFileChange = (e) => {
      const { name, files } = e.target;
      const file = files?.[0] || null;
      if (name === 'profile_picture') {
          setProfilePictureFile(file);
          if (file) setDeleteProfilePicture(false);
      } else if (name === 'banner_picture') {
          setBannerPictureFile(file);
          if (file) setDeleteBannerPicture(false);
      }
  };

  const handleRemoveExistingPicture = (fieldName) => {
      if (fieldName === 'profile_picture') {
          setDeleteProfilePicture(true);
          setProfilePictureFile(null);
      } else if (fieldName === 'banner_picture') {
          setDeleteBannerPicture(true);
          setBannerPictureFile(null);
      }
  };


  const handleEditFormSubmit = async (e) => {
      e.preventDefault();
      if (!profileUser) return;

      setIsSubmittingEdit(true);
      setEditFormError(null);

      try {
          const formData = new FormData();
          formData.append('description', editFormData.description);
          formData.append('email', editFormData.email); // Добавляем email в formData

          if (profilePictureFile) {
              formData.append('profile_picture', profilePictureFile);
          } else if (deleteProfilePicture && profileUser.profile_picture) {
              formData.append('profile_picture', null);
          }

          if (bannerPictureFile) {
              formData.append('banner_picture', bannerPictureFile);
          } else if (deleteBannerPicture && profileUser.banner_picture) {
              formData.append('banner_picture', null);
          }

          await pb.collection('users').update(profileUser.id, formData);

          console.log('Profile updated successfully.');
          setIsEditingProfile(false);
          loadProfileData();
      } catch (error) {
          console.error('Error updating profile:', error);
          setEditFormError(error.message || 'Произошла ошибка при обновлении профиля');
      } finally {
          setIsSubmittingEdit(false);
      }
  };

  const handleEditFormCancel = () => {
      setIsEditingProfile(false);
      setEditFormError(null);
  };

  // --- Showcase Management Handlers ---
  const handleManageShowcase = () => {
      if (!profileUser) return;
      console.log('ProfilePage: Opening showcase management modal.'); // Added log
      setSelectedShowcaseReviewIds(profileUser.showcase || []);
      setIsManagingShowcase(true);
  };

  const handleToggleShowcaseReview = (reviewId) => {
      setSelectedShowcaseReviewIds(prev => {
          const isSelected = prev.includes(reviewId);
          if (isSelected) {
              return prev.filter(id => id !== reviewId);
          } else {
              if (prev.length < 3) {
                  return [...prev, reviewId];
              } else {
                  alert('Вы можете выбрать до 3 рецензий для витрины.');
                  return prev;
              }
          }
      });
  };

  const handleSaveShowcase = async () => {
      if (!profileUser) return;
      setIsSubmittingEdit(true);
      setEditFormError(null);

      try {
          // PocketBase update for relation list requires sending the full list of IDs
          // Use pb instance imported directly
          await pb.collection('users').update(profileUser.id, {
              showcase: selectedShowcaseReviewIds
          });

          console.log('Showcase updated successfully.');
          setIsManagingShowcase(false);
          loadProfileData(); // Refresh profile data to show updated showcase

      } catch (err) {
          console.error('Error updating showcase:', err);
          const pbErrorData = err.response?.data?.data;
          let errorMessage = err.message || 'Произошла ошибка при обновлении витрины.';

          if (pbErrorData) {
              errorMessage = Object.entries(pbErrorData)
                  .map(([field, errorInfo]) => `${field}: ${errorInfo.message}`)
                  .join(', ');
          }
          setEditFormError(errorMessage);
      } finally {
          setIsSubmittingEdit(false);
      }
  };

  const handleCancelShowcase = () => {
      setIsManagingShowcase(false);
      setEditFormError(null);
  };

  // --- Achievement Assignment Handlers (New) ---
  const handleAssignAchievements = async () => {
      if (!profileUser || !isAdmin) return;

      console.log('ProfilePage: Opening achievement assignment modal.');
      setIsAssigningAchievements(true);
      setEditFormError(null);

      try {
          const allAchievements = await getAllAchievements();
          setAvailableAchievements(allAchievements);

          // Инициализируем выбранные достижения теми, которые уже есть у пользователя
          const currentUserAchievementIds = achievements.map(ua => ua.id);
          setSelectedAchievementIdsToAssign(currentUserAchievementIds);

      } catch (err) {
          console.error('Error loading achievements for assignment:', err);
          setEditFormError(err.message || 'Не удалось загрузить список достижений.');
      }
  };

  const handleToggleAchievementAssignment = (achievementId) => {
      setSelectedAchievementIdsToAssign(prev => {
          const isSelected = prev.includes(achievementId);
          if (isSelected) {
              return prev.filter(id => id !== achievementId);
          } else {
              return [...prev, achievementId];
          }
      });
  };

  const handleSaveAchievementAssignment = async () => {
      if (!profileUser || !isAdmin) return;

      setIsSubmittingEdit(true);
      setEditFormError(null);

      try {
          // Получаем текущие достижения пользователя
          const currentAchievements = await getUserAchievements(profileUser.id);
          
          // Находим достижения для добавления и удаления
          const achievementsToAdd = selectedAchievementIdsToAssign.filter(id => 
              !currentAchievements.some(ua => ua.id === id)
          );
          
          const achievementsToRemove = currentAchievements.filter(ua => 
              !selectedAchievementIdsToAssign.includes(ua.id)
          );

          // Собираем XP для удаления
          let totalXpToRemove = 0;
          for (const achievement of achievementsToRemove) {
              totalXpToRemove += achievement.xp_reward || 0;
          }

          // Добавляем новые достижения
          for (const achievementId of achievementsToAdd) {
              await awardAchievement(profileUser.id, achievementId);
          }

          // Удаляем снятые достижения
          for (const userAchievement of achievementsToRemove) {
              // Получаем ID записи user_achievements
              const userAchievementRecord = await pb.collection('user_achievements').getList(1, 1, {
                  filter: `user_id = "${profileUser.id}" && achievement_id = "${userAchievement.id}"`
              });
              
              if (userAchievementRecord.items.length > 0) {
                  await pb.collection('user_achievements').delete(userAchievementRecord.items[0].id);
              }
          }

          // Обновляем XP пользователя
          if (totalXpToRemove > 0) {
                  const currentXp = profileUser.xp || 0;
              const newXp = Math.max(0, currentXp - totalXpToRemove);
              const newLevel = calculateLevel(newXp);
              
              await pb.collection('users').update(profileUser.id, {
                  xp: newXp,
                  level: newLevel
              });
              }

          // Обновляем список достижений и данные пользователя
          const [updatedAchievements, updatedUserData] = await Promise.all([
              getUserAchievements(profileUser.id),
              pb.collection('users').getOne(profileUser.id)
          ]);
          
          setAchievements(updatedAchievements);
          setProfileUser(updatedUserData);
          
          // Сбрасываем позицию прокрутки и обновляем состояние кнопок
          if (achievementsContainerRef.current) {
              achievementsContainerRef.current.scrollLeft = 0;
              setAchievementsScrollPosition(0);
          }

          setIsAssigningAchievements(false);
      } catch (err) {
          console.error('Error saving achievement assignment:', err);
          const pbErrorData = err.response?.data?.data;
          let errorMessage = err.message || 'Произошла ошибка при сохранении достижений.';

          if (pbErrorData) {
              errorMessage = Object.entries(pbErrorData)
                  .map(([field, errorInfo]) => `${field}: ${errorInfo.message}`)
                  .join(', ');
          }
          setEditFormError(errorMessage);
      } finally {
          setIsSubmittingEdit(false);
      }
  };

  const handleCancelAchievementAssignment = () => {
      setIsAssigningAchievements(false);
      setEditFormError(null);
  };

  const handleAchievementsScroll = (direction) => {
    if (!achievementsContainerRef.current) return;
    
    const container = achievementsContainerRef.current;
    const scrollAmount = 310; // Примерная ширина карточки + отступ
    
    if (direction === 'left') {
      container.scrollLeft -= scrollAmount;
    } else {
      container.scrollLeft += scrollAmount;
    }
    
    setAchievementsScrollPosition(container.scrollLeft);
  };

  // Добавляем функцию для переключения темы
  const handleToggleShowcaseTheme = async () => {
    if (!profileUser || !isOwnProfile) return;
    
    try {
      const newTheme = showcaseTheme.type === 'squares' ? 'dither' : 'squares';
      await pb.collection('users').update(profileUser.id, {
        showcase_theme: JSON.stringify({
          type: newTheme,
          squares: showcaseTheme.squares,
          dither: showcaseTheme.dither
        })
      });
      setShowcaseTheme({
        type: newTheme,
        squares: showcaseTheme.squares,
        dither: showcaseTheme.dither
      });
    } catch (error) {
      console.error('Error updating showcase theme:', error);
    }
  };

  // Функция для открытия модального окна кастомизации
  const handleCustomizeTheme = () => {
    setPreviewTheme(JSON.parse(JSON.stringify(showcaseTheme))); // Создаем глубокую копию
    setIsCustomizingTheme(true);
  };

  // Функция для обновления параметров темы
  const handleThemeParamChange = (themeType, param, value) => {
    setPreviewTheme(prev => ({
      ...prev,
      [themeType]: {
        ...prev[themeType],
        [param]: value
      }
    }));
  };

  // Функция для сохранения темы
  const handleSaveTheme = async () => {
    if (!profileUser || !isOwnProfile) return;
    
    try {
      await pb.collection('users').update(profileUser.id, {
        showcase_theme: JSON.stringify(previewTheme)
      });
      setShowcaseTheme(previewTheme);
      setIsCustomizingTheme(false);
    } catch (error) {
      console.error('Error updating showcase theme:', error);
    }
  };

  // Добавляем функцию для проверки доступности темы
  const isThemeAvailable = (themeType) => {
    const userLevel = profileUser?.level || 1;
    
    switch (themeType) {
        case 'none':
            return true;
        case 'background':
            return userLevel >= 2;
        case 'squares':
            return userLevel >= 3;
        case 'dither':
            return userLevel >= 7;
        default:
            return false;
    }
  };

  if (loading || authLoading || !authInitialized) { // Show loading if auth is still initializing/loading
    console.log('ProfilePage: Showing initial loading state. Loading:', loading, 'AuthLoading:', authLoading, 'AuthInitialized:', authInitialized);
    return (
      <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-campfire-amber"></div>
      </div>
    );
  }

  if (error) {
    console.error('ProfilePage: Showing error state:', error);
    return (
      <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
        <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
          {error}
        </div>
      </div>
    );
  }

  if (!profileUser) {
     console.log('ProfilePage: Showing user not found state.');
    return (
      <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
        <div className="text-campfire-ash text-lg">Профиль пользователя не найден.</div>
      </div>
    );
  }

  const currentLevel = profileUser.level || 1;
  const currentXP = profileUser.xp || 0;
  const xpForCurrentLevel = getXpForCurrentLevel(currentLevel);
  const xpForNextLevel = getXpForNextLevel(currentLevel);
  const xpProgress = xpForNextLevel > xpForCurrentLevel ?
                     ((currentXP - xpForCurrentLevel) / (xpForNextLevel - xpForCurrentLevel)) * 100
                     : 100;

  const tabs = [
    { id: 'reviews', label: 'Рецензии' },
    { id: 'ratings', label: 'Оценки' },
    { id: 'lists', label: 'Списки' }
  ];

  return (
    <div className="min-h-screen bg-campfire-dark">
      {/* Banner Section */}
      <div
        className="relative h-[600px] bg-cover bg-center"
        style={{ 
          backgroundImage: `url(${getFileUrl(profileUser, 'banner_picture') || 'https://images.pexels.com/photos/1103970/pexels-photo-1103970.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'})`,
          backgroundPosition: 'center 20%'
        }}
      >
        <div className="absolute inset-0 from-campfire-dark/0 via-campfire-dark/50 to-campfire-dark"></div>
        
        {/* Admin Panel */}
        {isAdmin && (
          <div className="absolute top-8 right-8 z-50">
            <div className="bg-campfire-charcoal/20 rounded-2xl p-4 border border-campfire-amber/10 backdrop-blur-md">
              <div className="space-y-4">
                <button
                  onClick={handleAssignAchievements}
                  className="w-full py-2 px-4 bg-campfire-amber/10 rounded-2xl flex items-center justify-center space-x-2 hover:bg-campfire-amber/20 transition-all duration-300"
                >
                  <FaAward size={12} />
                  <span className="text-campfire-amber text-sm">Назначить</span>
                </button>
              </div>
            </div>
          </div>
        )}

        <div className="container-custom relative z-10 h-full flex items-end">
            <div className="w-full">
            {/* Profile Info Card */}
            <div className="w-full bg-campfire-dark/40 rounded-t-3xl p-8 shadow-md backdrop-blur-md">
                {/* User Info Section */}
                <div className="flex items-start justify-between mb-8">
                  {/* Left Section with Avatar and User Info */}
                  <div className="flex items-start space-x-4 flex-grow">
                    {/* Profile Picture Container */}
                    <div className="bg-campfire-charcoal/20 rounded-2xl p-3">
                      <div className="w-24 h-24 rounded-2xl bg-campfire-dark/40 overflow-hidden shadow-[0_0_30px_rgba(251,191,36,0.1)] backdrop-blur-md">
                        {profileUser.profile_picture ? (
                          <LazyImage
                            src={getFileUrl(profileUser, 'profile_picture')}
                            alt={`${profileUser.login}'s profile`}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center bg-campfire-charcoal/40">
                            <FaUser className="w-16 h-16 text-campfire-light/80" />
              </div>
                        )}
                      </div>
                    </div>

                    {/* User Info Container */}
                    <div className="bg-campfire-charcoal/20 rounded-2xl p-4 flex-grow">
                      <div className="flex items-center justify-between">
                        {/* Left part: Username, Login, Edit button */}
                        <div className="flex items-center space-x-4">
                          <h1 className="text-2xl font-bold text-campfire-light tracking-tight">{profileUser.username}</h1>
                          <div className="px-3 py-1 bg-campfire-amber/10 rounded-full">
                            <p className="text-campfire-amber font-medium text-sm">@{profileUser.login}</p>
                          </div>
                          {isOwnProfile && (
                            <button
                              onClick={handleEditProfile}
                              className="py-2 bg-campfire-amber/10 rounded-2xl flex items-center p-4 hover:bg-campfire-amber/20 transition-all duration-300"
                              title="Редактировать профиль"
                            >
                              <FaEdit size={12} />
                            </button>
                          )}
                        </div>

                        {/* Right part: Stats */}
                        <div className="flex items-center space-x-6">
                          <div className="flex items-center">
                            <FaTrophy className="text-campfire-amber/80 mr-2 text-sm" />
                            <div>
                              <p className="text-xs text-campfire-light">Уровень</p>
                              <p className="text-sm font-bold text-campfire-amber/90">{profileUser.level || 1}</p>
                            </div>
                          </div>
                          <div className="w-px h-8 bg-campfire-ash/10"></div>
                          <div className="flex items-center">
                            <FaFire className="text-campfire-amber/80 mr-2 text-sm" />
                            <div>
                              <p className="text-xs text-campfire-light">Рецензий</p>
                              <p className="text-sm font-bold text-campfire-amber/90">{profileUser.review_count || 0}</p>
                            </div>
                          </div>
                          <div className="w-px h-8 bg-campfire-ash/10"></div>
                          <div className="flex items-center">
                            <FaAward className="text-campfire-amber/80 mr-2 text-sm" />
                            <div>
                              <p className="text-xs text-campfire-light">Достижений</p>
                              <p className="text-sm font-bold text-campfire-amber/90">{achievements.length}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="mt-4 pt-4 border-t border-campfire-ash/10">
                        <p className="text-campfire-light/80 text-sm leading-relaxed">
                          {profileUser.description || 'Пользователь пока ничего не рассказал о себе.'}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Achievements Section */}
                <div className="mb-8">
                  <div className="flex justify-between items-center mb-6">
                    <div className="flex items-center space-x-4">
                      <div className="w-1 h-8 bg-campfire-amber/20 rounded-full"></div>
                      <h2 className="text-2xl font-bold text-campfire-light">Достижения</h2>
                    </div>
                    <div className="flex items-center space-x-2">
                      <button 
                        onClick={() => handleAchievementsScroll('left')}
                        className="w-8 h-8 rounded-full bg-campfire-charcoal/20 border border-campfire-ash/10 flex items-center justify-center text-campfire-light hover:bg-campfire-amber/10 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                        disabled={achievementsScrollPosition <= 0}
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                        </svg>
                      </button>
                      <button 
                        onClick={() => handleAchievementsScroll('right')}
                        className="w-8 h-8 rounded-full bg-campfire-charcoal/20 border border-campfire-ash/10 flex items-center justify-center text-campfire-light hover:bg-campfire-amber/10 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                        disabled={!achievementsContainerRef.current || achievementsScrollPosition >= achievementsContainerRef.current.scrollWidth - achievementsContainerRef.current.clientWidth}
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                        </svg>
                      </button>
                    </div>
                  </div>
                  {achievements.length > 0 ? (
                    <div className="relative">
                      <div 
                        ref={achievementsContainerRef}
                        className="flex overflow-x-auto pb-4 gap-4 custom-scrollbar scroll-smooth"
                        onScroll={(e) => setAchievementsScrollPosition(e.target.scrollLeft)}
                      >
                        {achievements.map(achievement => (
                          <AchievementItem key={achievement.id} achievement={achievement} />
                        ))}
                      </div>
                    </div>
                  ) : (
                    <div className="bg-campfire-charcoal/20 rounded-2xl p-8 text-center border border-campfire-ash/10">
                      <p className="text-campfire-light">У пользователя пока нет достижений</p>
                    </div>
                  )}
                </div>

               {/* XP Progress Bar */}
                <div className="bg-campfire-charcoal/20 rounded-2xl p-4 border border-campfire-ash/10">
                  <div className="flex justify-between text-sm mb-2">
                    <span className="text-campfire-light">XP: {profileUser.xp || 0} / {xpForNextLevel}</span>
                    <span className="text-campfire-light">Уровень {currentLevel + 1}</span>
                  </div>
                  <div className="w-full bg-campfire-charcoal/20 rounded-full h-3">
                   <div
                      className="bg-gradient-to-r from-campfire-amber/80 to-campfire-amber h-3 rounded-full transition-all duration-500 ease-out"
                       style={{ width: `${xpProgress}%` }}
                   ></div>
            </div>
          </div>
        </div>
      </div>
        </div>
        </div>

      <div className="container-custom py-12 mt-16">

        {/* Showcase Section */}
        <div className="mb-12">
            <div className="flex justify-between items-center mb-6 border-b border-campfire-ash/20 pb-4">
                <h2 className="text-2xl font-bold text-campfire-light">Витрина рецензий</h2>
                <div className="flex items-center space-x-4">
                    {isOwnProfile && (
                        <>
                            <button
                                onClick={handleCustomizeTheme}
                                className="btn-secondary flex items-center space-x-2"
                                title="Настроить тему фона"
                            >
                                <FaPalette size={18} />
                                <span>Настроить тему</span>
                            </button>
                            <button
                                onClick={handleManageShowcase}
                                className="btn-secondary flex items-center space-x-2"
                            >
                                <FaEdit size={18} />
                                <span>Управлять витриной</span>
                            </button>
                        </>
                    )}
                </div>
            </div>
            <div className="relative rounded-3xl overflow-hidden" style={{ backgroundColor: showcaseTheme.background }}>
                {showcaseTheme.type === 'squares' && (
                    <div className="absolute inset-0 pointer-events-none" style={{ backgroundColor: showcaseTheme.squares.backgroundColor }}>
                        <Squares 
                            direction={showcaseTheme.squares.direction}
                            speed={showcaseTheme.squares.speed}
                            borderColor={showcaseTheme.squares.borderColor}
                            squareSize={showcaseTheme.squares.squareSize}
                            hoverFillColor={showcaseTheme.squares.hoverFillColor}
                        />
                    </div>
                )}
                {showcaseTheme.type === 'dither' && (
                    <div className="absolute inset-0 z-0" style={{ pointerEvents: showcaseTheme.dither.enableMouseInteraction ? 'auto' : 'none' }}>
                        <Dither
                            waveSpeed={showcaseTheme.dither.waveSpeed}
                            waveFrequency={showcaseTheme.dither.waveFrequency}
                            waveAmplitude={showcaseTheme.dither.waveAmplitude}
                            waveColor={showcaseTheme.dither.waveColor}
                            colorNum={showcaseTheme.dither.colorNum}
                            pixelSize={showcaseTheme.dither.pixelSize}
                            enableMouseInteraction={showcaseTheme.dither.enableMouseInteraction}
                            mouseRadius={showcaseTheme.dither.mouseRadius}
                        />
                    </div>
                )}
                <div className="relative z-10 p-8" style={{ pointerEvents: 'none' }}>
                    {profileUser.expand?.showcase && profileUser.expand.showcase.length > 0 ? (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" style={{ pointerEvents: 'auto' }}>
                            {profileUser.expand.showcase.map(review => (
                                <ReviewItem
                                    key={review.id}
                                    review={review}
                                    media={review.expand?.media_id}
                                    season={review.expand?.season_id}
                                    reviewCharacteristics={review.expand?.media_id?.characteristics || {}}
                                    isProfilePage={true}
                                />
                            ))}
                        </div>
                    ) : (
                        <div className="text-center py-8 text-campfire-light">
                            {isOwnProfile ? (
                                <>
                                    Ваша витрина пуста. <button onClick={handleManageShowcase} className="text-campfire-amber hover:underline">Добавьте</button> сюда свои лучшие рецензии!
                                </>
                            ) : (
                                'У пользователя пока нет рецензий на витрине.'
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>


        {/* All Reviews Section - Render as smaller cards */}
        <div className="mb-12">
          <h2 className="text-2xl font-bold text-campfire-light mb-6 border-b border-campfire-ash/20 pb-4">Все рецензии</h2>
          {reviews.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6"> {/* Use grid for smaller cards */}
                {reviews.map(review => (
                     <ReviewItem
                        key={review.id}
                        review={review}
                        media={review.expand?.media_id}
                        season={review.expand?.season_id}
                        reviewCharacteristics={review.expand?.media_id?.characteristics || {}}
                        isProfilePage={true} // Indicate it's on the profile page
                        isSmallCard={true} // Indicate it should render as a small card
                    />
                ))}
            </div>
          ) : (
            <div className="text-center py-8 text-campfire-light">
              У пользователя пока нет рецензий.
            </div>
          )}
        </div>
      </div>

      {/* Profile Edit Modal */}
      {profileUser && (
          <Modal
              isOpen={isEditingProfile}
              onClose={handleEditFormCancel}
              title={`Редактировать профиль: ${profileUser.username}`}
              size="lg"
          >
              <form onSubmit={handleEditFormSubmit} className="space-y-6">
                  {editFormError && (
                      <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg">
                          Ошибка: {editFormError}
                      </div>
                  )}

                  {/* Email */}
                  <div>
                      <label htmlFor="email" className="block mb-2 text-campfire-light text-sm font-medium">
                          Email (опционально)
                      </label>
                      <input
                          type="email"
                          id="email"
                          name="email"
                          value={editFormData.email}
                          onChange={handleEditFormChange}
                          className="w-full p-3 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light focus:ring-2 focus:ring-campfire-amber focus:border-transparent transition-colors"
                          placeholder="your@email.com"
                      />
                  </div>

                  {/* Description */}
                  <div>
                      <label htmlFor="description" className="block mb-2 text-campfire-light text-sm font-medium">
                          О себе (опционально)
                      </label>
                      <textarea
                          id="description"
                          name="description"
                          rows="4"
                          value={editFormData.description}
                          onChange={handleEditFormChange}
                          className="w-full p-3 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light focus:ring-2 focus:ring-campfire-amber focus:border-transparent transition-colors"
                      />
                  </div>

                  {/* Profile Picture */}
                  <div>
                      <label htmlFor="profile_picture" className="block mb-2 text-campfire-light text-sm font-medium">
                          Фото профиля (опционально)
                      </label>
                      {profileUser.profile_picture && !deleteProfilePicture && (
                          <div className="mb-4">
                              <p className="text-sm text-campfire-ash mb-2">Текущее фото:</p>
                              <LazyImage src={getFileUrl(profileUser, 'profile_picture')} alt="Current Profile" className="w-20 h-20 rounded-full mb-2 object-cover" />
                              <button
                                  type="button"
                                  onClick={() => handleRemoveExistingPicture('profile_picture')}
                                  className="text-red-500 hover:underline text-sm"
                              >
                                  Удалить текущее фото
                              </button>
                          </div>
                      )}
                      <input
                          type="file"
                          id="profile_picture"
                          name="profile_picture"
                          onChange={handleEditFileChange}
                          className="w-full text-campfire-light text-sm
                             file:mr-4 file:py-2 file:px-4
                             file:rounded-md file:border-0
                             file:text-sm file:font-semibold
                             file:bg-campfire-amber file:text-campfire-dark
                             hover:file:bg-campfire-amber/80 cursor-pointer"
                      />
                  </div>

                  {/* Banner Picture */}
                  <div>
                      <label htmlFor="banner_picture" className="block mb-2 text-campfire-light text-sm font-medium">
                          Баннер профиля (опционально)
                      </label>
                      {profileUser.banner_picture && !deleteBannerPicture && (
                          <div className="mb-4">
                              <p className="text-sm text-campfire-ash mb-2">Текущий баннер:</p>
                              <LazyImage src={getFileUrl(profileUser, 'banner_picture')} alt="Current Banner" className="w-full h-32 object-cover rounded-md mb-2" />
                              <button
                                  type="button"
                                  onClick={() => handleRemoveExistingPicture('banner_picture')}
                                  className="text-red-500 hover:underline text-sm"
                               >
                                  Удалить текущий баннер
                              </button>
                          </div>
                      )}
                      <input
                          type="file"
                          id="banner_picture"
                          name="banner_picture"
                          onChange={handleEditFileChange}
                          className="w-full text-campfire-light text-sm
                             file:mr-4 file:py-2 file:px-4
                             file:rounded-md file:border-0
                             file:text-sm file:font-semibold
                             file:bg-campfire-amber file:text-campfire-dark
                             hover:file:bg-campfire-amber/80 cursor-pointer"
                    />
                  </div>


                  {/* Form Actions */}
                  <div className="flex justify-end space-x-4 mt-6">
                      <button
                          type="button"
                          onClick={handleEditFormCancel}
                          className="btn-secondary"
                          disabled={isSubmittingEdit}
                      >
                          Отмена
                      </button>
                      <button
                          type="submit"
                          className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
                          disabled={isSubmittingEdit}
                      >
                          {isSubmittingEdit ? 'Сохранение...' : 'Сохранить изменения'}
                      </button>
                  </div>
              </form>
          </Modal>
      )}

      {/* Showcase Management Modal */}
      {profileUser && isOwnProfile && (
          <Modal
              isOpen={isManagingShowcase}
              onClose={handleCancelShowcase}
              title={`Управление витриной (${selectedShowcaseReviewIds.length}/3)`}
              size="lg"
          >
              <div className="space-y-4">
                  {editFormError && (
                      <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg">
                          Ошибка: {editFormError}
                      </div>
                  )}
                  <p className="text-campfire-ash text-sm">Выберите до 3 рецензий, которые будут отображаться на вашей витрине.</p>
                  {reviews.length > 0 ? (
                      <ul className="space-y-3 max-h-96 overflow-y-auto pr-2 custom-scrollbar">
                          {reviews.map(review => {
                              const reviewMedia = review.expand?.media_id;
                              const reviewSeason = review.expand?.season_id;
                              const isSelected = selectedShowcaseReviewIds.includes(review.id);

                              const reviewTitle = reviewMedia
                                  ? `${reviewMedia.title}${reviewSeason ? ` - Сезон ${reviewSeason.season_number}${reviewSeason.title ? `: ${reviewSeason.title}` : ''}` : ''}`
                                  : 'Загрузка...';


                              return (
                                  <li
                                      key={review.id}
                                      className={`p-3 rounded-md border cursor-pointer flex items-center justify-between transition-colors duration-200
                                          ${isSelected
                                              ? 'bg-campfire-amber/20 border-campfire-amber text-campfire-light'
                                              : 'bg-campfire-dark border-campfire-ash/30 text-campfire-ash hover:bg-campfire-ash/10'
                                          }`}
                                      onClick={() => handleToggleShowcaseReview(review.id)}
                                  >
                                      <div className="flex-grow mr-4">
                                          <p className="font-semibold text-sm">{reviewTitle}</p>
                                          <p className="text-xs mt-1 flex items-center">
                                             Оценка: <span className="flex items-center text-campfire-amber ml-1 font-bold">
                                                <FaFire className="mr-1 text-xs" />
                                                {review.overall_rating !== null && review.overall_rating !== undefined ? review.overall_rating.toFixed(1) : 'N/A'} / 10
                                             </span>
                                          </p>
                                      </div>
                                      {isSelected ? (
                                          <FaCheckCircle size={20} className="text-campfire-amber" />
                                      ) : (
                                          <FaRegCircle size={20} className="text-campfire-ash" />
                                      )}
                                  </li>
                              );
                          })}
                      </ul>
                  ) : (
                      <div className="text-center py-4 text-campfire-ash">
                          У вас пока нет рецензий для добавления на витрину.
                      </div>
                  )}

                  {/* Form Actions */}
                  <div className="flex justify-end space-x-4 mt-6">
                      <button
                          type="button"
                          onClick={handleCancelShowcase}
                          className="btn-secondary"
                          disabled={isSubmittingEdit}
                      >
                          Отмена
                      </button>
                      <button
                          type="button"
                          onClick={handleSaveShowcase}
                          className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
                          disabled={isSubmittingEdit}
                      >
                          {isSubmittingEdit ? 'Сохранение...' : 'Сохранить витрину'}
                      </button>
                  </div>
              </div>
          </Modal>
      )}

      {/* Achievement Assignment Modal */}
      {profileUser && isAdmin && (
          <Modal
              isOpen={isAssigningAchievements}
              onClose={handleCancelAchievementAssignment}
              title={`Назначить достижения для ${profileUser.username}`}
              size="lg"
          >
              <div className="space-y-4">
                  {editFormError && (
                      <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg">
                          Ошибка: {editFormError}
                      </div>
                  )}
                  <p className="text-campfire-ash text-sm">Выберите достижения, которые нужно назначить или снять с пользователя.</p>
                  
                  {availableAchievements.length > 0 ? (
                      <ul className="space-y-3 max-h-96 overflow-y-auto pr-2 custom-scrollbar">
                          {availableAchievements.map((achievement) => {
                              const isSelected = selectedAchievementIdsToAssign.includes(achievement.id);
                              return (
                                  <li
                                      key={achievement.id}
                                      onClick={() => handleToggleAchievementAssignment(achievement.id)}
                                      className={`p-3 rounded-md border cursor-pointer flex items-center justify-between transition-colors duration-200
                                          ${isSelected
                                              ? 'bg-campfire-amber/20 border-campfire-amber text-campfire-light'
                                              : 'bg-campfire-dark border-campfire-ash/30 text-campfire-ash hover:bg-campfire-ash/10'
                                          }`}
                                  >
                                      <div className="flex-grow mr-4">
                                          <p className="font-semibold text-sm">{achievement.title}</p>
                                          <p className="text-xs text-campfire-ash mt-1">{achievement.description}</p>
                                           {achievement.xp_reward > 0 && (
                                              <p className="text-campfire-light text-xs mt-1 flex items-center">
                                                  <FaFire className="mr-1 text-campfire-amber" /> +{achievement.xp_reward} XP
                                              </p>
                                           )}
                                      </div>
                                      {isSelected ? (
                                          <FaCheckCircle size={20} className="text-campfire-amber" />
                                      ) : (
                                          <FaRegCircle size={20} className="text-campfire-ash" />
                                      )}
                                  </li>
                              );
                          })}
                      </ul>
                  ) : (
                      <div className="text-center py-4 text-campfire-ash">
                          Нет доступных достижений.
                      </div>
                  )}

                  <div className="flex justify-end space-x-4 mt-6">
                      <button
                          onClick={handleCancelAchievementAssignment}
                          className="btn-secondary"
                          disabled={isSubmittingEdit}
                      >
                          Отмена
                      </button>
                      <button
                          onClick={handleSaveAchievementAssignment}
                          className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
                          disabled={isSubmittingEdit}
                      >
                          {isSubmittingEdit ? 'Сохранение...' : 'Сохранить изменения'}
                      </button>
                  </div>
              </div>
          </Modal>
      )}

      {/* Theme Customization Modal */}
      {isCustomizingTheme && (
          <Modal
              isOpen={isCustomizingTheme}
              onClose={() => setIsCustomizingTheme(false)}
              title="Настройка темы витрины"
              size="xl"
          >
              <div className="space-y-6">
                  <div className="grid grid-cols-2 gap-6">
                      {/* Preview */}
                      <div className="relative h-[300px] rounded-2xl overflow-hidden" style={{ backgroundColor: previewTheme.background }}>
                          <div className="absolute inset-0">
                              {previewTheme.type === 'squares' && (
                                  <Squares 
                                      direction={previewTheme.squares.direction}
                                      speed={previewTheme.squares.speed}
                                      borderColor={previewTheme.squares.borderColor}
                                      squareSize={previewTheme.squares.squareSize}
                                      hoverFillColor={previewTheme.squares.hoverFillColor}
                                  />
                              )}
                              {previewTheme.type === 'dither' && (
                                  <Dither
                                      waveSpeed={previewTheme.dither.waveSpeed}
                                      waveFrequency={previewTheme.dither.waveFrequency}
                                      waveAmplitude={previewTheme.dither.waveAmplitude}
                                      waveColor={previewTheme.dither.waveColor}
                                      colorNum={previewTheme.dither.colorNum}
                                      pixelSize={previewTheme.dither.pixelSize}
                                      enableMouseInteraction={previewTheme.dither.enableMouseInteraction}
                                      mouseRadius={previewTheme.dither.mouseRadius}
                                  />
                              )}
                          </div>
                      </div>

                      {/* Controls */}
                      <div className="space-y-4">
                          <div>
                              <label className="block text-sm font-medium text-campfire-light mb-2">
                                  Тип темы
                              </label>
                              <select
                                  value={previewTheme.type}
                                  onChange={(e) => setPreviewTheme(prev => ({ ...prev, type: e.target.value }))}
                                  className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light focus:ring-2 focus:ring-campfire-amber focus:border-transparent transition-colors"
                              >
                                  <option value="none">Без темы</option>
                                  <option value="background" disabled={!isThemeAvailable('background')}>
                                      Цвет фона {!isThemeAvailable('background') && '(Доступно со 2 уровня)'}
                                  </option>
                                  <option value="squares" disabled={!isThemeAvailable('squares')}>
                                      Квадраты {!isThemeAvailable('squares') && '(Доступно с 3 уровня)'}
                                  </option>
                                  <option value="dither" disabled={!isThemeAvailable('dither')}>
                                      Волны {!isThemeAvailable('dither') && '(Доступно с 7 уровня)'}
                                  </option>
                              </select>
                          </div>

                          {previewTheme.type === 'background' && (
                              <div>
                                  <div className="flex justify-between items-center mb-2">
                                      <label className="text-sm font-medium text-campfire-light">
                                          Цвет фона
                                      </label>
                                      <div className="w-6 h-6 rounded-full border border-campfire-ash/30" style={{ backgroundColor: previewTheme.background }}></div>
                                  </div>
                                  <input
                                      type="color"
                                      value={previewTheme.background}
                                      onChange={(e) => setPreviewTheme(prev => ({ ...prev, background: e.target.value }))}
                                      className="w-full h-10 rounded-md cursor-pointer [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-md"
                                  />
                              </div>
                          )}

                          {previewTheme.type === 'squares' && isThemeAvailable('squares') && (
                              <>
                                  <div>
                                      <div className="flex justify-between items-center mb-2">
                                          <label className="text-sm font-medium text-campfire-light">
                                              Направление
                                          </label>
                                          <select
                                              value={previewTheme.squares.direction}
                                              onChange={(e) => handleThemeParamChange('squares', 'direction', e.target.value)}
                                              className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light focus:ring-2 focus:ring-campfire-amber focus:border-transparent transition-colors"
                                          >
                                              <option value="up">Вверх</option>
                                              <option value="down">Вниз</option>
                                              <option value="left">Влево</option>
                                              <option value="right">Вправо</option>
                                              <option value="diagonal">По диагонали</option>
                                          </select>
                                      </div>
                                      <div>
                                          <div className="flex justify-between items-center mb-2">
                                              <label className="text-sm font-medium text-campfire-light">
                                                  Скорость
                                              </label>
                                              <span className="text-xs text-campfire-ash">{previewTheme.squares.speed.toFixed(1)}</span>
                                          </div>
                                          <input
                                              type="range"
                                              min="0.1"
                                              max="1"
                                              step="0.1"
                                              value={previewTheme.squares.speed}
                                              onChange={(e) => handleThemeParamChange('squares', 'speed', parseFloat(e.target.value))}
                                              className="w-full h-1 bg-campfire-ash/20 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-campfire-amber [&::-webkit-slider-thumb]:cursor-pointer [&::-webkit-slider-thumb]:transition-all [&::-webkit-slider-thumb]:hover:scale-110 [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-campfire-amber [&::-moz-range-thumb]:cursor-pointer [&::-moz-range-thumb]:transition-all [&::-moz-range-thumb]:hover:scale-110 [&::-moz-range-thumb]:border-0"
                                          />
                                      </div>
                                      <div>
                                          <div className="flex justify-between items-center mb-2">
                                              <label className="text-sm font-medium text-campfire-light">
                                                  Цвет границ
                                              </label>
                                              <div className="w-6 h-6 rounded-full border border-campfire-ash/30" style={{ backgroundColor: previewTheme.squares.borderColor }}></div>
                                          </div>
                                          <input
                                              type="color"
                                              value={previewTheme.squares.borderColor}
                                              onChange={(e) => handleThemeParamChange('squares', 'borderColor', e.target.value)}
                                              className="w-full h-10 rounded-md cursor-pointer [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-md [&::-moz-color-swatch]:border-0 [&::-moz-color-swatch]:rounded-md"
                                          />
                                      </div>
                                      <div>
                                          <div className="flex justify-between items-center mb-2">
                                              <label className="text-sm font-medium text-campfire-light">
                                                  Размер квадратов
                                              </label>
                                              <span className="text-xs text-campfire-ash">{previewTheme.squares.squareSize}px</span>
                                          </div>
                                          <input
                                              type="range"
                                              min="10"
                                              max="50"
                                              step="1"
                                              value={previewTheme.squares.squareSize}
                                              onChange={(e) => handleThemeParamChange('squares', 'squareSize', parseInt(e.target.value))}
                                              className="w-full h-1 bg-campfire-ash/20 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-campfire-amber [&::-webkit-slider-thumb]:cursor-pointer [&::-webkit-slider-thumb]:transition-all [&::-webkit-slider-thumb]:hover:scale-110 [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-campfire-amber [&::-moz-range-thumb]:cursor-pointer [&::-moz-range-thumb]:transition-all [&::-moz-range-thumb]:hover:scale-110 [&::-moz-range-thumb]:border-0"
                                          />
                                      </div>
                                      <div>
                                          <div className="flex justify-between items-center mb-2">
                                              <label className="text-sm font-medium text-campfire-light">
                                                  Цвет при наведении
                                              </label>
                                              <div className="w-6 h-6 rounded-full border border-campfire-ash/30" style={{ backgroundColor: previewTheme.squares.hoverFillColor }}></div>
                                          </div>
                                          <input
                                              type="color"
                                              value={previewTheme.squares.hoverFillColor}
                                              onChange={(e) => handleThemeParamChange('squares', 'hoverFillColor', e.target.value)}
                                              className="w-full h-10 rounded-md cursor-pointer [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-md [&::-moz-color-swatch]:border-0 [&::-moz-color-swatch]:rounded-md"
                                          />
                                      </div>
                                      <div>
                                          <div className="flex justify-between items-center mb-2">
                                              <label className="text-sm font-medium text-campfire-light">
                                                  Цвет фона квадратов
                                              </label>
                                              <div className="w-6 h-6 rounded-full border border-campfire-ash/30" style={{ backgroundColor: previewTheme.squares.backgroundColor }}></div>
                                          </div>
                                          <input
                                              type="color"
                                              value={previewTheme.squares.backgroundColor}
                                              onChange={(e) => handleThemeParamChange('squares', 'backgroundColor', e.target.value)}
                                              className="w-full h-10 rounded-md cursor-pointer [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-md [&::-moz-color-swatch]:border-0 [&::-moz-color-swatch]:rounded-md"
                                          />
                                      </div>
                                  </div>
                              </>
                          )}
                      </div>
                  </div>

                  {/* Modal Actions */}
                  <div className="flex justify-end space-x-4 mt-6">
                      <button
                          type="button"
                          onClick={() => setIsCustomizingTheme(false)}
                          className="btn-secondary"
                      >
                          Отмена
                      </button>
                      <button
                          type="button"
                          onClick={handleSaveTheme}
                          className="btn-primary"
                      >
                          Сохранить тему
                      </button>
                  </div>
              </div>
          </Modal>
      )}

    </div>
  );
};

export default ProfilePage;
