// AdminGallery.jsx - Gallery Admin Dashboard Component
const { useState, useEffect, useRef } = React;

// Helper to get Firebase configuration dynamically
const getFirebaseConfig = () => {
  const config = window.firebaseConfig || {};
  return {
    ...config,
    authDomain: "fz39-admin-portal.firebaseapp.com"
  };
};

// Lazy initialization of Firebase Auth and Firestore
const getAuth = () => {
  const config = getFirebaseConfig();
  if (!window.firebase.apps.length) {
    window.firebase.initializeApp(config);
  }
  return window.firebase.auth();
};

const getDb = () => {
  const config = getFirebaseConfig();
  if (!window.firebase.apps.length) {
    window.firebase.initializeApp(config);
  }
  return window.firebase.firestore();
};

const signInWithPopup = (auth, provider) => auth.signInWithPopup(provider);

function AdminGallery() {
  const auth = getAuth();
  const db = getDb();
  const [photos, setPhotos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [dragActive, setDragActive] = useState(false);

  // Authorization state
  const [secretKey, setSecretKey] = useState('');
  const [deletingId, setDeletingId] = useState(null);
  const [loginError, setLoginError] = useState('');
  const [verifying, setVerifying] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // Form State
  const [tournament, setTournament] = useState('');
  const [caption, setCaption] = useState('');
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [previews, setPreviews] = useState([]);
  const [isCreatingNewAlbum, setIsCreatingNewAlbum] = useState(false);
  const [fileCaptions, setFileCaptions] = useState({});

  // Stats Management State Variables
  const [activeTab, setActiveTab] = useState('gallery'); // 'gallery' | 'stats' | 'records'

  const handleDownload = async (imageUrl, caption, id, event) => {
    // Prevent clicking the button from triggering parent card click events
    if (event) event.stopPropagation();

    try {
      const response = await fetch(imageUrl);
      if (!response.ok) throw new Error('Network response was not ok');
      
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      
      // Clean filename format
      const fileName = `fakhar-zaman-${id || 'gallery'}.jpg`;
      link.download = fileName;
      
      document.body.appendChild(link);
      link.click();
      
      // Cleanup resources
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
    } catch (error) {
      console.error("Download failed, opening image directly:", error);
      // Fallback: open in new tab if fetch fails
      window.open(imageUrl, '_blank');
    }
  };
  const [statsFormat, setStatsFormat] = useState('ODI');
  const [statsColumns, setStatsColumns] = useState([]);
  const [statsRecords, setStatsRecords] = useState([]);
  const [selectedRecordId, setSelectedRecordId] = useState('');
  const [statsPayload, setStatsPayload] = useState({});
  const [statsLoading, setStatsLoading] = useState(false);
  const [statsSubmitting, setStatsSubmitting] = useState(false);

  // Custom Milestone Records State
  const [records, setRecords] = useState([]);
  const [recordsLoading, setRecordsLoading] = useState(false);
  const [recordsSubmitting, setRecordsSubmitting] = useState(false);
  const [recordFormat, setRecordFormat] = useState('ODI');
  const [recordTitle, setRecordTitle] = useState('');
  const [recordValue, setRecordValue] = useState('');
  const [recordDescription, setRecordDescription] = useState('');
  const [editingRecordId, setEditingRecordId] = useState(null);

  // Toast / Status Message State
  const [status, setStatus] = useState(null); // { type: 'success' | 'error', text: string }
  const [alertMessage, setAlertMessage] = useState('');

  const fileInputRef = useRef(null);

  // Fetch all custom record milestones
  const fetchRecords = async () => {
    try {
      setRecordsLoading(true);
      const res = await fetch('/api/records');
      if (!res.ok) {
        throw new Error('Failed to retrieve records from server.');
      }
      const data = await res.json();
      setRecords(data || []);
    } catch (err) {
      console.error('[Admin fetchRecords]', err);
      showStatus('error', 'Error fetching record milestones: ' + err.message);
    } finally {
      setRecordsLoading(false);
    }
  };

  const handleRecordSubmit = async (e) => {
    e.preventDefault();
    if (!recordTitle.trim() || !recordValue.trim()) {
      showStatus('error', 'Record Title and Value are required fields.');
      return;
    }
    try {
      setRecordsSubmitting(true);
      showStatus(null, null);

      const url = editingRecordId ? `/api/records/${editingRecordId}` : '/api/records/update';
      const method = editingRecordId ? 'PUT' : 'POST';

      const res = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'x-admin-secret': secretKey
        },
        body: JSON.stringify({
          format: recordFormat,
          record_title: recordTitle.trim(),
          record_value: recordValue.trim(),
          description: recordDescription.trim()
        })
      });

      let data = {};
      const contentType = res.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        data = await res.json();
      } else {
        const text = await res.text();
        if (text.includes('<title>Cookie check</title>')) { throw new Error('Action blocked by browser cookie settings or payload size limit. Please open the app in a new tab to continue.'); } throw new Error(text || `Server returned status ${res.status}`);
      }
      if (!res.ok) {
        throw new Error(data.message || data.error || 'Failed to update record milestone.');
      }

      showStatus('success', data.message || 'Milestone updated successfully!');
      // Clear input fields and exit edit mode
      setRecordTitle('');
      setRecordValue('');
      setRecordDescription('');
      setEditingRecordId(null);
      // Refresh list
      fetchRecords();
    } catch (err) {
      console.error('[Admin handleRecordSubmit]', err);
      showStatus('error', 'Error: ' + err.message);
    } finally {
      setRecordsSubmitting(false);
    }
  };

  const handleRecordDelete = async (id) => {
    if (!id) return;
    const targetId = id;
    if (!window.confirm('Are you sure you want to delete this milestone record? This action cannot be undone.')) {
      return;
    }

    const storedSecretKey = localStorage.getItem('ADMIN_SECRET_KEY') || localStorage.getItem('admin_secret_key') || secretKey || '';

    try {
      setStatus(null);
      setAlertMessage('');
      const res = await fetch(`/api/records/${targetId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'x-admin-secret': storedSecretKey
        }
      });

      if (res.ok) {
        setRecords(prev => prev.filter(r => (r.id !== targetId && r.ID !== targetId)));
        setAlertMessage("Milestone record successfully removed.");
        showStatus('success', 'Milestone record deleted successfully.');
        fetchRecords();
      } else {
        setAlertMessage("Failed to delete record from the server.");
        showStatus('error', 'Failed to delete record from server.');
      }
    } catch (err) {
      console.error('[Admin handleRecordDelete]', err);
      showStatus('error', 'Error deleting record milestone: ' + err.message);
    }
  };

  // Fetch all current images from /api/gallery
  const fetchPhotos = async (showLoading = true) => {
    try {
      if (showLoading) setLoading(true);
      const res = await fetch('/api/gallery');
      if (!res.ok) {
        throw new Error('Failed to retrieve photos from the server.');
      }
      const data = await res.json();
      setPhotos(data || []);
    } catch (err) {
      console.error('[Admin Gallery fetch]', err);
      showStatus('error', 'Error fetching photos: ' + err.message);
    } finally {
      if (showLoading) setLoading(false);
    }
  };

  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    let hasResolved = false;
    const timeoutId = setTimeout(() => {
      if (!hasResolved) {
        console.warn("Auth state verification timed out (2s limit). Showing login UI.");
        setIsLoading(false);
      }
    }, 2000);

    // Listen for auth state changes securely via Firebase Auth
    const unsubscribe = auth.onAuthStateChanged(async (user) => {
      hasResolved = true;
      clearTimeout(timeoutId);
      
      setIsLoading(true);
      if (user) {
        const userEmail = (user.email || '').toLowerCase().trim();
        try {
          // Check if user is whitelisted in Firestore "admins" collection
          const adminDocSnap = await db.collection("admins").doc(userEmail).get();
          
          if (adminDocSnap.exists) {
            const idToken = await user.getIdToken();
            const response = await fetch('/api/admin/google-login', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ idToken })
            });

            if (response.ok) {
              const resData = await response.json();
              setSecretKey(resData.adminSecret);
              setCurrentUser(user);
              setLoginError('');
              
              // Bust Vercel dynamic cache / static caching freezes on reload
              if (!sessionStorage.getItem('admin_cache_busted')) {
                sessionStorage.setItem('admin_cache_busted', 'true');
                window.location.reload();
              }
            } else {
              const errData = await response.json();
              setLoginError(errData.error || "Failed to establish secure admin session.");
              await auth.signOut();
              setCurrentUser(null);
              setSecretKey('');
            }
          } else {
            console.warn(`[SECURITY LOCKDOWN] Non-admin access rejected for: ${userEmail}`);
            setLoginError("Access Denied: Your email is not whitelisted in the administrator database.");
            await auth.signOut();
            setCurrentUser(null);
            setSecretKey('');
          }
        } catch (err) {
          console.error('[Admin Secure Authentication Error]', err);
          setLoginError("Access Denied: Your email is not whitelisted in the administrator database.");
          await auth.signOut();
          setCurrentUser(null);
          setSecretKey('');
        }
      } else {
        setCurrentUser(null);
        setSecretKey('');
      }
      setIsLoading(false);
    });

    fetchPhotos();
    fetchRecords();

    return () => {
      clearTimeout(timeoutId);
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    const hasProcessing = photos.some(p => p.caption === "AI Caption processing...");
    let intervalId;
    if (hasProcessing) {
      intervalId = setInterval(() => {
        fetchPhotos(false);
      }, 4000);
    }
    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [photos]);

  // Fetch stats schemas & records
  const fetchStatsColumnsAndRecords = async (format) => {
    try {
      setStatsLoading(true);
      const headers = { 'x-admin-secret': secretKey };
      
      // 1. Fetch Columns
      const colsRes = await fetch(`/api/stats/columns/${format}`, { headers });
      if (!colsRes.ok) throw new Error('Failed to fetch columns');
      const colsData = await colsRes.json();
      setStatsColumns(colsData);

      // 2. Fetch current records
      const recsRes = await fetch(`/api/stats/${format}`);
      if (!recsRes.ok) throw new Error('Failed to fetch records');
      const recsData = await recsRes.json();
      setStatsRecords(recsData || []);

      // Reset payload & selection
      setSelectedRecordId('');
      const initialPayload = {};
      colsData.forEach(c => {
        initialPayload[c.name] = '';
      });
      setStatsPayload(initialPayload);

    } catch (err) {
      console.error('[Admin Stats fetch]', err);
      showStatus('error', 'Error loading stats schema: ' + err.message);
    } finally {
      setStatsLoading(false);
    }
  };

  useEffect(() => {
    if (activeTab === 'stats' && secretKey) {
      fetchStatsColumnsAndRecords(statsFormat);
    }
  }, [activeTab, statsFormat, secretKey]);

  const handleRecordSelect = (id) => {
    setSelectedRecordId(id);
    if (!id) {
      // Clear form
      const initialPayload = {};
      statsColumns.forEach(c => {
        initialPayload[c.name] = '';
      });
      setStatsPayload(initialPayload);
      return;
    }

    const record = statsRecords.find(r => (r.id === parseInt(id, 10)) || (r.ID === parseInt(id, 10)));
    if (record) {
      const newPayload = {};
      statsColumns.forEach(c => {
        let val = record[c.name] !== undefined ? record[c.name] : record[c.name.toLowerCase()];
        
        // Format Date to YYYY-MM-DD for date inputs
        if (c.type.toLowerCase().includes('date') && val) {
          try {
            const d = new Date(val);
            if (!isNaN(d.getTime())) {
              val = d.toISOString().split('T')[0];
            }
          } catch(e) {}
        }
        newPayload[c.name] = val !== null && val !== undefined ? val : '';
      });
      // Ensure we preserve the ID
      const idKey = statsColumns.find(c => c.name.toLowerCase() === 'id')?.name || 'ID';
      newPayload[idKey] = id;
      setStatsPayload(newPayload);
    }
  };

  const handleStatsSubmit = async (e) => {
    e.preventDefault();
    try {
      setStatsSubmitting(true);
      showStatus(null, null);

      const response = await fetch('/api/stats/update', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-admin-secret': secretKey
        },
        body: JSON.stringify({
          format: statsFormat,
          payload: statsPayload
        })
      });

      if (response.status === 403) {
        localStorage.removeItem('admin_secret_key');
        setSecretKey('');
        throw new Error('Unauthorized or expired session. Please verify your admin secret key.');
      }

      let result = {};
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        result = await response.json();
      } else {
        const text = await response.text();
        if (text.includes('<title>Cookie check</title>')) { throw new Error('Action blocked by browser cookie settings or payload size limit. Please open the app in a new tab to continue.'); } throw new Error(text || `Server returned status ${response.status}`);
      }

      if (!response.ok) {
        throw new Error(result.message || result.error || 'Server update failed.');
      }

      showStatus('success', result.message || 'Changes saved perfectly!');
      
      // Reload columns and records
      fetchStatsColumnsAndRecords(statsFormat);

    } catch (err) {
      console.error('[Admin Stats Submit]', err);
      showStatus('error', err.message);
    } finally {
      setStatsSubmitting(false);
    }
  };

  const handleStatsDelete = async (id) => {
    if (!confirm('Are you absolutely sure you want to delete this statistics record? This cannot be undone.')) {
      return;
    }
    try {
      setStatsLoading(true);
      showStatus(null, null);
      const response = await fetch(`/api/stats/${statsFormat}/${id}`, {
        method: 'DELETE',
        headers: {
          'x-admin-secret': secretKey
        }
      });

      if (response.status === 403) {
        localStorage.removeItem('admin_secret_key');
        setSecretKey('');
        throw new Error('Unauthorized or expired session. Please verify your admin secret key.');
      }

      let result = {};
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        result = await response.json();
      } else {
        const text = await response.text();
        if (text.includes('<title>Cookie check</title>')) { throw new Error('Action blocked by browser cookie settings or payload size limit. Please open the app in a new tab to continue.'); } throw new Error(text || `Server returned status ${response.status}`);
      }

      if (!response.ok) {
        throw new Error(result.message || result.error || 'Failed to delete record.');
      }

      showStatus('success', 'Record successfully deleted.');
      fetchStatsColumnsAndRecords(statsFormat);

    } catch (err) {
      console.error('[Admin Stats Delete]', err);
      showStatus('error', 'Delete failed: ' + err.message);
    } finally {
      setStatsLoading(false);
    }
  };

  const showStatus = (type, text) => {
    if (!type && !text) {
      setStatus(null);
      setAlertMessage('');
      return;
    }
    setStatus({ type, text });
    setAlertMessage(text || '');
    // Auto-clear success messages after 5 seconds
    if (type === 'success') {
      setTimeout(() => {
        setStatus(prev => prev && prev.text === text ? null : prev);
        setAlertMessage('');
      }, 5000);
    }
  };

  // Handle files selection
  const handleFiles = (files) => {
    const validFiles = Array.from(files).filter(file => file.type.startsWith('image/'));
    if (validFiles.length === 0) {
      showStatus('error', 'Please select image files only.');
      return;
    }

    setSelectedFiles(prev => [...prev, ...validFiles]);

    // Create dynamic previews
    const newPreviews = validFiles.map(file => ({
      name: file.name,
      url: URL.createObjectURL(file)
    }));
    setPreviews(prev => [...prev, ...newPreviews]);
  };

  const handleFileChange = (e) => {
    if (e.target.files) {
      handleFiles(e.target.files);
    }
  };

  // Drag & drop handlers
  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFiles(e.dataTransfer.files);
    }
  };

  const removeSelectedFile = (index) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index));
    // Revoke object URL to avoid memory leak
    URL.revokeObjectURL(previews[index].url);
    setPreviews(prev => prev.filter((_, i) => i !== index));
    setFileCaptions(prev => {
      const next = {};
      let nextIdx = 0;
      for (let i = 0; i < selectedFiles.length; i++) {
        if (i !== index) {
          next[nextIdx] = prev[i] || '';
          nextIdx++;
        }
      }
      return next;
    });
  };

  // Submit multiple files to /api/gallery/upload
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!tournament.trim()) {
      showStatus('error', 'Please provide a Tournament or Series name.');
      return;
    }
    if (selectedFiles.length === 0) {
      showStatus('error', 'Please select or drag at least one photograph to upload.');
      return;
    }

    try {
      setSubmitting(true);
      showStatus(null, null);

      const formData = new FormData();
      formData.append('tournament', tournament.trim());
      
      // Build metadata for each file to support individual captions & AI fallbacks
      const metadata = selectedFiles.map((file, idx) => ({
        fileName: file.name,
        caption: (fileCaptions[idx] || '').trim(),
        autoCaption: !(fileCaptions[idx] || '').trim()
      }));
      formData.append('metadata', JSON.stringify(metadata));
      
      selectedFiles.forEach(file => {
        formData.append('photos', file);
      });

      const response = await fetch('/api/gallery/upload', {
        method: 'POST',
        headers: {
          'x-admin-secret': secretKey
        },
        body: formData
      });

      if (response.status === 403) {
        localStorage.removeItem('admin_secret_key');
        setSecretKey('');
        throw new Error('Unauthorized or expired session. Please verify your admin secret key.');
      }

      let result = {};
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        result = await response.json();
      } else {
        const text = await response.text();
        if (text.includes('<title>Cookie check</title>')) { throw new Error('Action blocked by browser cookie settings or payload size limit. Please open the app in a new tab to continue.'); } throw new Error(text || `Server returned status ${response.status}`);
      }

      if (!response.ok) {
        throw new Error(result.message || result.error || 'Server upload failed.');
      }

      showStatus('success', `Successfully uploaded and saved ${selectedFiles.length} photos perfectly!`);
      
      // Reset form states
      setTournament('');
      setCaption('');
      setSelectedFiles([]);
      previews.forEach(p => URL.revokeObjectURL(p.url));
      setPreviews([]);
      setFileCaptions({});
      setIsCreatingNewAlbum(false);
      
      // Refresh inventory
      fetchPhotos();

    } catch (err) {
      console.error('[Admin Gallery Upload]', err);
      showStatus('error', err.message);
    } finally {
      setSubmitting(false);
    }
  };

  // Trigger DELETE route to remove physical blob and row
  const handleItemPurge = async (id) => {
    const storedSecretKey = secretKey || localStorage.getItem('admin_secret_key') || '';

    try {
      showStatus(null, null);
      const res = await fetch(`/api/gallery/${id}`, { 
          method: 'DELETE',
          headers: {
              'x-admin-secret': storedSecretKey
          }
      });

      if (res.status === 403) {
        localStorage.removeItem('admin_secret_key');
        setSecretKey('');
        setDeletingId(null);
        throw new Error('Unauthorized or expired session. Please verify your admin secret key.');
      }

      let result = {};
      const contentType = res.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        result = await res.json();
      } else {
        const text = await res.text();
        if (text.includes('<title>Cookie check</title>')) { throw new Error('Action blocked by browser cookie settings or payload size limit. Please open the app in a new tab to continue.'); } throw new Error(text || `Server returned status ${res.status}`);
      }

      if (!res.ok) {
        throw new Error(result.message || result.error || 'Failed to delete file.');
      }

      showStatus('success', 'Photo successfully removed.');
      
      // Optimistic update of inventory state
      setPhotos(prev => prev.filter(p => p.id !== id));
      setDeletingId(null);

    } catch (err) {
      console.error('[Admin Gallery Delete]', err);
      showStatus('error', 'Purge failed: ' + err.message);
      setDeletingId(null);
    }
  };

  const handleDelete = handleItemPurge;

  const handleGoogleLogin = async () => {
    try {
      setVerifying(true);
      setLoginError('');

      // Clear obsolete session/local storage variables if configuration or credential context changes
      localStorage.removeItem('admin_secret_key');
      localStorage.clear();
      sessionStorage.clear();

      const provider = new window.firebase.auth.GoogleAuthProvider();
      provider.setCustomParameters({ prompt: 'select_account' });
      
      // Set isLoading to true while popup is opening
      setIsLoading(true);

      const result = await signInWithPopup(auth, provider);
    } catch (err) {
      console.error('[Google Sign-In Error]', err);
      setLoginError(err.message || "Google Sign-In failed.");
      setCurrentUser(null);
      setSecretKey('');
      setIsLoading(false);
      setVerifying(false);
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-[80vh] flex flex-col items-center justify-center text-slate-400">
        <div className="w-10 h-10 border-4 border-lime-400 border-t-transparent rounded-full animate-spin mb-4"></div>
        <p className="text-sm font-semibold tracking-wide text-slate-400">Verifying session credentials...</p>
      </div>
    );
  }

  if (!secretKey) {
    return (
      <div className="max-w-md mx-auto my-16 p-6 sm:p-8 bg-zinc-900 border border-zinc-800 rounded-3xl shadow-xl space-y-6 fade-in text-white">
        <div className="text-center space-y-2">
          <div className="inline-flex p-3.5 bg-lime-950/40 rounded-full border border-lime-500/20 text-lime-400 mb-2">
            <svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          </div>
          <h2 className="display-font text-2xl font-black text-white tracking-tight">Admin Portal Login</h2>
          <p className="text-neutral-400 text-xs sm:text-sm">Secure area reserved strictly for authorized system administrators.</p>
        </div>

        {loginError && (
          <div className="p-3 bg-rose-950/40 border border-rose-500/20 text-rose-300 rounded-xl text-xs font-semibold text-center leading-relaxed">
            {loginError}
          </div>
        )}

        <div className="space-y-4">
          <button
            onClick={handleGoogleLogin}
            disabled={verifying}
            className={`w-full py-3.5 px-6 rounded-xl font-bold text-sm tracking-wide bg-white hover:bg-neutral-100 text-black cursor-pointer transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-3 border border-neutral-200 ${verifying ? 'opacity-70 cursor-not-allowed' : ''}`}
          >
            {verifying ? (
              <>
                <div className="w-4 h-4 border-2 border-black border-t-transparent rounded-full animate-spin"></div>
                <span>Verifying credentials...</span>
              </>
            ) : (
              <>
                <svg className="w-5 h-5 shrink-0" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4" />
                  <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
                  <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z" fill="#FBBC05" />
                  <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z" fill="#EA4335" />
                </svg>
                <span>Sign In with Google</span>
              </>
            )}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto p-4 sm:p-6 lg:p-8 space-y-12 fade-in text-white">
      
      {/* Overview Card */}
      <div className="bg-zinc-900 text-white rounded-3xl p-6 sm:p-8 shadow-xl border border-zinc-800 relative overflow-hidden">
        <div className="absolute top-0 right-0 p-8 opacity-5">
          <svg className="w-40 h-40" fill="currentColor" viewBox="0 0 24 24">
            <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96z" />
          </svg>
        </div>
        <div className="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div className="space-y-3 flex-1">
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-lime-950/40 text-lime-400 border border-lime-500/20 text-xs font-semibold uppercase tracking-wider">
              <span className="w-2 h-2 bg-lime-400 rounded-full animate-pulse"></span>
              Sports Media Integration Engine
            </span>
            <h1 className="display-font text-3xl sm:text-4xl font-extrabold tracking-tight">Gallery Control Center</h1>
            <p className="text-neutral-400 max-w-2xl text-sm sm:text-base leading-relaxed">
              Fully automated media upload and management dashboard. Keep your matches and championship series photos perfectly in sync.
            </p>
          </div>
          <div className="shrink-0 flex items-center gap-4">
            {currentUser && (
              <div className="hidden sm:flex items-center gap-2.5 bg-zinc-950 px-3.5 py-1.5 rounded-full border border-zinc-800">
                {currentUser.photoURL ? (
                  <img src={currentUser.photoURL} className="w-5.5 h-5.5 rounded-full object-cover" referrerPolicy="no-referrer" />
                ) : (
                  <div className="w-5.5 h-5.5 rounded-full bg-lime-500/20 text-lime-400 flex items-center justify-center font-bold text-xs uppercase">
                    {currentUser.email.charAt(0)}
                  </div>
                )}
                <span className="text-xs font-semibold text-neutral-300">{currentUser.email}</span>
              </div>
            )}
            <button 
              onClick={() => {
                auth.signOut().then(() => {
                  setSecretKey('');
                }).catch(err => {
                  console.error('Logout error:', err);
                  setSecretKey('');
                });
              }}
              className="inline-flex items-center gap-2 px-4 py-2.5 bg-zinc-950 hover:bg-rose-700/80 border border-zinc-800 hover:border-rose-600/60 text-neutral-300 hover:text-white rounded-xl text-xs font-bold transition-all cursor-pointer shadow-sm"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
              Lock Admin Panel
            </button>
          </div>
        </div>
      </div>

      {/* Status Messages */}
      {(status || alertMessage) && (
        <div className={`p-4 rounded-xl border flex items-start gap-3 transition-all duration-300 ${
          (status?.type || 'success') === 'error' 
            ? 'bg-rose-950/40 border-rose-500/20 text-rose-200' 
            : 'bg-lime-950/40 border-lime-500/20 text-lime-300'
        }`}>
          <div className="mt-0.5">
            {(status?.type || 'success') === 'error' ? (
              <svg className="w-5 h-5 text-rose-500" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            ) : (
              <svg className="w-5 h-5 text-lime-400" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            )}
          </div>
          <div className="flex-1 text-sm font-medium">
            {alertMessage || "Action completed successfully!"}
          </div>
          <button 
            onClick={() => { setStatus(null); setAlertMessage(''); }} 
            className="text-neutral-500 hover:text-white font-bold text-xs"
          >
            ✕
          </button>
        </div>
      )}

      {/* Navigation Tabs */}
      <div className="flex border-b border-zinc-800">
        <button
          onClick={() => { setActiveTab('gallery'); setStatus(null); setAlertMessage(''); }}
          className={`px-6 py-3 font-bold text-sm tracking-wide flex items-center gap-2 border-b-2 transition-all cursor-pointer ${
            activeTab === 'gallery'
              ? 'border-lime-400 text-lime-400'
              : 'border-transparent text-neutral-400 hover:text-white'
          }`}
        >
          <svg className="w-4.5 h-4.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>
          Gallery Manager
        </button>
        <button
          onClick={() => { setActiveTab('stats'); setStatus(null); setAlertMessage(''); }}
          className={`px-6 py-3 font-bold text-sm tracking-wide flex items-center gap-2 border-b-2 transition-all cursor-pointer ${
            activeTab === 'stats'
              ? 'border-lime-400 text-lime-400'
              : 'border-transparent text-neutral-400 hover:text-white'
          }`}
        >
          <svg className="w-4.5 h-4.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
          </svg>
          Stats Manager
        </button>
        <button
          onClick={() => { setActiveTab('records'); setStatus(null); setAlertMessage(''); }}
          className={`px-6 py-3 font-bold text-sm tracking-wide flex items-center gap-2 border-b-2 transition-all cursor-pointer ${
            activeTab === 'records'
              ? 'border-lime-400 text-lime-400'
              : 'border-transparent text-neutral-400 hover:text-white'
          }`}
        >
          <svg className="w-4.5 h-4.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5a2 2 0 10-2 2h2zm0 0h4m-4 0H8" />
          </svg>
          Milestones Manager
        </button>
      </div>

      {/* Gallery Manager Panel */}
      {activeTab === 'gallery' && (
        <>
          {/* Upload and Form Section */}
          <div className="bg-zinc-900 rounded-3xl border border-zinc-800 shadow-sm overflow-hidden grid grid-cols-1 lg:grid-cols-12 text-white">
            {/* Left Side Form inputs */}
            <div className="p-6 sm:p-8 lg:p-10 lg:col-span-5 border-b lg:border-b-0 lg:border-r border-zinc-800 flex flex-col justify-between">
              <div>
                <h2 className="display-font text-xl font-bold text-white mb-6 flex items-center gap-2">
                  <svg className="w-5 h-5 text-lime-400" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                  </svg>
                  Photo Media Ingestion
                </h2>
                
                <form onSubmit={handleSubmit} className="space-y-6">
                  {/* Album / Tournament Selection Logic */}
                  <div className="space-y-1.5">
                    <div className="flex items-center justify-between">
                      <label className="block text-xs font-bold uppercase tracking-wider text-neutral-400">
                        Album / Tournament
                      </label>
                      <button
                        type="button"
                        onClick={() => {
                          setIsCreatingNewAlbum(!isCreatingNewAlbum);
                          setTournament('');
                        }}
                        className="text-xs font-bold text-lime-400 hover:text-lime-300 hover:underline flex items-center gap-1 cursor-pointer"
                      >
                        {isCreatingNewAlbum ? (
                          <>
                            <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 12h16M4 18h16" />
                            </svg>
                            Select Existing Album
                          </>
                        ) : (
                          <>
                            <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
                            </svg>
                            + Create New Album
                          </>
                        )}
                      </button>
                    </div>

                    {isCreatingNewAlbum ? (
                      <input 
                        type="text"
                        placeholder="Enter brand new album name... (e.g. ICC Champions Trophy 2017)"
                        value={tournament}
                        onChange={(e) => setTournament(e.target.value)}
                        className="w-full px-4 py-3 rounded-xl border border-zinc-800 bg-zinc-950 focus:outline-none focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 text-sm text-white font-semibold transition-all shadow-inner placeholder:text-neutral-500"
                        required
                      />
                    ) : (
                      <select
                        value={tournament}
                        onChange={(e) => setTournament(e.target.value)}
                        className="w-full px-4 py-3 rounded-xl border border-zinc-800 bg-zinc-950 focus:outline-none focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 text-sm text-white font-semibold transition-all shadow-inner cursor-pointer"
                        required
                      >
                        <option value="" className="bg-zinc-950 text-white">-- Select an Album --</option>
                        {Array.from(new Set(photos.map(p => p.tournament).filter(Boolean))).map((albumName, index) => (
                          <option key={index} value={albumName} className="bg-zinc-950 text-white">
                            {albumName}
                          </option>
                        ))}
                      </select>
                    )}
                  </div>

                  {/* Upload Trigger Button */}
                  <button
                    type="submit"
                    disabled={submitting || selectedFiles.length === 0}
                    className={`w-full py-3.5 px-6 rounded-xl font-bold text-sm tracking-wide transition-all shadow-md flex items-center justify-center gap-2 ${
                      submitting || selectedFiles.length === 0
                        ? 'bg-zinc-950 border border-zinc-850 text-neutral-500 cursor-not-allowed shadow-none'
                        : 'bg-lime-500 hover:bg-lime-400 text-black cursor-pointer hover:shadow-lg'
                    }`}
                  >
                    {submitting ? (
                      <>
                        <div className="w-5 h-5 border-2 border-black border-t-transparent rounded-full animate-spin"></div>
                        <span>Uploading media...</span>
                      </>
                    ) : (
                      <>
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span>Save {selectedFiles.length} {selectedFiles.length === 1 ? 'Photograph' : 'Photographs'} to Gallery</span>
                      </>
                    )}
                  </button>
                </form>
              </div>
            </div>

            {/* Right Side File dropzone and selected files list */}
            <div className="p-6 sm:p-8 lg:p-10 lg:col-span-7 bg-zinc-950 flex flex-col justify-between">
              <div className="space-y-6 flex-grow flex flex-col">
                <h3 className="display-font text-sm font-bold uppercase tracking-wider text-neutral-400">Selected Photographic Material</h3>

                {/* Drag & Drop Area */}
                <div 
                  onDragEnter={handleDrag}
                  onDragOver={handleDrag}
                  onDragLeave={handleDrag}
                  onDrop={handleDrop}
                  onClick={() => fileInputRef.current.click()}
                  className={`border-2 border-dashed rounded-2xl p-8 text-center flex flex-col items-center justify-center cursor-pointer transition-all gap-3 ${
                    dragActive 
                      ? 'border-lime-400 bg-lime-950/20' 
                      : 'border-zinc-800 bg-zinc-900 hover:bg-zinc-850'
                  }`}
                >
                  <input 
                    type="file"
                    ref={fileInputRef}
                    onChange={handleFileChange}
                    className="hidden"
                    multiple
                    accept="image/*"
                  />
                  <div className="p-3 bg-lime-950/40 rounded-full border border-lime-500/20 text-lime-400">
                    <svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                  </div>
                  <div>
                    <p className="text-sm text-white font-bold">Drag and drop images here, or <span className="text-lime-400 hover:underline">browse files</span></p>
                    <p className="text-xs text-neutral-400 mt-1">Accepts multiple PNG, JPG, or JPEG images</p>
                  </div>
                </div>

                {/* List of pending uploads with individual caption fields */}
                {previews.length > 0 ? (
                  <div className="space-y-4 overflow-y-auto max-h-[320px] p-1 pr-2">
                    {previews.map((preview, idx) => (
                      <div key={idx} className="flex items-center gap-4 bg-zinc-900 p-3 rounded-xl border border-zinc-800 shadow-xs relative group">
                        {/* Thumbnail */}
                        <div className="w-16 h-16 rounded-lg overflow-hidden bg-slate-900 shrink-0 relative">
                          <img 
                            src={preview.url} 
                            alt="Preview" 
                            className="w-full h-full object-cover"
                          />
                        </div>
                        
                        {/* Information & Input */}
                        <div className="flex-grow space-y-1 text-white">
                          <p className="text-xs font-bold text-white truncate max-w-[200px]" title={preview.name}>
                            {preview.name}
                          </p>
                          <input 
                            type="text"
                            placeholder="Write a custom caption... (or leave blank for automatic AI fallback)"
                            value={fileCaptions[idx] || ''}
                            onChange={(e) => {
                              setFileCaptions(prev => ({
                                ...prev,
                                [idx]: e.target.value
                              }));
                            }}
                            className="w-full px-3 py-1.5 rounded-lg border border-zinc-800 bg-zinc-950 focus:outline-none focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 text-xs text-white transition-all placeholder:text-neutral-500"
                          />
                        </div>

                        {/* Remove Action */}
                        <button
                          type="button"
                          onClick={() => removeSelectedFile(idx)}
                          className="bg-rose-950/40 hover:bg-rose-600 text-rose-400 hover:text-white rounded-lg p-2 transition-colors cursor-pointer border border-rose-500/20"
                          title="Remove file"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-16v1a3 3 0 003 3h10a3 3 0 003-3v-1M4 7h16" />
                          </svg>
                        </button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="flex-1 flex items-center justify-center py-10 border border-zinc-800 rounded-2xl bg-zinc-900/30">
                    <span className="text-xs text-neutral-500 font-semibold tracking-wide uppercase">No files staged yet</span>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Inventory & Purge Control Panel Section */}
          <div className="space-y-6">
            <div className="flex items-center justify-between border-b border-zinc-800 pb-4">
              <div>
                <h2 className="display-font text-2xl font-black text-white">Current Gallery Inventory</h2>
                <p className="text-neutral-400 text-xs sm:text-sm mt-1">Review active tournament media and manage gallery assets.</p>
              </div>
              <span className="text-xs text-lime-400 uppercase tracking-widest font-mono bg-lime-950/40 border border-lime-500/20 px-3.5 py-1.5 rounded-full">
                {photos.length} Total Records
              </span>
            </div>

            {loading ? (
              <div className="py-20 text-center text-neutral-400">
                <div className="inline-block w-8 h-8 border-4 border-lime-400 border-t-transparent rounded-full animate-spin mb-3"></div>
                <p className="text-xs font-semibold tracking-wide">Loading gallery records...</p>
              </div>
            ) : photos.length === 0 ? (
              <div className="py-16 text-center text-neutral-400 border border-zinc-800 rounded-2xl bg-zinc-900 p-6 max-w-lg mx-auto">
                <svg className="w-12 h-12 text-neutral-500 mx-auto mb-3" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
                <p className="font-bold text-white">No media in the gallery yet.</p>
                <p className="text-xs text-neutral-500 mt-1">Staged photographs uploaded via the form will appear here dynamically.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                {photos.map((photo) => (
                  <div key={photo.id} className="group bg-zinc-900 rounded-2xl overflow-hidden border border-zinc-800 shadow-sm hover:shadow-lg transition-all duration-300 flex flex-col justify-between text-white">
                    <div>
                      <div className="aspect-square bg-slate-900 relative overflow-hidden">
                        <img 
                          src={photo.image_url} 
                          alt={photo.tournament} 
                          className="w-full h-full object-cover group-hover:scale-102 transition-transform duration-500"
                        />
                      </div>
                      
                      <div className="p-4 space-y-1.5">
                        <span className="inline-block bg-zinc-800 text-neutral-400 px-2.5 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase max-w-full truncate border border-zinc-700">
                          {photo.tournament}
                        </span>
                        <p className="text-xs text-neutral-400 line-clamp-2 leading-relaxed">
                          {photo.caption || 'No detailed caption provided for this record.'}
                        </p>
                      </div>
                    </div>

                    <div className="px-4 py-3 bg-zinc-950 border-t border-zinc-850 flex items-center justify-between gap-2">
                      <button
                        onClick={(e) => handleDownload(photo.image_url, photo.caption, photo.id, e)}
                        className="inline-flex items-center gap-1.5 px-2.5 py-1.5 bg-zinc-800/80 hover:bg-lime-500 text-zinc-300 hover:text-black rounded-lg text-[11px] font-bold transition-all cursor-pointer border border-zinc-700/80 shrink-0"
                        title="Download Image"
                      >
                        <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                        </svg>
                        <span>Download</span>
                      </button>

                      {deletingId === photo.id ? (
                        <div className="flex gap-1">
                          <button 
                            onClick={() => handleDelete(photo.id)}
                            className="inline-flex items-center px-2 py-1 bg-rose-600 hover:bg-rose-700 text-white rounded-md text-[10px] font-bold transition-all cursor-pointer shadow-sm"
                          >
                            Confirm
                          </button>
                          <button 
                            onClick={() => setDeletingId(null)}
                            className="inline-flex items-center px-1.5 py-1 bg-zinc-800 hover:bg-zinc-750 text-white rounded-md text-[10px] font-bold transition-all cursor-pointer"
                          >
                            ✕
                          </button>
                        </div>
                      ) : (
                        <button 
                          onClick={() => setDeletingId(photo.id)}
                          className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-rose-950/40 hover:bg-rose-600 border border-rose-500/20 text-rose-400 hover:text-white rounded-lg text-[11px] font-bold transition-all shadow-xs cursor-pointer"
                        >
                          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-16v1a3 3 0 003 3h10a3 3 0 003-3v-1M4 7h16" />
                          </svg>
                          <span>Purge File</span>
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </>
      )}

      {/* Stats Manager Content */}
      {activeTab === 'stats' && (
        <div className="space-y-8">
          <div className="bg-zinc-900 rounded-3xl border border-zinc-800 shadow-sm overflow-hidden grid grid-cols-1 lg:grid-cols-12 text-white">
            
            {/* Left Column: Form Panel */}
            <div className="p-6 sm:p-8 lg:p-10 lg:col-span-5 border-b lg:border-b-0 lg:border-r border-zinc-800 flex flex-col justify-between">
              <div>
                <h2 className="display-font text-xl font-bold text-white mb-6 flex items-center gap-2">
                  <svg className="w-5 h-5 text-lime-400" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                  Stats Entry Form
                </h2>

                <form onSubmit={handleStatsSubmit} className="space-y-6">
                  {/* Format Selector */}
                  <div className="space-y-1.5">
                    <label className="block text-xs font-bold uppercase tracking-wider text-neutral-400">Cricket Format</label>
                    <select
                      value={statsFormat}
                      onChange={(e) => setStatsFormat(e.target.value)}
                      className="w-full bg-zinc-950 text-white text-sm font-semibold border border-zinc-800 hover:border-zinc-750 rounded-xl px-3.5 py-3 outline-none focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 transition-all cursor-pointer"
                    >
                      <option value="ODI" className="bg-zinc-950 text-white">ODI (One Day International)</option>
                      <option value="T20I" className="bg-zinc-950 text-white">T20I (Twenty20 International)</option>
                      <option value="Test" className="bg-zinc-950 text-white">Test Matches</option>
                      <option value="PslMatches" className="bg-zinc-950 text-white">PSL (Pakistan Super League)</option>
                    </select>
                  </div>

                  {/* Record Update / Create Action Dropdown */}
                  <div className="space-y-1.5">
                    <label className="block text-xs font-bold uppercase tracking-wider text-neutral-400">Operation Action</label>
                    <select
                      value={selectedRecordId}
                      onChange={(e) => handleRecordSelect(e.target.value)}
                      className="w-full bg-zinc-950 text-white text-sm font-semibold border border-zinc-800 hover:border-zinc-750 rounded-xl px-3.5 py-3 outline-none focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 transition-all cursor-pointer"
                    >
                      <option value="" className="bg-zinc-950 text-white">+ Create New Match Record</option>
                      {statsRecords.map(r => {
                        const id = r.id || r.ID;
                        const dateStr = r.date ? new Date(r.date).toLocaleDateString() : 'N/A';
                        return (
                          <option key={id} value={id} className="bg-zinc-950 text-white">
                            Edit: {dateStr} vs {r.opposition || r.Opponent || 'Unknown'} ({r.runs} runs)
                          </option>
                        );
                      })}
                    </select>
                  </div>

                  {/* Dynamic Form Fields */}
                  {statsLoading ? (
                    <div className="py-8 text-center text-neutral-400">
                      <div className="inline-block w-6 h-6 border-2 border-lime-400 border-t-transparent rounded-full animate-spin mb-2"></div>
                      <p className="text-xs">Loading schema fields...</p>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      {statsColumns
                        .filter(col => col.name.toLowerCase() !== 'id')
                        .map(col => {
                          const colLower = col.name.toLowerCase();
                          const colLabel = col.name
                            .replace(/([A-Z])/g, ' $1') // insert a space before all caps
                            .replace(/^./, str => str.toUpperCase()) // uppercase the first character
                            .trim();

                          // Custom input mapping
                          let inputControl;
                          if (colLower === 'date') {
                            inputControl = (
                              <input
                                type="date"
                                value={statsPayload[col.name] || ''}
                                onChange={(e) => setStatsPayload(prev => ({ ...prev, [col.name]: e.target.value }))}
                                className="w-full px-3 py-2 rounded-lg border border-zinc-800 bg-zinc-950 text-white focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 text-xs font-semibold"
                                required
                              />
                            );
                          } else if (colLower === 'result') {
                            inputControl = (
                              <select
                                value={statsPayload[col.name] || ''}
                                onChange={(e) => setStatsPayload(prev => ({ ...prev, [col.name]: e.target.value }))}
                                className="w-full px-3 py-2 rounded-lg border border-zinc-800 bg-zinc-950 text-white focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 text-xs font-semibold cursor-pointer"
                                required
                              >
                                <option value="" className="bg-zinc-950 text-white">Select Result</option>
                                <option value="Won" className="bg-zinc-950 text-white">Won</option>
                                <option value="Lost" className="bg-zinc-950 text-white">Lost</option>
                                <option value="Draw" className="bg-zinc-950 text-white">Draw</option>
                                <option value="Tied" className="bg-zinc-950 text-white">Tied</option>
                              </select>
                            );
                          } else if (col.type.toLowerCase().includes('int') || col.type.toLowerCase().includes('decimal') || col.type.toLowerCase().includes('numeric') || col.type.toLowerCase().includes('float')) {
                            const isStrikeRate = colLower === 'strikerate' || colLower === 'strike_rate';
                            inputControl = (
                              <input
                                type="number"
                                step="any"
                                placeholder={isStrikeRate ? "S/R (Auto-computed if empty)" : "0"}
                                value={statsPayload[col.name] || ''}
                                onChange={(e) => setStatsPayload(prev => ({ ...prev, [col.name]: e.target.value }))}
                                className="w-full px-3 py-2 rounded-lg border border-zinc-800 bg-zinc-950 text-white focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 text-xs font-semibold"
                                required={!isStrikeRate && col.isNullable === false}
                              />
                            );
                          } else {
                            inputControl = (
                              <input
                                type="text"
                                placeholder={colLabel}
                                value={statsPayload[col.name] || ''}
                                onChange={(e) => setStatsPayload(prev => ({ ...prev, [col.name]: e.target.value }))}
                                className="w-full px-3 py-2 rounded-lg border border-zinc-800 bg-zinc-950 text-white focus:ring-2 focus:ring-lime-400/20 focus:border-lime-400 text-xs font-semibold"
                                required={col.isNullable === false}
                              />
                            );
                          }

                          return (
                            <div key={col.name} className="space-y-1">
                              <label className="block text-[10px] font-bold uppercase tracking-wider text-neutral-400">
                                {colLabel}
                                {col.isNullable === false && <span className="text-rose-500 ml-0.5">*</span>}
                              </label>
                              {inputControl}
                            </div>
                          );
                        })}
                    </div>
                  )}

                  {/* Submit Button */}
                  <button
                    type="submit"
                    disabled={statsSubmitting || statsLoading}
                    className={`w-full py-3.5 px-6 rounded-xl font-bold text-sm tracking-wide transition-all shadow-md flex items-center justify-center gap-2 ${
                      statsSubmitting || statsLoading
                        ? 'bg-zinc-950 border border-zinc-850 text-neutral-500 cursor-not-allowed shadow-none'
                        : 'bg-lime-500 hover:bg-lime-400 text-black cursor-pointer hover:shadow-lg'
                    }`}
                  >
                    {statsSubmitting ? (
                      <>
                        <div className="w-5 h-5 border-2 border-black border-t-transparent rounded-full animate-spin"></div>
                        <span>Saving Stats...</span>
                      </>
                    ) : (
                      <>
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                        </svg>
                        <span>{selectedRecordId ? 'Update Existing Record' : 'Create New Stats Record'}</span>
                      </>
                    )}
                  </button>
                </form>
              </div>
            </div>

            {/* Right Column: Historical Logs */}
            <div className="p-6 sm:p-8 lg:p-10 lg:col-span-7 bg-zinc-950 flex flex-col justify-between">
              <div className="space-y-6 flex-grow flex flex-col">
                <div className="flex items-center justify-between">
                  <h3 className="display-font text-sm font-bold uppercase tracking-wider text-neutral-400">
                    {statsFormat} Match Record Logs
                  </h3>
                  <span className="text-[10px] font-bold px-2 py-1 bg-lime-950/40 text-lime-400 rounded border border-lime-500/20">
                    {statsRecords.length} Matches Found
                  </span>
                </div>

                {statsLoading ? (
                  <div className="flex-1 flex items-center justify-center py-20 text-center text-neutral-400">
                    <div>
                      <div className="inline-block w-8 h-8 border-4 border-lime-400 border-t-transparent rounded-full animate-spin mb-3"></div>
                      <p className="text-xs font-semibold">Loading logs...</p>
                    </div>
                  </div>
                ) : statsRecords.length === 0 ? (
                  <div className="flex-1 flex items-center justify-center py-20 text-center text-neutral-400 border border-zinc-800 rounded-2xl bg-zinc-900 p-6">
                    <div>
                      <svg className="w-10 h-10 text-neutral-500 mx-auto mb-2" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                      </svg>
                      <p className="font-bold text-white">No records found for {statsFormat}.</p>
                      <p className="text-xs text-neutral-500 mt-1">Submit the stats form to populate this table.</p>
                    </div>
                  </div>
                ) : (
                  <div className="overflow-x-auto rounded-xl border border-zinc-800 bg-zinc-900 max-h-[500px]">
                    <table className="min-w-full divide-y divide-zinc-800 text-left">
                      <thead className="bg-zinc-950 text-[10px] font-bold text-neutral-400 uppercase tracking-wider sticky top-0 z-10">
                        <tr>
                          <th className="px-4 py-3 bg-zinc-950">Date</th>
                          <th className="px-4 py-3 bg-zinc-950">Opponent</th>
                          <th className="px-4 py-3 bg-zinc-950">Tournament</th>
                          <th className="px-4 py-3 text-center bg-zinc-950">Runs</th>
                          <th className="px-4 py-3 text-center bg-zinc-950">S/R</th>
                          <th className="px-4 py-3 text-center bg-zinc-950">Result</th>
                          <th className="px-4 py-3 text-right bg-zinc-950">Actions</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-zinc-800/60 text-xs text-neutral-300 font-semibold">
                        {statsRecords.map(r => {
                          const id = r.id || r.ID;
                          const dateStr = r.date ? new Date(r.date).toLocaleDateString() : 'N/A';
                          const runsVal = r.runs !== undefined ? r.runs : (r.Runs || 0);
                          const srVal = r.strike_rate !== undefined ? r.strike_rate : (r.StrikeRate || '-');
                          const resultVal = r.result || r.Result || 'N/A';

                          let resultClass = 'bg-zinc-850 text-neutral-300 border border-zinc-800';
                          if (resultVal.toLowerCase() === 'won') resultClass = 'bg-lime-950/40 text-lime-400 border border-lime-500/20';
                          if (resultVal.toLowerCase() === 'lost') resultClass = 'bg-rose-950/40 text-rose-400 border border-rose-500/20';
                          if (resultVal.toLowerCase() === 'draw' || resultVal.toLowerCase() === 'tied') resultClass = 'bg-amber-950/40 text-amber-400 border border-amber-500/20';

                          return (
                            <tr key={id} className="hover:bg-zinc-800/30 transition-colors">
                              <td className="px-4 py-3 whitespace-nowrap font-bold text-white">{dateStr}</td>
                              <td className="px-4 py-3 whitespace-nowrap">{r.opposition || r.Opponent || '-'}</td>
                              <td className="px-4 py-3 whitespace-nowrap text-neutral-400">{r.Tournament || r.tournament || 'N/A'}</td>
                              <td className="px-4 py-3 text-center whitespace-nowrap font-mono font-bold text-lime-400">{runsVal}</td>
                              <td className="px-4 py-3 text-center whitespace-nowrap font-mono text-neutral-400">{srVal}%</td>
                              <td className="px-4 py-3 text-center whitespace-nowrap">
                                <span className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider ${resultClass}`}>
                                  {resultVal}
                                </span>
                              </td>
                              <td className="px-4 py-3 text-right whitespace-nowrap">
                                <div className="flex justify-end gap-1">
                                  <button
                                    onClick={() => handleRecordSelect(id)}
                                    className="p-1 text-neutral-500 hover:text-lime-400 hover:bg-lime-950/40 rounded transition-colors cursor-pointer"
                                    title="Edit Record"
                                  >
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                    </svg>
                                  </button>
                                  <button
                                    onClick={() => handleStatsDelete(id)}
                                    className="p-1 text-neutral-500 hover:text-rose-400 hover:bg-rose-950/40 rounded transition-colors cursor-pointer"
                                    title="Delete Record"
                                  >
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-16v1a3 3 0 003 3h10a3 3 0 003-3v-1M4 7h16" />
                                    </svg>
                                  </button>
                                </div>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>

          </div>
        </div>
      )}

      {/* Milestones Records Manager Panel */}
      {activeTab === 'records' && (
        <div className="space-y-8 animate-fade-in text-white">
          <div className="bg-zinc-900 rounded-3xl border border-zinc-800 shadow-sm overflow-hidden grid grid-cols-1 lg:grid-cols-12">
            
            {/* Form Section */}
            <div className="p-6 sm:p-8 lg:p-10 lg:col-span-5 border-b lg:border-b-0 lg:border-r border-zinc-800 flex flex-col justify-between">
              <div>
                <h2 className="display-font text-xl font-bold text-white mb-2 flex items-center gap-2">
                  <svg className="w-5 h-5 text-lime-400" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5a2 2 0 10-2 2h2zm0 0h4m-4 0H8" />
                  </svg>
                  Custom Milestones
                </h2>
                <p className="text-neutral-400 text-xs mb-6 font-semibold">
                  Add or update premium milestone cards displayed on the public Stats page. If a record with the same format and title exists, it will update the value and description.
                </p>

                <form onSubmit={handleRecordSubmit} className="space-y-4">
                  {/* Format Selector */}
                  <div>
                    <label className="block text-[10px] font-bold text-neutral-400 uppercase tracking-wider mb-1.5">
                      Cricket Format
                    </label>
                    <select
                      value={recordFormat}
                      onChange={(e) => setRecordFormat(e.target.value)}
                      className="w-full bg-zinc-950 hover:bg-zinc-900 border border-zinc-800 rounded-xl px-4 py-2.5 text-xs text-white font-bold focus:outline-none focus:ring-2 focus:ring-lime-400 transition-colors"
                    >
                      <option value="ODI" className="bg-zinc-950 text-white">ODI (One Day International)</option>
                      <option value="T20I" className="bg-zinc-950 text-white">T20I (Twenty20 International)</option>
                      <option value="Test" className="bg-zinc-950 text-white">Test (Test Matches)</option>
                      <option value="PSL" className="bg-zinc-950 text-white">PSL (Pakistan Super League)</option>
                    </select>
                  </div>

                  {/* Title */}
                  <div>
                    <label className="block text-[10px] font-bold text-neutral-400 uppercase tracking-wider mb-1.5">
                      Milestone Title
                    </label>
                    <input
                      type="text"
                      required
                      placeholder="e.g., Highest Individual Score, Total Centuries"
                      value={recordTitle}
                      onChange={(e) => setRecordTitle(e.target.value)}
                      className="w-full bg-zinc-950 hover:bg-zinc-900 border border-zinc-800 rounded-xl px-4 py-2.5 text-xs font-semibold text-white focus:outline-none focus:ring-2 focus:ring-lime-400 transition-colors placeholder:text-neutral-500"
                    />
                  </div>

                  {/* Value */}
                  <div>
                    <label className="block text-[10px] font-bold text-neutral-400 uppercase tracking-wider mb-1.5">
                      Milestone Value
                    </label>
                    <input
                      type="text"
                      required
                      placeholder="e.g., 210*, 15, 3450"
                      value={recordValue}
                      onChange={(e) => setRecordValue(e.target.value)}
                      className="w-full bg-zinc-950 hover:bg-zinc-900 border border-zinc-800 rounded-xl px-4 py-2.5 text-xs font-semibold text-white focus:outline-none focus:ring-2 focus:ring-lime-400 transition-colors placeholder:text-neutral-500"
                    />
                  </div>

                  {/* Description */}
                  <div>
                    <label className="block text-[10px] font-bold text-neutral-400 uppercase tracking-wider mb-1.5">
                      Short Description
                    </label>
                    <textarea
                      placeholder="e.g., Scored against Zimbabwe in 2018, or Career overall record."
                      value={recordDescription}
                      onChange={(e) => setRecordDescription(e.target.value)}
                      rows={3}
                      className="w-full bg-zinc-950 hover:bg-zinc-900 border border-zinc-800 rounded-xl px-4 py-2.5 text-xs font-semibold text-white focus:outline-none focus:ring-2 focus:ring-lime-400 transition-colors resize-none placeholder:text-neutral-500"
                    />
                  </div>

                  <div className="space-y-2">
                    <button
                      type="submit"
                      disabled={recordsSubmitting || !secretKey}
                      className="w-full py-3 bg-lime-500 text-black rounded-xl text-xs font-black hover:bg-lime-400 active:bg-lime-300 transition-colors shadow-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                    >
                      {recordsSubmitting ? (
                        <>
                          <div className="w-3.5 h-3.5 border-2 border-black border-t-transparent rounded-full animate-spin"></div>
                          {editingRecordId ? 'Updating Milestone...' : 'Saving Milestone...'}
                        </>
                      ) : (
                        editingRecordId ? 'Update Milestone Record' : 'Save Milestone Record'
                      )}
                    </button>
                    {editingRecordId && (
                      <button
                        type="button"
                        onClick={() => {
                          setRecordTitle('');
                          setRecordValue('');
                          setRecordDescription('');
                          setEditingRecordId(null);
                        }}
                        className="w-full py-2 bg-zinc-800 text-white rounded-xl text-xs font-bold hover:bg-zinc-700 transition-colors cursor-pointer"
                      >
                        Cancel Editing
                      </button>
                    )}
                  </div>
                  {!secretKey && (
                    <p className="text-[10px] text-rose-500 font-semibold text-center mt-1">
                      Please enter your Admin Secret Key at the top of the dashboard first.
                    </p>
                  )}
                </form>
              </div>
            </div>

            {/* Existing Milestones List Section */}
            <div className="p-6 sm:p-8 lg:p-10 lg:col-span-7 bg-zinc-950 flex flex-col justify-between">
              <div>
                <h3 className="display-font text-lg font-bold text-white mb-6 flex items-center justify-between">
                  <span>Current Live Milestones</span>
                  <span className="text-[10px] font-bold bg-lime-950/40 text-lime-400 px-2.5 py-1 rounded-full border border-lime-500/20">
                    {records.length} Total
                  </span>
                </h3>

                {recordsLoading ? (
                  <div className="py-20 text-center text-neutral-400">
                    <div className="inline-block w-8 h-8 border-4 border-lime-400 border-t-transparent rounded-full animate-spin mb-3"></div>
                    <p className="text-xs font-semibold">Loading milestones...</p>
                  </div>
                ) : records.length === 0 ? (
                  <div className="py-20 text-center text-neutral-400 border border-dashed border-zinc-800 rounded-2xl bg-zinc-900/30 p-6">
                    <svg className="w-8 h-8 text-neutral-500 mx-auto mb-2" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.907c.961 0 1.36 1.233.582 1.833l-3.97 2.883a1 1 0 00-.364 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.971-2.883a1 1 0 00-1.18 0l-3.97 2.883c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.364-1.118l-3.97-2.883c-.779-.6-.38-1.833.582-1.833h4.907a1 1 0 00.951-.69l1.519-4.674z" />
                    </svg>
                    <p className="font-bold text-white text-sm">No Milestones Found</p>
                    <p className="text-xs text-neutral-500 mt-1">Submit the form on the left to add a custom milestone record.</p>
                  </div>
                ) : (
                  <div className="space-y-3 max-h-[500px] overflow-y-auto pr-1">
                    {records.map(rec => {
                      const recId = rec.id || rec.ID;
                      return (
                        <div
                          key={recId}
                          className="p-4 rounded-xl border border-zinc-800 bg-zinc-900 hover:bg-zinc-850 transition-all flex justify-between items-start gap-4"
                        >
                          <div className="space-y-1">
                            <div className="flex items-center gap-2">
                              <span className="text-[9px] font-bold tracking-wider px-2 py-0.5 rounded-full uppercase bg-zinc-800 text-neutral-400 border border-zinc-700">
                                {rec.format || rec.FORMAT}
                              </span>
                              <h4 className="text-xs font-bold text-white">{rec.record_title || rec.RECORD_TITLE}</h4>
                            </div>
                            <p className="text-xs text-neutral-400 font-semibold">{rec.description || rec.DESCRIPTION || 'No description provided.'}</p>
                          </div>
                          <div className="text-right flex flex-col items-end justify-between h-full min-h-[50px]">
                            <div className="text-sm font-black text-lime-400 font-mono tracking-tight">{rec.record_value || rec.RECORD_VALUE}</div>
                            <div className="flex items-center gap-2 mt-2">
                              <button
                                onClick={() => {
                                  setRecordFormat(rec.format || rec.FORMAT || 'ODI');
                                  setRecordTitle(rec.record_title || rec.RECORD_TITLE || '');
                                  setRecordValue(rec.record_value || rec.RECORD_VALUE || '');
                                  setRecordDescription(rec.description || rec.DESCRIPTION || '');
                                  setEditingRecordId(recId);
                                }}
                                className="text-[10px] text-lime-400 hover:text-lime-300 font-bold transition-colors cursor-pointer inline-block"
                              >
                                Edit
                              </button>
                              <span className="text-zinc-700 text-[10px]">|</span>
                              <button
                                onClick={() => handleRecordDelete(recId)}
                                className="text-[10px] text-rose-400 hover:text-rose-300 font-bold transition-colors cursor-pointer inline-block"
                              >
                                Delete
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}

// Global exposure for React rendering on mount in raw html scripts
window.AdminGallery = AdminGallery;
