// WeddingGallery.tsx
import React, { JSX, useCallback, useEffect, useState } from 'react';
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  CardMedia,
  Chip,
  CircularProgress,
  Container,
  CssBaseline,
  Grid,
  IconButton,
  LinearProgress,
  Paper,
  Snackbar,
  TextField,
  ThemeProvider,
  Toolbar,
  Typography,
  createTheme,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  alpha,
  styled,
  AppBar,
  Tabs,
  Tab,
} from '@mui/material';
import {
  // CameraAlt,
  CloudUpload,
  Delete as DeleteIcon,
  Download,
  Replay,
  PhotoAlbum,
  Celebration,
  Diamond,
  AddPhotoAlternate,
  FolderOpen,
  LocalFlorist,
  Favorite,
  Event,
  People,
  LocationOn,
  // DateRange,
  Timeline,
  ChevronRight,
  PhotoCamera,
  Videocam,
} from '@mui/icons-material';
import { useDropzone } from 'react-dropzone';
import LightboxModal from './LightboxModal';

/* ============================
   Types
   ============================ */
type WeddingPhoto = {
  id: number | string;
  url: string;
  title?: string;
  filename?: string;
  created_at?: string;
  date?: string;
  path?: string;
};

type FileQueueItem = {
  id: string;
  file: File;
  previewUrl: string;
  progress: number;
  status: 'pending' | 'uploading' | 'done' | 'error';
  error?: string;
  uploadedPhoto?: WeddingPhoto;
};

type FolderInfo = {
  title: string;
  count: number;
  thumb?: string;
  date?: string;
  description?: string;
};

type StoryStep = {
  title: string;
  description: string;
  icon: React.ReactNode;
  photos?: WeddingPhoto[];
};

/* ============================
   Config
   ============================ */
const MFS_API_BASE = 'https://mfs-api.midastix.com';
const MAX_FILE_SIZE = 10 * 1024 * 1024;
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const MAX_QUEUE_FILES = 30;

/* ============================
   Styled Components
   ============================ */
const FloralBackground = styled(Box)(() => ({
  position: 'fixed',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  backgroundImage: `
    radial-gradient(circle at 20% 80%, ${alpha('#ffebee', 0.1)} 0%, transparent 20%),
    radial-gradient(circle at 80% 20%, ${alpha('#e8f5e9', 0.1)} 0%, transparent 20%),
    radial-gradient(circle at 40% 40%, ${alpha('#f3e5f5', 0.1)} 0%, transparent 30%),
    radial-gradient(circle at 60% 60%, ${alpha('#e3f2fd', 0.1)} 0%, transparent 25%)
  `,
  pointerEvents: 'none',
  zIndex: -1,
}));

const GoldButton = styled(Button)(() => ({
  background: 'linear-gradient(135deg, #d4af37 0%, #ffd700 50%, #d4af37 100%)',
  color: '#2c1810',
  fontWeight: 600,
  padding: '12px 32px',
  borderRadius: '50px',
  textTransform: 'none',
  letterSpacing: '0.5px',
  transition: 'all 0.3s ease',
  boxShadow: '0 4px 20px rgba(212, 175, 55, 0.3)',
  '&:hover': {
    transform: 'translateY(-2px)',
    boxShadow: '0 8px 25px rgba(212, 175, 55, 0.4)',
  },
  '&:disabled': {
    background: 'linear-gradient(135deg, #cccccc 0%, #aaaaaa 100%)',
    boxShadow: 'none',
  },
}));

const DropzoneArea = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(4),
  border: `2px dashed ${alpha('#d4af37', 0.4)}`,
  borderRadius: '20px',
  background: `linear-gradient(135deg, ${alpha('#fffaf0', 0.9)} 0%, ${alpha('#fff8e1', 0.9)} 100%)`,
  transition: 'all 0.3s ease',
  cursor: 'pointer',
  textAlign: 'center',
  '&:hover': {
    borderColor: '#d4af37',
    background: `linear-gradient(135deg, ${alpha('#fffaf0', 1)} 0%, ${alpha('#fff8e1', 1)} 100%)`,
    transform: 'translateY(-2px)',
    boxShadow: '0 12px 24px rgba(212, 175, 55, 0.15)',
  },
}));

const AlbumCard = styled(Card)(() => ({
  position: 'relative',
  borderRadius: '16px',
  overflow: 'hidden',
  transition: 'all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275)',
  background: 'linear-gradient(145deg, #ffffff 0%, #fafafa 100%)',
  boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)',
  border: '1px solid rgba(255, 255, 255, 0.3)',
  height: '100%',
  '&:hover': {
    transform: 'translateY(-8px)',
    boxShadow: '0 20px 40px rgba(0, 0, 0, 0.15)',
    '& .album-overlay': {
      opacity: 1,
    },
  },
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: '4px',
    background: 'linear-gradient(90deg, #d4af37 0%, #ffd700 50%, #d4af37 100%)',
    zIndex: 1,
  },
}));

const AlbumOverlay = styled(Box)(({ theme }) => ({
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  background: 'linear-gradient(0deg, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.2) 50%, rgba(0,0,0,0) 100%)',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'flex-end',
  padding: theme.spacing(3),
  color: 'white',
}));

const PhotoCard = styled(Card)(() => ({
  position: 'relative',
  borderRadius: '12px',
  overflow: 'hidden',
  transition: 'all 0.3s ease',
  '&:hover': {
    transform: 'scale(1.03)',
    boxShadow: '0 12px 28px rgba(0, 0, 0, 0.2)',
    '& .photo-actions': {
      opacity: 1,
    },
  },
}));

const PhotoActions = styled(Box)(({ theme }) => ({
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  background: 'linear-gradient(to bottom, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0) 100%)',
  padding: theme.spacing(1),
  opacity: 0,
  transition: 'opacity 0.3s ease',
  display: 'flex',
  justifyContent: 'flex-end',
  gap: theme.spacing(1),
}));

const FloatingActionButton = styled(IconButton)(() => ({

  position: 'fixed',
  bottom: 24,
  right: 24,
  background: 'linear-gradient(135deg, #d4af37 0%, #ffd700 100%)',
  color: '#2c1810',
  width: 56,
  height: 56,
  boxShadow: '0 8px 25px rgba(212, 175, 55, 0.4)',
  zIndex: 1000,
  '&:hover': {
    background: 'linear-gradient(135deg, #c19b2a 0%, #e6c200 100%)',
    transform: 'scale(1.1)',
  },
}));

const StoryStepCard = styled(Paper)(({ theme }) => ({
  position: 'relative',
  padding: theme.spacing(3),
  borderRadius: '16px',
  background: 'rgba(255, 255, 255, 0.95)',
  boxShadow: '0 8px 32px rgba(0, 0, 0, 0.08)',
  border: '1px solid rgba(255, 255, 255, 0.3)',
  '&:hover': {
    transform: 'translateY(-4px)',
    boxShadow: '0 16px 40px rgba(0, 0, 0, 0.12)',
  },
}));

const WeddingHeader = styled(AppBar)(() => ({
  background: 'linear-gradient(135deg, rgba(15, 118, 110, 0.95) 0%, rgba(45, 212, 191, 0.9) 100%)',
  backdropFilter: 'blur(10px)',
  boxShadow: '0 4px 30px rgba(0, 0, 0, 0.1)',
  borderBottom: '2px solid rgba(212, 175, 55, 0.3)',
}));

/* ============================
   Helper Functions
   ============================ */
const toAbsoluteUrl = (path?: string) => {
  if (!path) return '';
  if (path.startsWith('http://') || path.startsWith('https://')) return path;
  return `${MFS_API_BASE}${path}`;
};

const uploadFileXHR = (
  file: File,
  onProgress: (pct: number) => void,
  title?: string
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<{ success: boolean; data?: any; error?: string }> =>
  new Promise((resolve) => {
    try {
      const xhr = new XMLHttpRequest();
      const url = `${MFS_API_BASE}/image-upload/single`;
      xhr.open('POST', url, true);
      xhr.setRequestHeader('Accept', 'application/json');

      xhr.upload.onprogress = (ev) => {
        if (!ev.lengthComputable) return;
        const pct = Math.round((ev.loaded / ev.total) * 100);
        onProgress(pct);
      };

      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const json = JSON.parse(xhr.responseText);
            resolve({ success: true, data: json });
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
          } catch (e) {
            resolve({ success: true, data: xhr.responseText });
          }
        } else {
          const txt = xhr.responseText || `HTTP ${xhr.status}`;
          resolve({ success: false, error: txt });
        }
      };

      xhr.onerror = () => resolve({ success: false, error: 'Network error' });

      const fd = new FormData();
      fd.append('file', file, file.name);
      if (title) fd.append('title', title);

      xhr.send(fd);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      resolve({ success: false, error: err?.message ?? String(err) });
    }
  });

const fetchImagesApi = async (title = ''): Promise<WeddingPhoto[]> => {
  const url =
    title && title.trim() !== '' ? `${MFS_API_BASE}/image-upload?title=${encodeURIComponent(title)}` : `${MFS_API_BASE}/image-upload`;
  const res = await fetch(url, { headers: { accept: 'application/json' } });
  if (!res.ok) {
    const txt = await res.text();
    throw new Error(txt || `HTTP ${res.status}`);
  }
  const body = await res.json();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let imagesArray: any[] = [];
  if (Array.isArray(body)) imagesArray = body;
  else if (Array.isArray(body.images)) imagesArray = body.images;
  else if (body.data && Array.isArray(body.data.images)) imagesArray = body.data.images;
  else {
    const firstArray = Object.values(body).find((v) => Array.isArray(v));
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    if (Array.isArray(firstArray)) imagesArray = firstArray as any[];
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return imagesArray.map((it: any) => ({
    id: it.id ?? it._id ?? `${it.filename ?? Math.random()}`,
    url: toAbsoluteUrl(it.path ?? it.url),
    title: it.title ?? it.filename ?? '',
    filename: it.filename,
    created_at: it.created_at ?? it.createdAt,
    date: it.date,
    path: it.path,
  }));
};

const deletePhotoApi = async (id: number | string) => {
  const url = `${MFS_API_BASE}/image-upload/id/${id}`;
  const res = await fetch(url, { method: 'DELETE', headers: { accept: 'application/json' } });
  const txt = await res.text();
  if (!res.ok) throw new Error(txt || `HTTP ${res.status}`);
  return txt || 'deleted';
};

const deleteFolderApi = async (title: string) => {
  const url = `${MFS_API_BASE}/image-upload/folder?title=${encodeURIComponent(title)}`;
  const res = await fetch(url, { method: 'DELETE', headers: { accept: 'application/json' } });
  const txt = await res.text();
  if (!res.ok) throw new Error(txt || `HTTP ${res.status}`);
  return txt || 'folder deleted';
};

/* ============================
   Theme
   ============================ */
const theme = createTheme({
  palette: {
    primary: { main: '#0f766e', light: '#2dd4bf' },
    secondary: { main: '#d4af37', light: '#ffd700' },
    background: {
      default: '#fefefe',
      paper: '#fff'
    },
    text: {
      primary: '#2c1810',
      secondary: '#6b7280'
    },
  },
  typography: {
    fontFamily: '"Poppins", "Inter", -apple-system, BlinkMacSystemFont, sans-serif',
    h1: {
      fontFamily: '"Great Vibes", cursive',
      fontSize: '3.5rem',
      fontWeight: 400,
      letterSpacing: '1px',
    },
    h2: {
      fontFamily: '"Great Vibes", cursive',
      fontSize: '2.8rem',
      fontWeight: 400,
    },
    h3: {
      fontFamily: '"Playfair Display", serif',
      fontWeight: 600,
    },
    h4: {
      fontFamily: '"Playfair Display", serif',
      fontWeight: 500,
    },
    h5: {
      fontFamily: '"Poppins", sans-serif',
      fontWeight: 500,
    },
    h6: {
      fontFamily: '"Poppins", sans-serif',
      fontWeight: 500,
    },
    body1: {
      fontFamily: '"Inter", sans-serif',
      lineHeight: 1.6,
    },
    body2: {
      fontFamily: '"Inter", sans-serif',
      lineHeight: 1.5,
    },
  },
  shape: {
    borderRadius: 16,
  },
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          borderRadius: 12,
          textTransform: 'none',
          fontWeight: 500,
        },
      },
    },
    MuiPaper: {
      styleOverrides: {
        root: {
          borderRadius: 16,
        },
      },
    },
    MuiCard: {
      styleOverrides: {
        root: {
          borderRadius: 16,
        },
      },
    },
    MuiTab: {
      styleOverrides: {
        root: {
          textTransform: 'none',
          fontWeight: 500,
          fontSize: '1rem',
        },
      },
    },
  },
});

/* ============================
   Component
   ============================ */
export default function WeddingGallery(): JSX.Element {
  const [photosAll, setPhotosAll] = useState<WeddingPhoto[]>([]);
  const [folders, setFolders] = useState<FolderInfo[]>([]);
  const [folderOpenTitle, setFolderOpenTitle] = useState<string | null>(null);
  const [folderPhotos, setFolderPhotos] = useState<WeddingPhoto[]>([]);
  const [folderModalOpen, setFolderModalOpen] = useState(false);

  const [queue, setQueue] = useState<FileQueueItem[]>([]);
  const [commonTitle, setCommonTitle] = useState<string>('');
  const [snackbar, setSnackbar] = useState<{ open: boolean; severity?: 'success' | 'error' | 'info'; message: string }>({
    open: false,
    severity: 'info',
    message: '',
  });

  const [deletingId, setDeletingId] = useState<number | string | null>(null);
  const [deletingFolder, setDeletingFolder] = useState<string | null>(null);

  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxStartIndex, setLightboxStartIndex] = useState(0);
  const [showUploadPanel, setShowUploadPanel] = useState(false);
  const [activeTab, setActiveTab] = useState(0);

  // Storyline steps
  const [storySteps] = useState<StoryStep[]>([
    {
      title: 'The Proposal',
      description: 'The magical moment when everything began',
      icon: <Favorite />,
    },
    {
      title: 'Engagement Shoot',
      description: 'Capturing our love and excitement',
      icon: <PhotoCamera />,
    },
    {
      title: 'Wedding Planning',
      description: 'Preparing for our dream day',
      icon: <Event />,
    },
    {
      title: 'The Ceremony',
      description: 'Saying "I Do" surrounded by loved ones',
      icon: <People />,
    },
    {
      title: 'Reception',
      description: 'Celebrating with family and friends',
      icon: <Celebration />,
    },
    {
      title: 'Honeymoon',
      description: 'Beginning our journey together',
      icon: <LocationOn />,
    },
  ]);

  const loadAll = useCallback(async () => {
    try {
      const items = await fetchImagesApi('');
      setPhotosAll(items);

      // Group photos by title/album
      const map = new Map<string, FolderInfo>();
      items.forEach((it) => {
        const title = it.title ?? 'Untitled';
        if (!map.has(title)) {
          map.set(title, {
            title,
            count: 0,
            thumb: it.url,
            date: it.date || it.created_at,
          });
        }
        const entry = map.get(title)!;
        entry.count += 1;
        if (!entry.thumb) entry.thumb = it.url;
      });

      const folderArray = Array.from(map.values()).sort((a, b) => b.count - a.count);

      // Add sample descriptions for demo
      const sampleDescriptions = [
        'Beautiful moments from our special day',
        'Cherished memories with family and friends',
        'Every glance, every smile, every tear of joy',
        'The beginning of our forever journey',
        'Love, laughter, and happily ever after',
      ];

      folderArray.forEach((folder, index) => {
        folder.description = sampleDescriptions[index % sampleDescriptions.length];
      });

      setFolders(folderArray);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      console.error('loadAll error', err);
      setFolders([]);
      setSnackbar({ open: true, severity: 'error', message: `Failed to load: ${err?.message || err}` });
    }
  }, []);

  useEffect(() => {
    loadAll();
    return () => {
      queue.forEach((q) => {
        try {
          URL.revokeObjectURL(q.previewUrl);
        } catch {
          //ignore
        }
      });
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /* ============================
     Dropzone
  ============================ */
  const onDrop = useCallback((acceptedFiles: File[]) => {
    if (!acceptedFiles || acceptedFiles.length === 0) return;

    const currentCount = queue.length;
    const available = Math.max(0, MAX_QUEUE_FILES - currentCount);

    if (available <= 0) {
      setSnackbar({ open: true, severity: 'error', message: `Maximum ${MAX_QUEUE_FILES} files allowed.` });
      return;
    }

    const acceptedToAdd = acceptedFiles.slice(0, available);
    const rejectedCount = acceptedFiles.length - acceptedToAdd.length;

    const now = Date.now();
    const items: FileQueueItem[] = acceptedToAdd.map((f, i) => {
      const id = `${now}-${currentCount + i}-${f.name}`;
      const tooLarge = f.size > MAX_FILE_SIZE;
      const invalidType = ALLOWED_TYPES.length > 0 && !ALLOWED_TYPES.includes(f.type);
      return {
        id,
        file: f,
        previewUrl: URL.createObjectURL(f),
        progress: 0,
        status: tooLarge || invalidType ? 'error' : 'pending',
        error: tooLarge ? `File too large ${(f.size / (1024 * 1024)).toFixed(1)}MB` : invalidType ? 'Invalid type' : undefined,
      } as FileQueueItem;
    });

    setQueue((prev) => [...items, ...prev]);
    setShowUploadPanel(true);

    if (rejectedCount > 0) {
      setSnackbar({
        open: true,
        severity: 'info',
        message: `Added ${acceptedToAdd.length} file(s). ${rejectedCount} file(s) were not added.`,
      });
    } else {
      setSnackbar({ open: true, severity: 'success', message: `Added ${acceptedToAdd.length} file(s)` });
    }
  }, [queue.length]);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    multiple: true,
    maxSize: MAX_FILE_SIZE,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    accept: ALLOWED_TYPES.length ? ALLOWED_TYPES.reduce((acc, t) => ({ ...acc, [t]: [] }), {} as any) : undefined,
  });

  /* ============================
     Upload logic
  ============================ */
  const uploadSingle = useCallback(
    async (item: FileQueueItem) => {
      setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, status: 'uploading', progress: 0, error: undefined } : q)));
      const res = await uploadFileXHR(item.file, (pct) => {
        setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, progress: pct } : q)));
      }, commonTitle || undefined);

      if (res.success) {
        const it = res.data;
        const uploadedPhoto: WeddingPhoto = {
          id: it.id ?? it._id,
          url: toAbsoluteUrl(it.path ?? it.url),
          title: it.title ?? it.filename ?? commonTitle ?? 'Untitled',
          filename: it.filename,
          created_at: it.created_at ?? it.createdAt,
          path: it.path,
        };
        setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, status: 'done', progress: 100, uploadedPhoto } : q)));
        setPhotosAll((prev) => [uploadedPhoto, ...prev]);
        await loadAll();
        return true;
      } else {
        setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, status: 'error', error: res.error } : q)));
        console.error('upload failed', res.error);
        return false;
      }
    },
    [commonTitle, loadAll]
  );

  const uploadAll = useCallback(async () => {
    const pending = queue.filter((q) => q.status === 'pending' || q.status === 'error');
    if (!pending.length) {
      setSnackbar({ open: true, severity: 'info', message: 'No files to upload' });
      return;
    }
    for (const item of pending) {
      await uploadSingle(item);
    }
    setSnackbar({ open: true, severity: 'success', message: 'All photos uploaded successfully!' });
    setQueue((prev) => prev.filter((q) => q.status !== 'done'));
  }, [queue, uploadSingle]);

  const retryOne = (id: string) => {
    const item = queue.find((q) => q.id === id);
    if (item) uploadSingle(item);
  };

  const removeOne = (id: string) => {
    const item = queue.find((q) => q.id === id);
    if (item) {
      try {
        URL.revokeObjectURL(item.previewUrl);
      } catch {
        //ignore
      }
    }
    setQueue((prev) => prev.filter((q) => q.id !== id));
  };

  /* ============================
     Folder Management
  ============================ */
  const openFolder = async (title: string) => {
    setFolderOpenTitle(title);
    try {
      const items = await fetchImagesApi(title);
      setFolderPhotos(items);
      setFolderModalOpen(true);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      console.error('openFolder error', err);
      setSnackbar({ open: true, severity: 'error', message: `Failed to load folder: ${err?.message || err}` });
    }
  };

  const handleDeletePhoto = async (id: number | string) => {
    // if (!confirm('Delete this photo? This cannot be undone.')) return;
    setDeletingId(id);
    try {
      await deletePhotoApi(id);
      setFolderPhotos((prev) => prev.filter((p) => p.id !== id));
      setPhotosAll((prev) => prev.filter((p) => p.id !== id));
      setSnackbar({ open: true, severity: 'success', message: 'Photo deleted' });
      await loadAll();
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      console.error('deletePhoto error', err);
      setSnackbar({ open: true, severity: 'error', message: `Failed to delete: ${err?.message || err}` });
    } finally {
      setDeletingId(null);
    }
  };

  const handleDeleteFolder = async (title: string) => {
    if (!confirm(`Delete "${title}" and all ${folders.find(f => f.title === title)?.count || 0} photos?`)) return;
    setDeletingFolder(title);
    try {
      await deleteFolderApi(title);
      setSnackbar({ open: true, severity: 'success', message: `Folder "${title}" deleted` });
      await loadAll();
      setFolderModalOpen(false);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      console.error('deleteFolder error', err);
      setSnackbar({ open: true, severity: 'error', message: `Failed to delete folder: ${err?.message || err}` });
    } finally {
      setDeletingFolder(null);
    }
  };

  /* ============================
     UI
  ============================ */
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />

      <FloralBackground />

      <style>
        {`
          @import url('https://fonts.googleapis.com/css2?family=Great+Vibes&family=Playfair+Display:wght@400;500;600;700&family=Poppins:wght@400;500;600&family=Inter:wght@300;400;500&display=swap');
          
          body {
            background: #fefefe;
            min-height: 100vh;
            margin: 0;
          }
          
          ::selection {
            background: rgba(212, 175, 55, 0.3);
            color: #2c1810;
          }
          
          .gold-gradient-text {
            background: linear-gradient(135deg, #d4af37 0%, #ffd700 50%, #d4af37 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
          }
        `}
      </style>

      {/* Header */}
      <WeddingHeader position="sticky">
        <Toolbar>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexGrow: 1 }}>
            <LocalFlorist sx={{ color: '#ffd700', fontSize: 28 }} />
            <Typography variant="h6" sx={{
              fontFamily: '"Great Vibes", cursive',
              fontSize: '1.8rem',
              flexGrow: 1,
            }}>
              Sakashi and Chirags Wedding Memories
            </Typography>

            <Tabs
              value={activeTab}
              onChange={(e, newValue) => setActiveTab(newValue)}
              sx={{
                display: { xs: 'none', md: 'flex' },
                '& .MuiTabs-indicator': {
                  backgroundColor: '#ffd700',
                },
              }}
            >
              <Tab
                icon={<PhotoAlbum sx={{ mr: 1 }} />}
                iconPosition="start"
                label="Albums"
                sx={{ color: 'white' }}
              />
              <Tab
                icon={<Timeline sx={{ mr: 1 }} />}
                iconPosition="start"
                label="Our Story"
                sx={{ color: 'white' }}
              />
              <Tab
                icon={<Videocam sx={{ mr: 1 }} />}
                iconPosition="start"
                label="Moments"
                sx={{ color: 'white' }}
              />
            </Tabs>
          </Box>

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Chip
              icon={<Favorite />}
              label="Love Story"
              sx={{
                bgcolor: 'rgba(255, 215, 0, 0.2)',
                color: '#ffd700',
                border: '1px solid rgba(255, 215, 0, 0.3)',
                display: { xs: 'none', sm: 'flex' },
              }}
            />
            <IconButton
              color="inherit"
              onClick={() => setShowUploadPanel(true)}
              sx={{ color: '#ffd700' }}
            >
              <AddPhotoAlternate />
            </IconButton>
          </Box>
        </Toolbar>
      </WeddingHeader>

      <Container maxWidth="xl" sx={{ py: 6 }}>
        {/* Tab Content */}
        {activeTab === 0 && (
          <Box>
            {/* Hero Section */}
            <Box sx={{
              textAlign: 'center',
              mb: 6,
              px: { xs: 2, md: 0 },
            }}>
              <Typography variant="h1" className="gold-gradient-text" gutterBottom>
                Our Wedding Albums
              </Typography>
              <Typography variant="h5" sx={{
                color: 'primary.main',
                mb: 2,
                fontFamily: '"Playfair Display", serif',
              }}>
                Preserving precious memories of our special day
              </Typography>
            </Box>

            {/* Upload Section (Collapsible) */}
            {showUploadPanel && (
              <Paper
                sx={{
                  p: 3,
                  mb: 4,
                  background: 'linear-gradient(135deg, rgba(255, 250, 240, 0.95) 0%, rgba(255, 248, 225, 0.95) 100%)',
                  border: '1px solid rgba(212, 175, 55, 0.2)',
                  boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
                }}
              >
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                  <Typography variant="h6">
                    📸 Upload Photos
                  </Typography>
                  <IconButton onClick={() => setShowUploadPanel(false)} size="small">
                    <DeleteIcon />
                  </IconButton>
                </Box>

                <Box sx={{ mb: 3 }}>
                  <DropzoneArea {...getRootProps()}>
                    <input {...getInputProps()} />
                    <Box sx={{ py: 3 }}>
                      <CloudUpload sx={{ fontSize: 48, color: 'secondary.main', mb: 2, opacity: 0.8 }} />
                      <Typography variant="h6" sx={{ mb: 1 }}>
                        {isDragActive ? 'Drop photos here' : 'Drag & drop photos here'}
                      </Typography>
                      <Typography variant="body2" sx={{ color: 'text.secondary', mb: 2 }}>
                        or click to browse files
                      </Typography>
                      <Box sx={{ display: 'flex', justifyContent: 'center', gap: 1, flexWrap: 'wrap' }}>
                        <Chip label="JPG/PNG" size="small" />
                        <Chip label={`Max ${(MAX_FILE_SIZE / (1024 * 1024)).toFixed(0)}MB`} size="small" />
                        <Chip label={`Max ${MAX_QUEUE_FILES} files`} size="small" />
                      </Box>
                    </Box>
                  </DropzoneArea>
                </Box>

                {queue.length > 0 && (
                  <Box>
                    <Box sx={{ mb: 2 }}>
                      <TextField
                        fullWidth
                        size="small"
                        placeholder="Album name (optional)"
                        value={commonTitle}
                        onChange={(e) => setCommonTitle(e.target.value)}
                        sx={{ mb: 2 }}
                      />

                      <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
                        <GoldButton
                          variant="contained"
                          onClick={uploadAll}
                          disabled={!queue.some((q) => q.status === 'pending' || q.status === 'error')}
                          startIcon={<CloudUpload />}
                          sx={{ flex: 1 }}
                        >
                          Upload All ({queue.filter(q => q.status === 'pending' || q.status === 'error').length})
                        </GoldButton>
                        <Button
                          variant="outlined"
                          onClick={() => {
                            queue.forEach((q) => {
                              try { URL.revokeObjectURL(q.previewUrl); } catch {
                                //ignore
                              }
                            });
                            setQueue([]);
                          }}
                          sx={{
                            borderColor: 'secondary.main',
                            color: 'secondary.main',
                          }}
                        >
                          Clear
                        </Button>
                      </Box>
                    </Box>

                    {/* Queue Preview */}
                    <Box sx={{ display: 'flex', gap: 2, overflowX: 'auto', py: 1 }}>
                      {queue.map((q) => (
                        <Card key={q.id} sx={{ width: 120, flex: '0 0 120px' }}>
                          <CardMedia
                            component="img"
                            height={80}
                            image={q.previewUrl}
                            alt={q.file.name}
                            sx={{ objectFit: 'cover' }}
                          />
                          <CardContent sx={{ p: 1 }}>
                            <Typography variant="caption" noWrap sx={{ fontSize: '0.7rem' }}>
                              {q.file.name}
                            </Typography>
                            <Box sx={{ display: 'flex', gap: 0.5, alignItems: 'center', mt: 0.5 }}>
                              {q.status === 'uploading' && <CircularProgress size={14} />}
                              {q.status === 'error' && (
                                <IconButton size="small" onClick={() => retryOne(q.id)}>
                                  <Replay fontSize="small" />
                                </IconButton>
                              )}
                              <IconButton size="small" onClick={() => removeOne(q.id)}>
                                <DeleteIcon fontSize="small" />
                              </IconButton>
                            </Box>
                            <LinearProgress
                              variant="determinate"
                              value={q.progress}
                              sx={{ mt: 0.5, height: 4, borderRadius: 2 }}
                            />
                          </CardContent>
                        </Card>
                      ))}
                    </Box>
                  </Box>
                )}
              </Paper>
            )}

            {/* Albums Grid */}
            <Box sx={{ mb: 8 }}>
              <Box sx={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                mb: 4,
              }}>
                <Typography variant="h4" sx={{
                  color: 'primary.main',
                  fontFamily: '"Playfair Display", serif',
                }}>
                  All Albums ({folders.length})
                </Typography>
                <Button
                  variant="contained"
                  onClick={() => setShowUploadPanel(true)}
                  startIcon={<AddPhotoAlternate />}
                  sx={{
                    background: 'linear-gradient(135deg, #0f766e 0%, #2dd4bf 100%)',
                    color: 'white',
                  }}
                >
                  Add Album
                </Button>
              </Box>

              {folders.length === 0 ? (
                <Paper
                  sx={{
                    p: 8,
                    textAlign: 'center',
                    background: 'linear-gradient(135deg, rgba(255, 250, 240, 0.6) 0%, rgba(255, 248, 225, 0.6) 100%)',
                    border: '2px dashed rgba(212, 175, 55, 0.3)',
                  }}
                >
                  <Celebration sx={{ fontSize: 64, color: 'secondary.main', mb: 3, opacity: 0.7 }} />
                  <Typography variant="h4" sx={{
                    color: 'text.primary',
                    mb: 2,
                    fontFamily: '"Playfair Display", serif',
                  }}>
                    No Albums Yet
                  </Typography>
                  <Typography variant="body1" sx={{
                    color: 'text.secondary',
                    maxWidth: 400,
                    mx: 'auto',
                    mb: 4,
                  }}>
                    Create your first album to start preserving wedding memories
                  </Typography>
                  <GoldButton
                    onClick={() => setShowUploadPanel(true)}
                    startIcon={<AddPhotoAlternate />}
                  >
                    Create Album
                  </GoldButton>
                </Paper>
              ) : (
                <Grid container spacing={3}>
                  {folders.map((folder) => (
                    <Grid key={folder.title}>
                      <AlbumCard>
                        <Box onClick={() => openFolder(folder.title)} sx={{ position: 'relative', cursor: 'pointer' }}>
                          <Box sx={{ height: 200, overflow: 'hidden' }}>
                            <CardMedia
                              component="img"
                              image={folder.thumb ?? ''}
                              alt={folder.title}
                              sx={{
                                width: '100%',
                                height: '100%',
                                objectFit: 'cover',
                                transition: 'transform 0.6s ease',
                                '&:hover': {
                                  transform: 'scale(1.1)',
                                },
                              }}
                            />
                          </Box>
                          <AlbumOverlay className="album-overlay">
                            <Box>
                              <Typography variant="h6" sx={{
                                color: 'white',
                                mb: 0.5,
                                fontFamily: '"Playfair Display", serif',
                              }}>
                                Open Album
                              </Typography>
                              <Typography variant="body2" sx={{
                                color: 'rgba(255, 255, 255, 0.9)',
                              }}>
                                {folder.count} precious memories
                              </Typography>
                            </Box>
                          </AlbumOverlay>

                          <Box sx={{
                            position: 'absolute',
                            top: 12,
                            left: 12,
                            bgcolor: 'rgba(15, 118, 110, 0.9)',
                            color: 'white',
                            px: 1.5,
                            py: 0.5,
                            borderRadius: 3,
                            fontSize: '0.75rem',
                            fontWeight: 600,
                          }}>
                            ALBUM
                          </Box>
                        </Box>
                        <CardContent sx={{ p: 2.5 }}>
                          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
                            <Box sx={{ minWidth: 0, flex: 1 }}>
                              <Typography variant="h6" noWrap sx={{
                                fontWeight: 600,
                                color: 'text.primary',
                                mb: 0.5,
                              }}>
                                {folder.title}
                              </Typography>
                              <Typography variant="body2" sx={{
                                color: 'text.secondary',
                                mb: 1.5,
                                height: 40,
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                display: '-webkit-box',
                                WebkitLineClamp: 2,
                                WebkitBoxOrient: 'vertical',
                              }}>
                                {folder.description}
                              </Typography>
                              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                  <Celebration sx={{ fontSize: 14, color: 'secondary.main' }} />
                                  <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                                    {folder.count} photos
                                  </Typography>
                                </Box>
                                <IconButton
                                  size="small"
                                  onClick={async (e) => {
                                    e.stopPropagation();
                                    if (confirm(`Delete album "${folder.title}"?`)) {
                                      await handleDeleteFolder(folder.title);
                                    }
                                  }}
                                  sx={{
                                    color: '#ef4444',
                                    '&:hover': {
                                      backgroundColor: 'rgba(239, 68, 68, 0.1)',
                                    },
                                  }}
                                >
                                  <DeleteIcon fontSize="small" />
                                </IconButton>
                              </Box>
                            </Box>
                          </Box>
                        </CardContent>
                      </AlbumCard>
                    </Grid>
                  ))}
                </Grid>
              )}
            </Box>
          </Box>
        )}

        {activeTab === 1 && (
          <Box>
            {/* Storyline Hero */}
            <Box sx={{ textAlign: 'center', mb: 6 }}>
              <Typography variant="h1" className="gold-gradient-text" gutterBottom>
                Our Story
              </Typography>
              <Typography variant="h5" sx={{
                color: 'primary.main',
                mb: 3,
                fontFamily: '"Playfair Display", serif',
              }}>
                The beautiful journey that led us here
              </Typography>
              <Typography variant="body1" sx={{
                color: 'text.secondary',
                maxWidth: 800,
                mx: 'auto',
                mb: 4,
                fontSize: '1.1rem',
                lineHeight: 1.8,
              }}>
                From the first hello to forever, every step of our journey has been magical.
                Here's our story in chapters.
              </Typography>
            </Box>

            {/* Story Steps */}
            <Grid container spacing={3} sx={{ mb: 8 }}>
              {storySteps.map((step) => (
                <Grid key={step.title}>
                  <StoryStepCard>
                    <Box sx={{
                      width: 60,
                      height: 60,
                      borderRadius: '50%',
                      background: 'linear-gradient(135deg, #d4af37 0%, #ffd700 100%)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      color: '#2c1810',
                      mb: 2,
                      mx: 'auto',
                    }}>
                      {step.icon}
                    </Box>
                    <Typography variant="h5" sx={{
                      textAlign: 'center',
                      color: 'primary.main',
                      mb: 1,
                      fontFamily: '"Playfair Display", serif',
                    }}>
                      {step.title}
                    </Typography>
                    <Typography variant="body2" sx={{
                      textAlign: 'center',
                      color: 'text.secondary',
                      mb: 2,
                    }}>
                      {step.description}
                    </Typography>
                    <Box sx={{ textAlign: 'center' }}>
                      <Button
                        variant="text"
                        endIcon={<ChevronRight />}
                        sx={{
                          color: 'secondary.main',
                          fontWeight: 500,
                        }}
                      >
                        View Memories
                      </Button>
                    </Box>
                  </StoryStepCard>
                </Grid>
              ))}
            </Grid>
          </Box>
        )}

        {activeTab === 2 && (
          <Box>
            {/* Moments Hero */}
            <Box sx={{ textAlign: 'center', mb: 6 }}>
              <Typography variant="h1" className="gold-gradient-text" gutterBottom>
                Special Moments
              </Typography>
              <Typography variant="h5" sx={{
                color: 'primary.main',
                mb: 3,
                fontFamily: '"Playfair Display", serif',
              }}>
                Candid shots and heartfelt moments
              </Typography>
              <Typography variant="body1" sx={{
                color: 'text.secondary',
                maxWidth: 800,
                mx: 'auto',
                mb: 4,
                fontSize: '1.1rem',
                lineHeight: 1.8,
              }}>
                The most beautiful moments are often the unplanned ones.
                These photos capture the true essence of our wedding day.
              </Typography>
            </Box>

            {/* Photo Grid */}
            <Box sx={{ mb: 8 }}>
              {photosAll.length === 0 ? (
                <Paper
                  sx={{
                    p: 8,
                    textAlign: 'center',
                    background: 'linear-gradient(135deg, rgba(255, 250, 240, 0.6) 0%, rgba(255, 248, 225, 0.6) 100%)',
                    border: '2px dashed rgba(212, 175, 55, 0.3)',
                  }}
                >
                  <Celebration sx={{ fontSize: 64, color: 'secondary.main', mb: 3, opacity: 0.7 }} />
                  <Typography variant="h4" sx={{
                    color: 'text.primary',
                    mb: 2,
                    fontFamily: '"Playfair Display", serif',
                  }}>
                    No Photos Yet
                  </Typography>
                  <Typography variant="body1" sx={{
                    color: 'text.secondary',
                    maxWidth: 400,
                    mx: 'auto',
                    mb: 4,
                  }}>
                    Upload photos to see your special moments here
                  </Typography>
                  <GoldButton
                    onClick={() => setShowUploadPanel(true)}
                    startIcon={<AddPhotoAlternate />}
                  >
                    Upload Photos
                  </GoldButton>
                </Paper>
              ) : (
                <Grid container spacing={2}>
                  {photosAll.slice(0, 12).map((photo) => (
                    <Grid key={photo.id}>
                      <PhotoCard>
                        <PhotoActions className="photo-actions">
                          <IconButton
                            size="small"
                            onClick={() => {
                              try {
                                const a = document.createElement('a');
                                a.href = photo.url;
                                a.download = photo.filename || 'wedding-photo.jpg';
                                document.body.appendChild(a);
                                a.click();
                                a.remove();
                              } catch (err) {
                                console.error('download error', err);
                              }
                            }}
                            sx={{
                              color: 'white',
                              bgcolor: 'rgba(15, 118, 110, 0.8)',
                              '&:hover': { bgcolor: '#0f766e' },
                            }}
                          >
                            <Download fontSize="small" />
                          </IconButton>
                        </PhotoActions>
                        <CardMedia
                          component="img"
                          height={160}
                          image={photo.url}
                          alt={photo.filename || 'Wedding photo'}
                          sx={{ objectFit: 'cover' }}
                        />
                      </PhotoCard>
                    </Grid>
                  ))}
                </Grid>
              )}
            </Box>
          </Box>
        )}
      </Container>

      {/* Album Modal */}
      <Dialog
        open={folderModalOpen}
        onClose={() => setFolderModalOpen(false)}
        fullWidth
        maxWidth="lg"
        PaperProps={{
          sx: {
            borderRadius: 3,
            maxHeight: '90vh',
          },
        }}
      >
        <DialogTitle sx={{
          background: 'linear-gradient(135deg, #0f766e 0%, #2dd4bf 100%)',
          color: 'white',
          py: 2.5,
        }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <FolderOpen />
              <Box>
                <Typography variant="h5">{folderOpenTitle}</Typography>
                <Typography variant="body2" sx={{ opacity: 0.9 }}>
                  {folderPhotos.length} photos
                </Typography>
              </Box>
            </Box>
            <Button
              variant="outlined"
              size="small"
              onClick={() => {
                if (folderOpenTitle) handleDeleteFolder(folderOpenTitle);
              }}
              disabled={!!deletingFolder}
              sx={{
                color: 'white',
                borderColor: 'rgba(255, 255, 255, 0.5)',
                '&:hover': {
                  borderColor: 'white',
                },
              }}
            >
              Delete Album
            </Button>
          </Box>
        </DialogTitle>
        <DialogContent dividers sx={{ p: 3 }}>
          {folderPhotos.length === 0 ? (
            <Box sx={{ textAlign: 'center', py: 6 }}>
              <Typography variant="h6" sx={{ color: 'text.secondary', mb: 2 }}>
                No photos in this album
              </Typography>
            </Box>
          ) : (
            <Grid container spacing={2}>
              {folderPhotos.map((p, idx) => (
                <Grid key={p.id}>
                  <PhotoCard>
                    <PhotoActions className="photo-actions">
                      <IconButton
                        size="small"
                        onClick={() => handleDeletePhoto(p.id)}
                        disabled={deletingId === p.id}
                        sx={{
                          color: 'white',
                          bgcolor: 'rgba(239, 68, 68, 0.9)',
                          '&:hover': { bgcolor: '#ef4444' },
                        }}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                      <IconButton
                        size="small"
                        onClick={() => {
                          try {
                            const a = document.createElement('a');
                            a.href = p.url;
                            a.download = p.filename || `${p.title || 'wedding-photo'}.jpg`;
                            document.body.appendChild(a);
                            a.click();
                            a.remove();
                            setSnackbar({ open: true, severity: 'success', message: 'Photo downloaded!' });
                          } catch (err) {
                            console.error('download error', err);
                            setSnackbar({ open: true, severity: 'error', message: 'Download failed' });
                          }
                        }}
                        sx={{
                          color: 'white',
                          bgcolor: 'rgba(15, 118, 110, 0.9)',
                          '&:hover': { bgcolor: '#0f766e' },
                        }}
                      >
                        <Download fontSize="small" />
                      </IconButton>
                    </PhotoActions>
                    <Box
                      sx={{ cursor: 'pointer' }}
                      onClick={() => {
                        setLightboxStartIndex(idx);
                        setLightboxOpen(true);
                      }}
                    >
                      <CardMedia
                        component="img"
                        height={140}
                        image={p.url}
                        alt={p.filename || p.title || 'Wedding photo'}
                        sx={{ objectFit: 'cover' }}
                      />
                    </Box>
                  </PhotoCard>
                </Grid>
              ))}
            </Grid>
          )}
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setFolderModalOpen(false)}>Close</Button>
        </DialogActions>
      </Dialog>

      {/* Floating Action Button */}
      <FloatingActionButton onClick={() => setShowUploadPanel(true)}>
        <AddPhotoAlternate />
      </FloatingActionButton>

      {/* Lightbox */}
      <LightboxModal
        open={lightboxOpen}
        photos={folderPhotos}
        startIndex={lightboxStartIndex}
        onClose={() => setLightboxOpen(false)}
      />

      {/* Snackbar */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar((s) => ({ ...s, open: false }))}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert
          severity={snackbar.severity}
          onClose={() => setSnackbar((s) => ({ ...s, open: false }))}
          sx={{
            borderRadius: 2,
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.12)',
            fontFamily: '"Inter", sans-serif',
            fontWeight: 500,
          }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>

      {/* Footer */}
      <Box sx={{
        py: 4,
        textAlign: 'center',
        color: 'text.secondary',
        borderTop: '1px solid rgba(0, 0, 0, 0.05)',
        background: 'rgba(255, 255, 255, 0.5)',
      }}>
        <Container maxWidth="sm">
          <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mb: 2 }}>
            <LocalFlorist sx={{ fontSize: 20, color: 'secondary.main', opacity: 0.7 }} />
            <Diamond sx={{ fontSize: 18, color: 'primary.main', opacity: 0.7 }} />
            <LocalFlorist sx={{ fontSize: 20, color: 'secondary.main', opacity: 0.7 }} />
          </Box>
          <Typography variant="body2" sx={{
            fontFamily: '"Cormorant Garamond", serif',
            fontSize: '1.1rem',
            color: 'primary.main',
            mb: 1,
          }}>
            Forever Cherished • Always Remembered
          </Typography>
          <Typography variant="caption" sx={{
            opacity: 0.6,
            letterSpacing: '0.5px',
          }}>
            © {new Date().getFullYear()} Our Wedding Gallery
          </Typography>
        </Container>
      </Box>
    </ThemeProvider>
  );
}