const { useState, useEffect, useRef } = React;

function FanPortal() {
  // Helper for daily lock key
  const getTodayDateKey = () => {
    try {
      return new Date().toISOString().split('T')[0];
    } catch (e) {
      return 'today';
    }
  };

  // --- USER IDENTITY & PREVIOUS HANDLE STATE ---
  const [userIdentity, setUserIdentity] = useState(() => {
    try {
      const saved = localStorage.getItem('fz_user_identity');
      return saved ? JSON.parse(saved) : null;
    } catch (e) {
      return null;
    }
  });

  const [previousHandle, setPreviousHandle] = useState(() => {
    try {
      return localStorage.getItem('fz_previous_handle') || '';
    } catch (e) {
      return '';
    }
  });

  const [showIdentityModal, setShowIdentityModal] = useState(false);
  const [identityForm, setIdentityForm] = useState({
    userName: userIdentity?.userName || '',
    socialPlatform: userIdentity?.socialPlatform || 'Twitter/X',
    userHandle: userIdentity?.userHandle || ''
  });

  // Action pending after identity capture (e.g., 'VOTE', 'QUIZ_SUBMIT', 'FEEDBACK')
  const [pendingAction, setPendingAction] = useState(null);

  // --- DAILY POLL STATE ---
  const [poll, setPoll] = useState(null);
  const [pollLoading, setPollLoading] = useState(true);
  const [selectedPollOption, setSelectedPollOption] = useState(null);
  const [pollSubmitting, setPollSubmitting] = useState(false);
  const [pollMessage, setPollMessage] = useState('');

  // --- DAILY QUIZ STATE (20s QUESTION TIMER) ---
  const [quizQuestions, setQuizQuestions] = useState([]);
  const [quizLoading, setQuizLoading] = useState(true);
  const [quizDay, setQuizDay] = useState(() => {
    const startDate = new Date("2026-08-27T00:00:00Z");
    const today = new Date();
    return (Math.floor((today - startDate) / (1000 * 60 * 60 * 24)) % 50) + 1;
  });
  const [quizTheme, setQuizTheme] = useState('');
  const [quizStarted, setQuizStarted] = useState(false);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedQuizAnswers, setSelectedQuizAnswers] = useState({});
  const [questionTimer, setQuestionTimer] = useState(20);
  const [quizCompleted, setQuizCompleted] = useState(() => {
    try {
      return Boolean(localStorage.getItem(`fz_quiz_completed_${new Date().toISOString().split('T')[0]}`));
    } catch (e) {
      return false;
    }
  });
  const [quizStartTime, setQuizStartTime] = useState(null);
  const [quizTimeTaken, setQuizTimeTaken] = useState(0);
  const [quizResult, setQuizResult] = useState(() => {
    try {
      const saved = localStorage.getItem(`fz_quiz_completed_${new Date().toISOString().split('T')[0]}`);
      return saved ? JSON.parse(saved) : null;
    } catch (e) {
      return null;
    }
  });
  const [quizSubmitting, setQuizSubmitting] = useState(false);
  const timerRef = useRef(null);

  // --- POSTER GRAPHIC & SHARE MODAL STATE ---
  const [showPosterModal, setShowPosterModal] = useState(false);
  const [posterData, setPosterData] = useState(() => {
    try {
      const saved = localStorage.getItem(`fz_quiz_completed_${new Date().toISOString().split('T')[0]}`);
      return saved ? JSON.parse(saved) : null;
    } catch (e) {
      return null;
    }
  });

  // --- LEADERBOARD STATE ---
  const [leaderboard, setLeaderboard] = useState([]);
  const [leaderboardLoading, setLeaderboardLoading] = useState(true);
  const [shareSuccessMessage, setShareSuccessMessage] = useState('');

  // --- FEEDBACK STATE ---
  const [feedbackRating, setFeedbackRating] = useState(5);
  const [feedbackComment, setFeedbackComment] = useState('');
  const [feedbackSubmitting, setFeedbackSubmitting] = useState(false);
  const [feedbackSuccess, setFeedbackSuccess] = useState('');

  // --- PORTAL OPERATIONAL & 8:00 PM CUTOFF CLOSURE STATE ---
  const [portalStatus, setPortalStatus] = useState(null);

  // Helper to check client-side PKT (UTC+5) auto-freeze (8:00 PM PKT / 20:00 to 8:00 AM PKT / 08:00)
  const isPktPortalTimeClosed = () => {
    const now = new Date();
    const utcHours = now.getUTCHours();
    const pktHour = (utcHours + 5) % 24;
    // Freeze if PKT time is between 8:00 PM (20:00) and 8:00 AM (08:00)
    return pktHour >= 20 || pktHour < 8;
  };

  const isPortalClosed = Boolean(portalStatus?.isClosed || isPktPortalTimeClosed());

  const fetchPortalStatus = async () => {
    try {
      const res = await fetch('/api/fan-portal/status');
      if (res.ok) {
        const data = await res.json();
        setPortalStatus(data);
      }
    } catch (err) {
      console.warn('Error fetching portal status:', err);
    }
  };

  // --- INITIAL DATA FETCH & SEO CONFIGURATION ---
  useEffect(() => {
    // Dynamic SEO Configuration
    document.title = "Fan Portal | Team Fakhar Zaman";
    
    // Ensure Canonical URL tag exists
    let canonical = document.querySelector('link[rel="canonical"]');
    if (!canonical) {
      canonical = document.createElement('link');
      canonical.rel = 'canonical';
      document.head.appendChild(canonical);
    }
    canonical.href = 'https://www.teamfakharzaman.site/fan-portal';

    // Check Local Storage Quiz Completed Lock
    const todayKey = getTodayDateKey();
    try {
      const savedQuiz = localStorage.getItem(`fz_quiz_completed_${todayKey}`);
      if (savedQuiz) {
        const parsed = JSON.parse(savedQuiz);
        setQuizCompleted(true);
        setQuizStarted(false);
        setQuizResult(parsed);
        setPosterData(parsed);
      }
    } catch (e) {}

    fetchPortalStatus();
    fetchActivePoll();
    fetchQuizQuestions();
    fetchLeaderboard();
  }, []);

  // Sync identity changes locally and re-fetch status
  useEffect(() => {
    if (userIdentity) {
      localStorage.setItem('fz_user_identity', JSON.stringify(userIdentity));
      setIdentityForm({
        userName: userIdentity.userName || '',
        socialPlatform: userIdentity.socialPlatform || 'Twitter/X',
        userHandle: userIdentity.userHandle || ''
      });
      fetchActivePoll();
      fetchQuizQuestions();
    }
  }, [userIdentity?.userHandle]);

  // --- POLL HANDLERS ---
  const fetchActivePoll = async () => {
    try {
      setPollLoading(true);
      const userHandle = userIdentity?.userHandle || '';
      const prevHandle = previousHandle || '';
      const res = await fetch(`/api/fan-portal/poll/active?userHandle=${encodeURIComponent(userHandle)}&previousHandle=${encodeURIComponent(prevHandle)}`);
      if (res.ok) {
        const data = await res.json();
        
        // Strict Local Storage Anti-Bypass Check for Poll
        const localVote = localStorage.getItem(`fz_poll_voted_${data.id}`);
        if (localVote !== null && !data.hasVoted) {
          data.hasVoted = true;
          data.userVotedOption = parseInt(localVote, 10);
        }

        setPoll(data);
      }
    } catch (err) {
      console.error('Error fetching poll:', err);
    } finally {
      setPollLoading(false);
    }
  };

  const handlePollVoteSubmit = async (optionIdxToVote = selectedPollOption) => {
    if (optionIdxToVote === null || optionIdxToVote === undefined) return;

    if (isPortalClosed) {
      setPollMessage("Today's poll voting has concluded at 8:00 PM PKT! Results are locked.");
      return;
    }

    if (!userIdentity || !userIdentity.userName || !userIdentity.userHandle) {
      setPendingAction({ type: 'POLL_VOTE', optionIndex: optionIdxToVote });
      setShowIdentityModal(true);
      return;
    }

    if (poll?.hasVoted || (poll?.id && localStorage.getItem(`fz_poll_voted_${poll.id}`) !== null)) {
      setPollMessage('You have already voted in this poll!');
      return;
    }

    try {
      setPollSubmitting(true);
      setPollMessage('');
      const res = await fetch('/api/fan-portal/poll/vote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          pollId: poll.id,
          optionIndex: optionIdxToVote,
          userName: userIdentity.userName,
          userHandle: userIdentity.userHandle,
          previousHandle: previousHandle || '',
          socialPlatform: userIdentity.socialPlatform
        })
      });

      const data = await res.json();
      if (res.ok) {
        // Lock in Local Storage to prevent exploit attempts
        if (poll?.id) {
          localStorage.setItem(`fz_poll_voted_${poll.id}`, optionIdxToVote.toString());
        }
        setPoll(data.poll);
        setPollMessage(data.message || 'Vote recorded!');
      } else {
        setPollMessage(data.error || 'Failed to submit vote');
      }
    } catch (err) {
      setPollMessage('Network error submitting vote');
    } finally {
      setPollSubmitting(false);
    }
  };

  // --- QUIZ HANDLERS (20 SECONDS PER QUESTION) ---
  const fetchQuizQuestions = async () => {
    try {
      setQuizLoading(true);
      const userHandle = userIdentity?.userHandle || '';
      const prevHandle = previousHandle || '';
      const res = await fetch(`/api/fan-portal/quiz/active?userHandle=${encodeURIComponent(userHandle)}&previousHandle=${encodeURIComponent(prevHandle)}`);
      if (res.ok) {
        const data = await res.json();
        let loadedQuestions = data.questions || [];
        if (data.day) setQuizDay(data.day);
        if (data.theme) setQuizTheme(data.theme);

        // Fallback to /data/daily_quizzes.json if API returned no questions
        if (loadedQuestions.length === 0) {
          try {
            const fallbackRes = await fetch('/data/daily_quizzes.json');
            if (fallbackRes.ok) {
              const allDays = await fallbackRes.json();
              const startDate = new Date("2026-08-27T00:00:00Z");
              const today = new Date();
              const activeDay = data.day || (Math.floor((today - startDate) / (1000 * 60 * 60 * 24)) % 50) + 1;
              const matchedDay = allDays.find(d => d.day === activeDay) || allDays[0];
              if (matchedDay && Array.isArray(matchedDay.questions)) {
                setQuizDay(matchedDay.day);
                setQuizTheme(matchedDay.theme);
                loadedQuestions = matchedDay.questions.map((q, idx) => {
                  const cleanOpts = (q.options || []).map(o => String(o).trim());
                  let correctIdx = cleanOpts.findIndex(opt => opt.toLowerCase() === String(q.correctAnswer).toLowerCase());
                  return {
                    id: q.id || idx + 1,
                    questionText: q.question,
                    options: cleanOpts,
                    correctOptionIndex: correctIdx !== -1 ? correctIdx : 0,
                    category: matchedDay.theme || 'Fakhar Zaman Trivia'
                  };
                });
              }
            }
          } catch (fbErr) {
            console.warn('[FAN PORTAL] Fallback daily quiz fetch error:', fbErr);
          }
        }

        setQuizQuestions(loadedQuestions);

        const todayKey = getTodayDateKey();
        const savedLocally = localStorage.getItem(`fz_quiz_completed_${todayKey}`);

        if ((data.hasCompleted && data.userScore) || savedLocally) {
          const scoreObj = (data.hasCompleted && data.userScore) ? data.userScore : JSON.parse(savedLocally);
          setQuizCompleted(true);
          setQuizStarted(false);
          setQuizResult(scoreObj);
          
          const posterObj = {
            userName: userIdentity?.userName || scoreObj.userName || 'FZ39 Fan',
            userHandle: userIdentity?.userHandle || scoreObj.userHandle || '@fan',
            socialPlatform: userIdentity?.socialPlatform || scoreObj.socialPlatform || 'Twitter/X',
            score: scoreObj.score,
            totalQuestions: scoreObj.totalQuestions,
            rank: scoreObj.rank,
            timeTakenSeconds: scoreObj.timeTakenSeconds
          };
          setPosterData(posterObj);

          if (!savedLocally) {
            localStorage.setItem(`fz_quiz_completed_${todayKey}`, JSON.stringify(posterObj));
          }
        }
      }
    } catch (err) {
      console.error('Error fetching quiz:', err);
    } finally {
      setQuizLoading(false);
    }
  };

  const startQuiz = () => {
    if (isPortalClosed) {
      alert("Today's Daily Quiz concluded at 8:00 PM PKT! Results are locked. Check back tomorrow at 8:00 AM PKT for the next challenge.");
      return;
    }

    if (!userIdentity || !userIdentity.userName || !userIdentity.userHandle) {
      setPendingAction({ type: 'START_QUIZ' });
      setShowIdentityModal(true);
      return;
    }

    const todayKey = getTodayDateKey();
    if (quizCompleted || quizResult || localStorage.getItem(`fz_quiz_completed_${todayKey}`)) {
      alert("You have already completed today's quiz! Check back tomorrow for new trivia.");
      return;
    }

    setQuizStarted(true);
    setCurrentQuestionIndex(0);
    setSelectedQuizAnswers({});
    setQuizCompleted(false);
    setQuestionTimer(20);
    setQuizStartTime(Date.now());

    startTimer();
  };

  const startTimer = () => {
    if (timerRef.current) clearInterval(timerRef.current);
    setQuestionTimer(20);
    timerRef.current = setInterval(() => {
      setQuestionTimer((prev) => {
        if (prev <= 1) {
          handleNextQuestionTimeout();
          return 20;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const handleNextQuestionTimeout = () => {
    setCurrentQuestionIndex((prevIndex) => {
      if (prevIndex + 1 < quizQuestions.length) {
        setQuestionTimer(20);
        return prevIndex + 1;
      } else {
        finishQuiz();
        return prevIndex;
      }
    });
  };

  const selectQuizOption = (questionId, optionIdx) => {
    setSelectedQuizAnswers((prev) => ({ ...prev, [questionId]: optionIdx }));
  };

  const handleNextQuestion = () => {
    if (currentQuestionIndex + 1 < quizQuestions.length) {
      setCurrentQuestionIndex(prev => prev + 1);
      setQuestionTimer(20);
    } else {
      finishQuiz();
    }
  };

  const finishQuiz = () => {
    if (timerRef.current) clearInterval(timerRef.current);
    const endTime = Date.now();
    const totalAllowed = (quizQuestions.length || 5) * 20;
    const rawTimeTaken = Math.round((endTime - (quizStartTime || endTime)) / 1000);
    const timeTaken = Math.min(totalAllowed, Math.max(3, rawTimeTaken));
    setQuizTimeTaken(timeTaken);

    // Calculate score
    let calculatedScore = 0;
    quizQuestions.forEach((q) => {
      if (selectedQuizAnswers[q.id] === q.correctOptionIndex) {
        calculatedScore += 1;
      }
    });

    setQuizCompleted(true);
    setQuizStarted(false);

    // Auto-submit score to Leaderboard
    submitQuizScore(calculatedScore, quizQuestions.length, timeTaken);
  };

  const submitQuizScore = async (score, total, timeTaken) => {
    if (!userIdentity) return;
    const todayKey = getTodayDateKey();

    try {
      setQuizSubmitting(true);
      const res = await fetch('/api/fan-portal/quiz/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userName: userIdentity.userName,
          socialPlatform: userIdentity.socialPlatform,
          userHandle: userIdentity.userHandle,
          previousHandle: previousHandle || '',
          score,
          totalQuestions: total,
          timeTakenSeconds: timeTaken
        })
      });

      const data = await res.json();
      if (res.ok) {
        setQuizResult(data);
        fetchLeaderboard();

        // Prepare poster graphic data
        const posterObj = {
          userName: userIdentity.userName,
          userHandle: userIdentity.userHandle,
          socialPlatform: userIdentity.socialPlatform,
          score: data.score,
          totalQuestions: data.totalQuestions,
          rank: data.rank,
          timeTakenSeconds: data.timeTakenSeconds
        };
        setPosterData(posterObj);

        // Strict client-side one-attempt lock
        localStorage.setItem(`fz_quiz_completed_${todayKey}`, JSON.stringify(posterObj));
      } else if (data.alreadyCompleted) {
        const lockedObj = {
          score: data.score,
          totalQuestions: data.totalQuestions,
          timeTakenSeconds: data.timeTakenSeconds,
          rank: data.rank,
          userName: userIdentity.userName,
          userHandle: userIdentity.userHandle,
          socialPlatform: userIdentity.socialPlatform
        };
        setQuizResult(lockedObj);
        setPosterData(lockedObj);
        localStorage.setItem(`fz_quiz_completed_${todayKey}`, JSON.stringify(lockedObj));

        if (data.leaderboard) {
          setLeaderboard(data.leaderboard);
        } else {
          fetchLeaderboard();
        }
      }
    } catch (err) {
      console.error('Error submitting score:', err);
    } finally {
      setQuizSubmitting(false);
    }
  };

  // --- LEADERBOARD & FEEDBACK FETCH ---
  const fetchLeaderboard = async () => {
    try {
      setLeaderboardLoading(true);
      const res = await fetch('/api/fan-portal/leaderboard');
      if (res.ok) {
        const data = await res.json();
        setLeaderboard(data);
      }
    } catch (err) {
      console.error('Error fetching leaderboard:', err);
    } finally {
      setLeaderboardLoading(false);
    }
  };

  const handleFeedbackSubmit = async (e) => {
    e.preventDefault();
    if (!feedbackComment.trim()) return;

    if (!userIdentity || !userIdentity.userName || !userIdentity.userHandle) {
      setPendingAction({ type: 'SUBMIT_FEEDBACK' });
      setShowIdentityModal(true);
      return;
    }

    try {
      setFeedbackSubmitting(true);
      setFeedbackSuccess('');
      const res = await fetch('/api/fan-portal/feedback', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userName: userIdentity.userName,
          socialPlatform: userIdentity.socialPlatform,
          userHandle: userIdentity.userHandle,
          rating: feedbackRating,
          comment: feedbackComment
        })
      });

      const data = await res.json();
      if (res.ok) {
        setFeedbackComment('');
        setFeedbackSuccess('Thank you for your feedback! 💚 Your message has been sent directly to Team FZ39.');
        setTimeout(() => setFeedbackSuccess(''), 5000);
      } else {
        setFeedbackSuccess(data.error || 'Failed to submit feedback.');
      }
    } catch (err) {
      console.error('Error submitting feedback:', err);
      setFeedbackSuccess('Network error submitting feedback.');
    } finally {
      setFeedbackSubmitting(false);
    }
  };

  // --- IDENTITY MODAL SAVE & DATABASE SYNCHRONIZATION ---
  const handleIdentitySave = async (e) => {
    e.preventDefault();
    if (!identityForm.userName.trim() || !identityForm.userHandle.trim()) {
      alert('Please provide your name and social handle!');
      return;
    }

    const formattedHandle = identityForm.userHandle.trim().startsWith('@')
      ? identityForm.userHandle.trim()
      : `@${identityForm.userHandle.trim()}`;

    const prevHandle = userIdentity?.userHandle || previousHandle || formattedHandle;

    const updatedUser = {
      userName: identityForm.userName.trim(),
      socialPlatform: identityForm.socialPlatform || 'Twitter/X',
      userHandle: formattedHandle
    };

    // Track previous and new handle in state & localStorage
    localStorage.setItem('fz_previous_handle', prevHandle);
    setPreviousHandle(prevHandle);
    setUserIdentity(updatedUser);
    localStorage.setItem('fz_user_identity', JSON.stringify(updatedUser));
    setShowIdentityModal(false);

    // Synchronize Identity with MSSQL Backend Database
    try {
      const syncRes = await fetch('/api/fan-portal/identity/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          previousHandle: prevHandle,
          newUserName: updatedUser.userName,
          newSocialPlatform: updatedUser.socialPlatform,
          newUserHandle: updatedUser.userHandle
        })
      });

      if (syncRes.ok) {
        const syncData = await syncRes.json();
        if (syncData.leaderboard) {
          setLeaderboard(syncData.leaderboard);
        } else {
          fetchLeaderboard();
        }
      }
    } catch (syncErr) {
      console.error('Error syncing identity to DB:', syncErr);
    }

    // Refresh poll & quiz status under new identity
    fetchActivePoll();
    fetchQuizQuestions();

    // Resume pending action if any
    if (pendingAction) {
      if (pendingAction.type === 'POLL_VOTE') {
        handlePollVoteSubmit(pendingAction.optionIndex);
      } else if (pendingAction.type === 'START_QUIZ') {
        setTimeout(() => startQuiz(), 200);
      } else if (pendingAction.type === 'SUBMIT_FEEDBACK') {
        // user can now submit feedback
      }
      setPendingAction(null);
    }
  };

  // --- POSTER GRAPHIC GENERATOR & SOCIAL SHARE HELPERS ---
  const openPosterModal = (customData = null) => {
    const dataToUse = customData || (quizResult ? {
      userName: userIdentity?.userName || 'FZ39 Fan',
      userHandle: userIdentity?.userHandle || '@fan',
      socialPlatform: userIdentity?.socialPlatform || 'Twitter/X',
      score: quizResult.score,
      totalQuestions: quizResult.totalQuestions,
      rank: quizResult.rank,
      timeTakenSeconds: quizResult.timeTakenSeconds
    } : (leaderboard.length > 0 ? {
      userName: leaderboard[0].userName,
      userHandle: leaderboard[0].userHandle,
      socialPlatform: leaderboard[0].socialPlatform,
      score: leaderboard[0].score,
      totalQuestions: leaderboard[0].totalQuestions || 5,
      rank: 1,
      timeTakenSeconds: leaderboard[0].timeTakenSeconds
    } : {
      userName: userIdentity?.userName || 'Team FZ39 Member',
      userHandle: userIdentity?.userHandle || '@fz39fan',
      socialPlatform: userIdentity?.socialPlatform || 'Twitter/X',
      score: 0,
      totalQuestions: quizQuestions.length || 0,
      rank: '-',
      timeTakenSeconds: 0
    }));

    setPosterData(dataToUse);
    setShowPosterModal(true);
  };

  const downloadPosterGraphic = (autoClose = true) => {
    if (!posterData) return;

    const canvas = document.createElement('canvas');
    canvas.width = 1080;
    canvas.height = 1350; // Standard 4:5 social media resolution (Instagram / Facebook / X)
    const ctx = canvas.getContext('2d');

    // Background Dark Slate Theme
    ctx.fillStyle = '#090d16';
    ctx.fillRect(0, 0, 1080, 1350);

    // Glowing Radial Light
    const glow = ctx.createRadialGradient(540, 420, 50, 540, 420, 650);
    glow.addColorStop(0, 'rgba(139, 228, 28, 0.28)');
    glow.addColorStop(1, 'rgba(9, 13, 22, 0)');
    ctx.fillStyle = glow;
    ctx.fillRect(0, 0, 1080, 1350);

    // Dynamic Diagonal Sports Stripes
    ctx.strokeStyle = 'rgba(139, 228, 28, 0.08)';
    ctx.lineWidth = 14;
    for (let x = -500; x < 2000; x += 110) {
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x + 420, 1350);
      ctx.stroke();
    }

    // Outer Dark Frame Border
    ctx.strokeStyle = '#27272a';
    ctx.lineWidth = 16;
    ctx.strokeRect(40, 40, 1000, 1270);

    // Inner Lime Border Frame
    ctx.strokeStyle = '#8BE41C';
    ctx.lineWidth = 6;
    ctx.strokeRect(54, 54, 972, 1242);

    // Header Badge & Title
    ctx.fillStyle = '#8BE41C';
    ctx.font = '800 34px "Space Grotesk", sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('⚡ OFFICIAL FZ39 FAN PORTAL', 540, 125);

    ctx.fillStyle = '#FFFFFF';
    ctx.font = '900 70px "Space Grotesk", sans-serif';
    ctx.fillText('FAKHAR ZAMAN FAN QUIZ', 540, 205);

    // Green Accent Bar
    ctx.fillStyle = '#8BE41C';
    ctx.fillRect(340, 230, 400, 8);

    // Main Certificate Card Box
    ctx.fillStyle = '#121824';
    ctx.fillRect(100, 270, 880, 810);
    ctx.strokeStyle = '#27272a';
    ctx.lineWidth = 4;
    ctx.strokeRect(100, 270, 880, 810);

    // Fan Name & Platform
    ctx.fillStyle = '#9ca3af';
    ctx.font = '600 28px "Space Grotesk", sans-serif';
    ctx.fillText('PERFORMANCE & RANK CERTIFICATE', 540, 335);

    ctx.fillStyle = '#FFFFFF';
    ctx.font = '900 56px "Space Grotesk", sans-serif';
    ctx.fillText(posterData.userName || 'FZ39 Champion', 540, 405);

    ctx.fillStyle = '#8BE41C';
    ctx.font = '700 30px monospace';
    ctx.fillText(`${posterData.socialPlatform || 'Social'}: ${posterData.userHandle || '@fan'}`, 540, 455);

    // Score Highlight Box
    ctx.fillStyle = 'rgba(139, 228, 28, 0.12)';
    ctx.fillRect(220, 495, 640, 220);
    ctx.strokeStyle = '#8BE41C';
    ctx.lineWidth = 6;
    ctx.strokeRect(220, 495, 640, 220);

    ctx.fillStyle = '#8BE41C';
    ctx.font = '900 125px "Space Grotesk", sans-serif';
    ctx.fillText(`${posterData.score} / ${posterData.totalQuestions || 5}`, 540, 640);

    ctx.fillStyle = '#ffffff';
    ctx.font = '700 24px "Space Grotesk", sans-serif';
    ctx.fillText('OFFICIAL QUIZ SCORE', 540, 690);

    // Rank Highlight Badge
    ctx.fillStyle = '#8BE41C';
    ctx.fillRect(220, 745, 640, 95);
    ctx.fillStyle = '#000000';
    ctx.font = '900 46px "Space Grotesk", sans-serif';
    ctx.fillText(`🏆 LEADERBOARD RANK #${posterData.rank || 1}`, 540, 810);

    // Metrics
    const accuracy = Math.round(((posterData.score || 0) / (posterData.totalQuestions || 5)) * 100);
    ctx.fillStyle = '#e4e4e7';
    ctx.font = '700 30px "Space Grotesk", sans-serif';
    ctx.fillText(`⚡ Time: ${posterData.timeTakenSeconds || 10}s  |  Accuracy: ${accuracy}%`, 540, 890);

    // Verified Stamp
    ctx.fillStyle = '#8BE41C';
    ctx.font = '800 28px "Space Grotesk", sans-serif';
    ctx.fillText('✓ VERIFIED FZ39 TRIVIA CHAMPION', 540, 1020);

    // Footer Website URL
    ctx.fillStyle = '#FFFFFF';
    ctx.font = '800 34px "Space Grotesk", sans-serif';
    ctx.fillText('www.teamfakharzaman.site/fan-portal', 540, 1175);

    ctx.fillStyle = '#71717a';
    ctx.font = '500 22px sans-serif';
    ctx.fillText('Join the official fan community & play daily cricket polls & trivia!', 540, 1220);

    const a = document.createElement('a');
    a.download = `FZ39_Quiz_ScoreCard_${(posterData.userName || 'Fan').replace(/\s+/g, '_')}.png`;
    a.href = canvas.toDataURL('image/png');
    a.click();
    setShareSuccessMessage('Poster Graphic downloaded! 📸');

    if (autoClose) {
      setTimeout(() => {
        setShowPosterModal(false);
        setShareSuccessMessage('');
      }, 1200);
    } else {
      setTimeout(() => setShareSuccessMessage(''), 4000);
    }
  };

  const shareText = posterData
    ? `🎯 I scored ${posterData.score}/${posterData.totalQuestions} on the Team Fakhar Zaman Daily Quiz in ${posterData.timeTakenSeconds}s! Rank #${posterData.rank}! Test your FZ39 knowledge:`
    : quizResult
    ? `🎯 I scored ${quizResult.score}/${quizResult.totalQuestions} on the Team Fakhar Zaman Daily Quiz in ${quizResult.timeTakenSeconds}s! Rank #${quizResult.rank}! Test your FZ39 knowledge:`
    : `⚡ Join the Team Fakhar Zaman Fan Portal! Take daily polls, play trivia, and climb the leaderboard!`;

  const portalUrl = 'https://www.teamfakharzaman.site/fan-portal';

  const copyShareLink = () => {
    navigator.clipboard.writeText(`${shareText} ${portalUrl}`);
    setShareSuccessMessage('Copied link & score to clipboard! 📋');
    setTimeout(() => setShareSuccessMessage(''), 3000);
  };

  // Platform Icon Helper
  const getPlatformIcon = (platform) => {
    switch (platform) {
      case 'Twitter/X':
        return '𝕏';
      case 'Instagram':
        return '📸';
      case 'Facebook':
        return '📘';
      case 'TikTok':
        return '🎵';
      case 'WhatsApp':
        return '💬';
      default:
        return '🌐';
    }
  };

  return (
    <div class="space-y-12">
      {/* HERO BANNER & USER GATEWAY STATUS */}
      <section class="bg-gradient-to-r from-zinc-900 via-zinc-900/90 to-zinc-950 rounded-2xl p-6 sm:p-8 border border-zinc-800/80 shadow-2xl relative overflow-hidden">
        <div class="absolute top-0 right-0 -mt-8 -mr-8 w-64 h-64 bg-lime-500/10 rounded-full blur-3xl pointer-events-none"></div>
        
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6 relative z-10">
          <div class="space-y-3 max-w-2xl">
            <div class="inline-flex items-center space-x-2 bg-lime-500/15 border border-lime-500/30 px-3 py-1 rounded-full text-lime-400 text-xs font-bold uppercase tracking-wider">
              <span>⚡ Official Fan Community</span>
              <span class="w-1.5 h-1.5 bg-lime-400 rounded-full animate-ping"></span>
            </div>
            <h1 class="display-font text-3xl sm:text-4xl lg:text-5xl font-black text-white tracking-tight">
              TEAM FZ39 <span class="text-lime-400">FAN PORTAL</span>
            </h1>
            <p class="text-zinc-300 text-base sm:text-lg leading-relaxed">
              Vote in daily match polls, test your Fakhar Zaman cricket trivia knowledge, compete on the live fan leaderboard, and leave your feedback!
            </p>
          </div>

          {/* User Profile Badge or Login Button */}
          <div class="bg-zinc-950/80 border border-zinc-800 p-5 rounded-xl shadow-lg flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 min-w-[280px]">
            {userIdentity ? (
              <div class="flex items-center space-x-3">
                <div class="w-12 h-12 rounded-full bg-lime-500/20 border border-lime-500/40 flex items-center justify-center text-lime-400 text-xl font-black display-font">
                  {userIdentity.userName.charAt(0).toUpperCase()}
                </div>
                <div>
                  <div class="flex items-center space-x-2">
                    <span class="font-bold text-white text-base">{userIdentity.userName}</span>
                    <span class="text-xs bg-zinc-800 text-lime-400 px-2 py-0.5 rounded font-mono border border-zinc-700">
                      {getPlatformIcon(userIdentity.socialPlatform)} {userIdentity.socialPlatform}
                    </span>
                  </div>
                  <p class="text-xs text-lime-400/90 font-mono mt-0.5">{userIdentity.userHandle}</p>
                </div>
              </div>
            ) : (
              <div class="space-y-1">
                <p class="text-xs text-zinc-400 font-medium">Fan Identity</p>
                <p class="text-sm font-semibold text-zinc-200">Not signed in yet</p>
              </div>
            )}

            <button
              onClick={() => setShowIdentityModal(true)}
              class="w-full sm:w-auto px-4 py-2 bg-lime-500 hover:bg-lime-400 text-black font-bold text-xs uppercase tracking-wider rounded-lg transition-all duration-200 shadow-md flex items-center justify-center space-x-1.5 cursor-pointer"
            >
              <i data-lucide="user" class="w-3.5 h-3.5"></i>
              <span>{userIdentity ? 'Edit Identity' : 'Set Fan Handle'}</span>
            </button>
          </div>
        </div>
      </section>

      {/* 8:00 PM PKT CUTOFF BANNER */}
      {isPortalClosed && (
        <section class="bg-gradient-to-r from-amber-950/40 via-zinc-900 to-amber-950/40 border-2 border-amber-500/50 rounded-2xl p-5 sm:p-7 shadow-2xl relative overflow-hidden">
          <div class="absolute top-0 right-0 -mt-6 -mr-6 w-48 h-48 bg-amber-500/10 rounded-full blur-3xl pointer-events-none"></div>
          <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 relative z-10">
            <div class="flex items-start space-x-4">
              <div class="p-3.5 bg-amber-500/20 text-amber-400 border border-amber-500/30 rounded-2xl text-2xl shrink-0">
                🌙
              </div>
              <div class="space-y-1">
                <div class="flex items-center gap-2 flex-wrap">
                  <span class="bg-amber-500/20 text-amber-300 border border-amber-500/40 text-[10px] font-black uppercase px-2.5 py-0.5 rounded tracking-widest font-mono">
                    8:00 PM PKT Cutoff Active
                  </span>
                  <span class="text-xs text-amber-400/80 font-mono">Daily Event Concluded</span>
                </div>
                <h3 class="text-lg sm:text-xl font-bold text-white display-font">
                  Today's Poll & Quiz Have Concluded!
                </h3>
                <p class="text-xs sm:text-sm text-zinc-300 max-w-2xl leading-relaxed">
                  Results & leaderboard rankings are locked for the night. Check back tomorrow at <strong class="text-lime-400">8:00 AM PKT</strong> when the new daily poll & quiz challenge go live!
                </p>
              </div>
            </div>
            <div class="flex items-center gap-2 shrink-0 self-start sm:self-center">
              <span class="px-3.5 py-2 bg-amber-500/15 border border-amber-500/30 rounded-xl text-amber-300 text-xs font-bold font-mono inline-flex items-center space-x-1.5">
                <span>🔒 Results Locked</span>
              </span>
            </div>
          </div>
        </section>
      )}

      {/* SECTION 1: DAILY POLL */}
      <section class="bg-zinc-900/90 rounded-2xl p-6 sm:p-8 border border-zinc-800/80 shadow-xl relative">
        <div class="flex items-center justify-between border-b border-zinc-800 pb-4 mb-6">
          <div class="flex items-center space-x-3">
            <div class="p-2.5 bg-lime-500/10 border border-lime-500/20 rounded-xl text-lime-400">
              <i data-lucide="vote" class="w-6 h-6"></i>
            </div>
            <div>
              <h2 class="display-font text-xl sm:text-2xl font-bold text-white">Daily Match Poll</h2>
              <p class="text-xs sm:text-sm text-zinc-400">Cast your vote and see live community sentiment</p>
            </div>
          </div>
          <span class={`text-xs font-bold px-3 py-1 rounded-full border uppercase tracking-wider ${
            isPortalClosed
              ? 'bg-amber-500/20 text-amber-400 border-amber-500/30'
              : 'bg-lime-500/20 text-lime-400 border-lime-500/30'
          }`}>
            {isPortalClosed ? 'Voting Concluded' : 'Live Poll'}
          </span>
        </div>

        {pollLoading ? (
          <div class="space-y-4 animate-pulse">
            <div class="h-6 bg-zinc-800 rounded-lg w-3/4"></div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
              <div class="h-14 bg-zinc-800/70 rounded-xl border border-zinc-700/40"></div>
              <div class="h-14 bg-zinc-800/70 rounded-xl border border-zinc-700/40"></div>
              <div class="h-14 bg-zinc-800/70 rounded-xl border border-zinc-700/40"></div>
              <div class="h-14 bg-zinc-800/70 rounded-xl border border-zinc-700/40"></div>
            </div>
            <div class="flex justify-end pt-2">
              <div class="h-10 w-32 bg-zinc-800 rounded-xl"></div>
            </div>
          </div>
        ) : poll ? (
          <div class="space-y-6">
            <h3 class="text-lg sm:text-xl font-bold text-white display-font">{poll.question}</h3>

            {poll.hasVoted || isPortalClosed ? (
              /* Poll Results View */
              <div class="space-y-4">
                {poll.hasVoted ? (
                  <div class="p-3 bg-lime-500/10 border border-lime-500/30 rounded-xl text-lime-400 text-xs font-semibold flex items-center">
                    <span class="flex items-center space-x-1.5">
                      <span>⚡</span>
                      <span>You have voted in today's poll!</span>
                    </span>
                  </div>
                ) : (
                  <div class="p-3 bg-amber-500/10 border border-amber-500/30 rounded-xl text-amber-300 text-xs font-semibold flex items-center">
                    <span class="flex items-center space-x-1.5">
                      <span>🔒</span>
                      <span>Today's poll voting concluded at 8:00 PM PKT. Final results are locked.</span>
                    </span>
                  </div>
                )}

                <div class="space-y-3">
                  {poll.options.map((opt, idx) => {
                    const optionVotes = poll.votes[idx] || 0;
                    const percent = poll.totalVotes > 0 ? Math.round((optionVotes / poll.totalVotes) * 100) : 0;
                    const isUserChoice = poll.userVotedOption === idx;

                    return (
                      <div key={idx} class="space-y-1.5">
                        <div class="flex justify-between text-sm font-medium">
                          <span class={`flex items-center space-x-2 ${isUserChoice ? 'text-lime-400 font-bold' : 'text-zinc-200'}`}>
                            <span>{opt}</span>
                            {isUserChoice && (
                              <span class="bg-lime-500 text-black text-[10px] font-black px-1.5 py-0.5 rounded uppercase">Your Vote</span>
                            )}
                          </span>
                          <span class="text-lime-400 font-mono font-bold text-xs">{percent}%</span>
                        </div>
                        {/* Progress Bar */}
                        <div class="w-full bg-zinc-800 rounded-full h-3.5 overflow-hidden p-0.5 border border-zinc-700/50">
                          <div
                            class={`h-full rounded-full transition-all duration-700 ease-out ${
                              isUserChoice ? 'bg-gradient-to-r from-lime-500 to-lime-400' : 'bg-zinc-600'
                            }`}
                            style={{ width: `${percent}%` }}
                          ></div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            ) : (
              /* Voting Form View */
              <div class="space-y-4">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {poll.options.map((opt, idx) => (
                    <button
                      key={idx}
                      onClick={() => setSelectedPollOption(idx)}
                      class={`p-4 rounded-xl border text-left font-medium text-sm transition-all duration-200 cursor-pointer flex items-center space-x-3 ${
                        selectedPollOption === idx
                          ? 'bg-lime-500/15 border-lime-400 text-lime-300 shadow-md shadow-lime-500/10'
                          : 'bg-zinc-800/60 border-zinc-700/80 text-zinc-300 hover:border-zinc-500 hover:bg-zinc-800'
                      }`}
                    >
                      <div class={`w-5 h-5 rounded-full border flex items-center justify-center ${
                        selectedPollOption === idx ? 'border-lime-400 bg-lime-500' : 'border-zinc-500'
                      }`}>
                        {selectedPollOption === idx && <div class="w-2 h-2 rounded-full bg-black"></div>}
                      </div>
                      <span>{opt}</span>
                    </button>
                  ))}
                </div>

                <div class="flex items-center justify-end pt-2">
                  <button
                    onClick={() => handlePollVoteSubmit(selectedPollOption)}
                    disabled={selectedPollOption === null || pollSubmitting}
                    class="px-6 py-2.5 bg-lime-500 hover:bg-lime-400 disabled:opacity-50 text-black font-extrabold text-sm uppercase tracking-wider rounded-xl transition-all duration-200 shadow-lg cursor-pointer flex items-center space-x-2"
                  >
                    {pollSubmitting ? (
                      <span>Recording Vote...</span>
                    ) : (
                      <>
                        <span>Submit Vote</span>
                        <i data-lucide="arrow-right" class="w-4 h-4"></i>
                      </>
                    )}
                  </button>
                </div>
                {pollMessage && (
                  <p class="text-xs font-semibold text-lime-400 bg-lime-500/10 border border-lime-500/20 p-2 rounded-lg text-center">
                    {pollMessage}
                  </p>
                )}
              </div>
            )}
          </div>
        ) : (
          <div class="py-12 text-center text-zinc-400 space-y-2 bg-zinc-950/40 rounded-xl border border-zinc-800/60 p-6">
            <div class="w-12 h-12 bg-zinc-800/60 text-zinc-400 rounded-full flex items-center justify-center mx-auto text-xl">
              🗳️
            </div>
            <h4 class="text-base font-bold text-white display-font">Not uploaded yet</h4>
            <p class="text-xs text-zinc-400 max-w-sm mx-auto">
              No active poll at the moment! Check back soon for the next match prediction.
            </p>
          </div>
        )}
      </section>

      {/* SECTION 2: DAILY QUIZ */}
      <section class="bg-zinc-900/90 rounded-2xl p-6 sm:p-8 border border-zinc-800/80 shadow-xl relative">
        <div class="flex items-center justify-between border-b border-zinc-800 pb-4 mb-6">
          <div class="flex items-center space-x-3">
            <div class="p-2.5 bg-lime-500/10 border border-lime-500/20 rounded-xl text-lime-400">
              <i data-lucide="brain" class="w-6 h-6"></i>
            </div>
            <div>
              <h2 class="display-font text-xl sm:text-2xl font-bold text-white">Daily Fakhar Zaman Quiz</h2>
              <p class="text-xs sm:text-sm text-zinc-400">Test your FZ39 knowledge, earn points & rank on the leaderboard!</p>
            </div>
          </div>
          <span class={`text-xs font-bold px-3 py-1 rounded-full border uppercase tracking-wider ${
            isPortalClosed
              ? 'bg-amber-500/20 text-amber-400 border-amber-500/30'
              : 'bg-lime-500/20 text-lime-400 border-lime-500/30'
          }`}>
            {isPortalClosed ? 'Quiz Concluded' : 'Trivia Master'}
          </span>
        </div>

        {quizLoading ? (
          <div class="text-center py-8 max-w-xl mx-auto space-y-4 animate-pulse">
            <div class="w-16 h-16 bg-zinc-800 rounded-2xl mx-auto"></div>
            <div class="h-7 bg-zinc-800 rounded-lg w-2/3 mx-auto"></div>
            <div class="h-4 bg-zinc-800/70 rounded w-5/6 mx-auto"></div>
            <div class="h-4 bg-zinc-800/70 rounded w-4/6 mx-auto"></div>
            <div class="pt-2">
              <div class="h-12 w-48 bg-zinc-800 rounded-xl mx-auto"></div>
            </div>
          </div>
        ) : quizQuestions.length === 0 ? (
          <div class="py-12 text-center text-zinc-400 space-y-2 bg-zinc-950/40 rounded-xl border border-zinc-800/60 p-6">
            <div class="w-12 h-12 bg-zinc-800/60 text-zinc-400 rounded-full flex items-center justify-center mx-auto text-xl">
              🧠
            </div>
            <h4 class="text-base font-bold text-white display-font">Not uploaded yet</h4>
            <p class="text-xs text-zinc-400 max-w-sm mx-auto">
              Today's quiz hasn't been uploaded yet! Stay tuned.
            </p>
          </div>
        ) : isPortalClosed && !quizCompleted && !quizResult ? (
          /* Closed Quiz Notice */
          <div class="text-center py-8 max-w-xl mx-auto space-y-4 bg-zinc-950/60 p-6 rounded-2xl border border-zinc-800">
            <div class="w-14 h-14 bg-amber-500/15 text-amber-400 border border-amber-500/30 rounded-2xl flex items-center justify-center mx-auto text-2xl font-black">
              🌙
            </div>
            <h3 class="display-font text-2xl font-black text-white">Daily Quiz Concluded for Today</h3>
            <p class="text-zinc-300 text-sm leading-relaxed">
              Today's daily quiz concluded at <strong>8:00 PM PKT</strong>. Submissions are now closed and leaderboard rankings are locked. Check back tomorrow at <strong class="text-lime-400">8:00 AM PKT</strong> for the next challenge!
            </p>
            <div class="pt-2">
              <span class="inline-flex items-center space-x-2 px-4 py-2 bg-zinc-800 border border-zinc-700 text-zinc-400 rounded-xl text-xs font-mono font-bold">
                <span>🔒 Submissions Closed until 8:00 AM PKT</span>
              </span>
            </div>
          </div>
        ) : !quizStarted && !quizCompleted ? (
          /* Quiz Start Welcome Screen */
          <div class="text-center py-8 max-w-xl mx-auto space-y-5">
            <div class="w-16 h-16 bg-lime-500/15 text-lime-400 border border-lime-500/30 rounded-2xl flex items-center justify-center mx-auto text-2xl font-black display-font">
              🏆
            </div>
            <div>
              <div class="inline-flex items-center space-x-2 px-3 py-1 bg-lime-500/10 border border-lime-500/30 rounded-full text-lime-400 text-xs font-mono font-bold uppercase tracking-wider mb-2">
                <span>📅 Day {quizDay} of 50</span>
              </div>
              <h3 class="display-font text-2xl font-black text-white">
                {quizTheme ? quizTheme : 'Daily FZ39 Cricket Challenge'}
              </h3>
            </div>
            <p class="text-zinc-300 text-sm leading-relaxed">
              Answer {quizQuestions.length} verified multiple choice questions about Fakhar Zaman's career records, ODI masterclasses, and stats. Beat the 20s question clock to claim top spot on the Leaderboard!
            </p>
            <div class="pt-2">
              <button
                onClick={startQuiz}
                class="px-8 py-3.5 bg-lime-500 hover:bg-lime-400 text-black font-extrabold text-base uppercase tracking-wider rounded-xl transition-all duration-200 shadow-xl shadow-lime-500/20 cursor-pointer inline-flex items-center space-x-2 transform hover:scale-105"
              >
                <span>Start Quiz Challenge</span>
                <i data-lucide="play" class="w-5 h-5 fill-black"></i>
              </button>
            </div>
          </div>
        ) : quizStarted && quizQuestions[currentQuestionIndex] ? (
          /* Active Quiz Interface */
          <div class="space-y-6">
            {/* Question Header Status */}
            <div class="flex items-center justify-between bg-zinc-950 p-4 rounded-xl border border-zinc-800">
              <div class="flex items-center space-x-3">
                <span class="bg-lime-500 text-black font-black text-xs px-2.5 py-1 rounded uppercase">
                  Q{currentQuestionIndex + 1} of {quizQuestions.length}
                </span>
                <span class="text-xs text-zinc-400 font-medium hidden sm:inline">
                  {quizQuestions[currentQuestionIndex].category}
                </span>
              </div>

              {/* Timer Badge */}
              <div class={`flex items-center space-x-1.5 font-mono text-sm font-bold px-3 py-1 rounded-lg border ${
                questionTimer <= 5
                  ? 'bg-red-500/20 border-red-500/40 text-red-400 animate-pulse'
                  : 'bg-zinc-800 border-zinc-700 text-lime-400'
              }`}>
                <i data-lucide="clock" class="w-4 h-4"></i>
                <span>{questionTimer}s</span>
              </div>
            </div>

            {/* Question Text */}
            <div class="bg-zinc-950/60 p-5 rounded-xl border border-zinc-800">
              <h3 class="display-font text-lg sm:text-xl font-extrabold text-white">
                {quizQuestions[currentQuestionIndex].questionText}
              </h3>
            </div>

            {/* Multiple Choice Options */}
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {quizQuestions[currentQuestionIndex].options.map((opt, idx) => {
                const isSelected = selectedQuizAnswers[quizQuestions[currentQuestionIndex].id] === idx;
                return (
                  <button
                    key={idx}
                    onClick={() => selectQuizOption(quizQuestions[currentQuestionIndex].id, idx)}
                    class={`p-4 rounded-xl border text-left font-medium text-sm transition-all duration-200 cursor-pointer flex items-center justify-between ${
                      isSelected
                        ? 'bg-lime-500/20 border-lime-400 text-lime-300 font-bold shadow-md shadow-lime-500/10'
                        : 'bg-zinc-800/60 border-zinc-700/80 text-zinc-300 hover:border-zinc-500 hover:bg-zinc-800'
                    }`}
                  >
                    <span>{opt}</span>
                    <div class={`w-5 h-5 rounded-full border flex items-center justify-center ${
                      isSelected ? 'border-lime-400 bg-lime-500' : 'border-zinc-600'
                    }`}>
                      {isSelected && <div class="w-2 h-2 rounded-full bg-black"></div>}
                    </div>
                  </button>
                );
              })}
            </div>

            {/* Next Question / Finish Button */}
            <div class="flex justify-end pt-2">
              <button
                onClick={handleNextQuestion}
                disabled={selectedQuizAnswers[quizQuestions[currentQuestionIndex].id] === undefined}
                class="px-6 py-2.5 bg-lime-500 hover:bg-lime-400 disabled:opacity-40 text-black font-black text-sm uppercase tracking-wider rounded-xl transition-all duration-200 shadow-md cursor-pointer flex items-center space-x-2"
              >
                <span>{currentQuestionIndex + 1 === quizQuestions.length ? 'Finish Quiz' : 'Next Question'}</span>
                <i data-lucide="arrow-right" class="w-4 h-4"></i>
              </button>
            </div>
          </div>
        ) : quizCompleted ? (
          /* Quiz Locked Completion & Results View */
          <div class="text-center py-6 space-y-6 max-w-xl mx-auto">
            <div class="p-6 bg-zinc-950 rounded-2xl border border-lime-500/30 shadow-xl space-y-5">
              <div class="w-16 h-16 bg-lime-500/20 text-lime-400 rounded-full flex items-center justify-center mx-auto text-3xl font-black display-font">
                🏆
              </div>
              <div>
                <h3 class="display-font text-2xl font-black text-white">Quiz Challenge Completed!</h3>
                <p class="text-xs text-lime-400 font-semibold mt-1 flex items-center justify-center space-x-1">
                  <span>🔒 One Attempt Only — Your score is locked on the Leaderboard</span>
                </p>
              </div>

              {quizResult && (
                <div class="space-y-3 bg-zinc-900/80 p-4 rounded-xl border border-zinc-800">
                  <div class="inline-block bg-lime-500/10 border border-lime-500/30 text-lime-400 px-4 py-2 rounded-xl text-lg font-black display-font">
                    Score: {quizResult.score} / {quizResult.totalQuestions} ({quizResult.timeTakenSeconds}s)
                  </div>
                  <p class="text-sm text-zinc-300">
                    Leaderboard Rank: <span class="text-lime-400 font-extrabold">#{quizResult.rank}</span>
                  </p>
                </div>
              )}

              <div class="flex flex-col sm:flex-row items-center justify-center gap-3 pt-2">
                <button
                  onClick={() => openPosterModal()}
                  class="w-full sm:w-auto px-8 py-3.5 bg-lime-500 hover:bg-lime-400 text-black font-extrabold text-sm uppercase tracking-wider rounded-xl transition-all shadow-xl shadow-lime-500/20 cursor-pointer flex items-center justify-center space-x-2 transform hover:scale-105"
                >
                  <i data-lucide="share-2" class="w-4 h-4"></i>
                  <span>🎨 View & Share Score Poster</span>
                </button>
              </div>
              {shareSuccessMessage && (
                <p class="text-xs text-lime-400 font-semibold">{shareSuccessMessage}</p>
              )}
            </div>
          </div>
        ) : null}
      </section>

      {/* SECTION 3: FAN LEADERBOARD & SOCIAL SHARE */}
      <section class="bg-zinc-900/90 rounded-2xl p-6 sm:p-8 border border-zinc-800/80 shadow-xl relative">
        <div class="flex flex-col sm:flex-row sm:items-center justify-between border-b border-zinc-800 pb-4 mb-6 gap-3">
          <div class="flex items-center space-x-3">
            <div class="p-2.5 bg-lime-500/10 border border-lime-500/20 rounded-xl text-lime-400">
              <i data-lucide="trophy" class="w-6 h-6"></i>
            </div>
            <div>
              <div class="flex items-center gap-2.5 flex-wrap">
                <h2 class="display-font text-xl sm:text-2xl font-bold text-white">Fan Leaderboard</h2>
                <span class={`text-xs font-mono font-bold px-2.5 py-0.5 rounded-full uppercase tracking-wide border ${
                  isPortalClosed
                    ? 'bg-amber-500/15 text-amber-300 border-amber-500/30'
                    : 'bg-lime-500/15 text-lime-400 border-lime-500/30'
                }`}>
                  {isPortalClosed ? '🔒 Locked Final Standings (8:00 PM Cutoff)' : 'Top 5 Standings'}
                </span>
              </div>
              <p class="text-xs sm:text-sm text-zinc-400 mt-0.5">Top 5 Standings of Team FZ39 daily quiz champions</p>
            </div>
          </div>

          {/* Social Share Card Trigger Buttons */}
          <div class="flex flex-wrap items-center gap-2">
            <button
              onClick={() => openPosterModal()}
              class="px-3 py-1.5 bg-lime-500 text-black font-extrabold text-xs rounded-lg shadow-md hover:bg-lime-400 transition-colors flex items-center space-x-1.5 cursor-pointer"
            >
              <span>🎨 Graphic Poster</span>
            </button>
            <a
              href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(portalUrl)}`}
              target="_blank"
              rel="noopener noreferrer"
              class="px-2.5 py-1.5 bg-zinc-800 hover:bg-zinc-700 text-zinc-200 text-xs font-bold rounded-lg border border-zinc-700 transition-colors flex items-center space-x-1"
            >
              <span>𝕏 Share</span>
            </a>
            <a
              href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(portalUrl)}&quote=${encodeURIComponent(shareText)}`}
              target="_blank"
              rel="noopener noreferrer"
              class="px-2.5 py-1.5 bg-blue-600/20 hover:bg-blue-600/30 text-blue-400 text-xs font-bold rounded-lg border border-blue-500/30 transition-colors flex items-center space-x-1"
            >
              <span>📘 Facebook</span>
            </a>
            <button
              onClick={() => {
                openPosterModal();
              }}
              class="px-2.5 py-1.5 bg-pink-600/20 hover:bg-pink-600/30 text-pink-400 text-xs font-bold rounded-lg border border-pink-500/30 transition-colors flex items-center space-x-1 cursor-pointer"
            >
              <span>📸 Instagram</span>
            </button>
            <a
              href={`https://api.whatsapp.com/send?text=${encodeURIComponent(shareText + ' ' + portalUrl)}`}
              target="_blank"
              rel="noopener noreferrer"
              class="px-2.5 py-1.5 bg-emerald-600/20 hover:bg-emerald-600/30 text-emerald-400 text-xs font-bold rounded-lg border border-emerald-500/30 transition-colors flex items-center space-x-1"
            >
              <span>💬 WhatsApp</span>
            </a>
          </div>
        </div>

        {leaderboardLoading ? (
          <div class="space-y-3 animate-pulse">
            <div class="h-10 bg-zinc-950/60 rounded-xl border border-zinc-800"></div>
            <div class="space-y-2">
              {[1, 2, 3, 4, 5].map((n) => (
                <div key={n} class="h-12 bg-zinc-850/40 rounded-lg flex items-center justify-between px-4 border border-zinc-800/40">
                  <div class="flex items-center space-x-3 w-1/3">
                    <div class="h-6 w-12 bg-zinc-800 rounded"></div>
                    <div class="h-5 w-28 bg-zinc-800 rounded"></div>
                  </div>
                  <div class="h-5 w-16 bg-zinc-800 rounded"></div>
                  <div class="h-5 w-12 bg-zinc-800 rounded"></div>
                  <div class="h-5 w-20 bg-zinc-800 rounded hidden sm:block"></div>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div class="space-y-4">
            {/* User's Own Standing Card (shown when quiz is completed and user is outside Top 5) */}
            {(() => {
              const cleanUserHandle = (userIdentity?.userHandle || quizResult?.userHandle || '').trim().toLowerCase();
              const top5 = leaderboard.slice(0, 5);
              const isUserInTop5 = cleanUserHandle && top5.some(item => (item.userHandle || '').trim().toLowerCase() === cleanUserHandle);
              const userRank = quizResult?.rank || posterData?.rank;

              if (quizCompleted && quizResult && !isUserInTop5) {
                return (
                  <div class="p-4 rounded-xl border border-lime-500/30 bg-zinc-950 flex flex-col sm:flex-row items-center justify-between gap-3 shadow-lg">
                    <div class="flex items-center space-x-3 w-full sm:w-auto">
                      <div class="w-10 h-10 rounded-xl bg-zinc-800 border border-zinc-700 flex items-center justify-center font-black text-sm text-lime-400 font-mono">
                        #{userRank || '—'}
                      </div>
                      <div>
                        <div class="flex items-center space-x-2">
                          <span class="text-xs font-bold text-lime-400 uppercase tracking-wider">Your Standing</span>
                          <span class="text-[10px] text-zinc-400 bg-zinc-800 px-1.5 py-0.5 rounded font-mono">Rank #{userRank || '—'}</span>
                        </div>
                        <p class="text-sm font-bold text-white">
                          {userIdentity?.userName || quizResult.userName || 'You'}{' '}
                          <span class="text-xs text-zinc-400 font-mono font-normal">
                            ({userIdentity?.userHandle || quizResult.userHandle || '@fan'})
                          </span>
                        </p>
                      </div>
                    </div>
                    <div class="flex items-center space-x-4 w-full sm:w-auto justify-between sm:justify-end border-t sm:border-t-0 border-zinc-800 pt-2 sm:pt-0">
                      <div class="text-left sm:text-right">
                        <span class="text-[10px] text-zinc-500 uppercase block font-semibold">Your Score</span>
                        <span class="text-sm font-bold font-mono text-lime-400">
                          {quizResult.score} / {quizResult.totalQuestions || 5}
                        </span>
                      </div>
                      <div class="text-left sm:text-right">
                        <span class="text-[10px] text-zinc-500 uppercase block font-semibold">Time</span>
                        <span class="text-sm font-mono text-zinc-300">{quizResult.timeTakenSeconds}s</span>
                      </div>
                      <button
                        onClick={() => openPosterModal()}
                        class="px-3 py-1.5 bg-lime-500 hover:bg-lime-400 text-black text-xs font-black rounded-lg cursor-pointer transition-colors shadow"
                      >
                        Poster
                      </button>
                    </div>
                  </div>
                );
              }
              return null;
            })()}

            {leaderboard.length > 0 ? (
              <div class="overflow-x-auto">
                <div class="flex items-center justify-between px-1 mb-2 text-xs text-zinc-400 font-semibold uppercase tracking-wider">
                  <span class="flex items-center space-x-1.5">
                    <span class="text-lime-400">🏆</span>
                    <span class="text-white font-bold">Top 5 Standings</span>
                  </span>
                  <span class="text-zinc-500 text-[11px] font-mono">Live Rankings</span>
                </div>
                <table class="w-full text-left border-collapse">
                  <thead>
                    <tr class="border-b border-zinc-800 text-xs uppercase tracking-wider text-zinc-400 font-semibold bg-zinc-950/50">
                      <th class="py-3 px-4">Rank</th>
                      <th class="py-3 px-4">Fan Name & Social</th>
                      <th class="py-3 px-4">Score</th>
                      <th class="py-3 px-4">Time</th>
                      <th class="py-3 px-4">Date</th>
                    </tr>
                  </thead>
                  <tbody class="divide-y divide-zinc-800/60 text-sm">
                    {leaderboard.slice(0, 5).map((item, idx) => {
                      const rank = idx + 1;
                      let badgeColor = 'text-zinc-300 bg-zinc-800/80 border border-zinc-700';
                      let badgeText = `#${rank}`;

                      if (rank === 1) {
                        badgeColor = 'bg-amber-400/20 text-amber-300 border border-amber-400/40';
                        badgeText = '🥇 #1';
                      } else if (rank === 2) {
                        badgeColor = 'bg-slate-300/20 text-slate-200 border border-slate-300/40';
                        badgeText = '🥈 #2';
                      } else if (rank === 3) {
                        badgeColor = 'bg-amber-700/20 text-amber-500 border border-amber-600/40';
                        badgeText = '🥉 #3';
                      }

                      const cleanUserHandle = (userIdentity?.userHandle || '').trim().toLowerCase();
                      const isCurrentUser = cleanUserHandle && (item.userHandle || '').trim().toLowerCase() === cleanUserHandle;

                      return (
                        <tr
                          key={item.id || idx}
                          class={`transition-colors ${
                            isCurrentUser
                              ? 'bg-lime-500/10 hover:bg-lime-500/15 border-l-2 border-lime-400'
                              : 'hover:bg-zinc-850/50'
                          }`}
                        >
                          <td class="py-3.5 px-4 font-mono font-bold">
                            <span class={`px-2.5 py-1 rounded-md text-xs font-black display-font ${badgeColor}`}>
                              {badgeText}
                            </span>
                          </td>
                          <td class="py-3.5 px-4">
                            <div class="flex items-center space-x-2">
                              <span class="font-bold text-white">{item.userName}</span>
                              {isCurrentUser && (
                                <span class="bg-lime-500 text-black text-[10px] font-black px-1.5 py-0.2 rounded uppercase">
                                  You
                                </span>
                              )}
                              <span class="text-xs text-lime-400 font-mono bg-zinc-800 px-2 py-0.5 rounded border border-zinc-700">
                                {getPlatformIcon(item.socialPlatform)} {item.userHandle}
                              </span>
                            </div>
                          </td>
                          <td class="py-3.5 px-4 font-mono font-bold text-lime-400">
                            {item.score} / {item.totalQuestions || 5}
                          </td>
                          <td class="py-3.5 px-4 font-mono text-zinc-300 text-xs">
                            {item.timeTakenSeconds}s
                          </td>
                          <td class="py-3.5 px-4 text-xs text-zinc-400 font-mono">
                            {new Date(item.dateCompleted).toLocaleDateString()}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <div class="py-12 text-center text-zinc-400 space-y-2 bg-zinc-950/40 rounded-xl border border-zinc-800/60 p-6">
                <div class="w-12 h-12 bg-zinc-800/60 text-zinc-400 rounded-full flex items-center justify-center mx-auto text-xl">
                  🏆
                </div>
                <h4 class="text-base font-bold text-white display-font">Not uploaded yet</h4>
                <p class="text-xs text-zinc-400 max-w-sm mx-auto">
                  No submissions yet today. Be the first to take the quiz and top the leaderboard!
                </p>
              </div>
            )}
          </div>
        )}
      </section>

      {/* SECTION 4: FAN FEEDBACK SYSTEM */}
      <section class="bg-zinc-900/90 rounded-2xl p-6 sm:p-8 border border-zinc-800/80 shadow-xl relative">
        <div class="flex items-center justify-between border-b border-zinc-800 pb-4 mb-6">
          <div class="flex items-center space-x-3">
            <div class="p-2.5 bg-lime-500/10 border border-lime-500/20 rounded-xl text-lime-400">
              <i data-lucide="message-square" class="w-6 h-6"></i>
            </div>
            <div>
              <h2 class="display-font text-xl sm:text-2xl font-bold text-white">Fan Feedback & Suggestions</h2>
              <p class="text-xs sm:text-sm text-zinc-400">Send your thoughts, match messages, and feedback directly to Team FZ39</p>
            </div>
          </div>
        </div>

        <div class="max-w-2xl mx-auto">
          {/* Submit Feedback Form */}
          <form onSubmit={handleFeedbackSubmit} class="space-y-5 bg-zinc-950 p-6 sm:p-8 rounded-2xl border border-zinc-800 shadow-xl">
            <div class="border-b border-zinc-800/80 pb-3">
              <h3 class="text-base font-bold text-white display-font flex items-center space-x-2">
                <span>Leave Your Message & Feedback</span>
              </h3>
              <p class="text-xs text-zinc-400 mt-0.5">Your comments are delivered straight to the official management team.</p>
            </div>

            {/* Rating selector */}
            <div class="space-y-1.5">
              <label class="text-xs font-semibold text-zinc-300">Overall Rating *</label>
              <div class="flex items-center space-x-2">
                {[1, 2, 3, 4, 5].map((star) => (
                  <button
                    key={star}
                    type="button"
                    onClick={() => setFeedbackRating(star)}
                    class={`text-3xl transition-transform hover:scale-110 cursor-pointer ${
                      star <= feedbackRating ? 'text-lime-400' : 'text-zinc-700'
                    }`}
                  >
                    ★
                  </button>
                ))}
                <span class="text-xs text-lime-400 font-bold ml-2 font-mono">{feedbackRating} / 5 Stars</span>
              </div>
            </div>

            {/* User Identity Info Preview or Inputs */}
            {userIdentity ? (
              <div class="text-xs bg-zinc-900 p-3 rounded-xl border border-zinc-800 text-zinc-300 flex items-center justify-between">
                <span>Posting as: <strong class="text-white">{userIdentity.userName}</strong> ({userIdentity.userHandle} - {userIdentity.socialPlatform})</span>
                <button
                  type="button"
                  onClick={() => setShowIdentityModal(true)}
                  class="text-lime-400 underline hover:text-lime-300 text-xs font-semibold"
                >
                  Change Profile
                </button>
              </div>
            ) : (
              <div class="p-3 bg-zinc-900/80 rounded-xl border border-zinc-800 text-xs text-zinc-400 flex items-center justify-between">
                <span>You can save your profile to display your verified fan handle.</span>
                <button
                  type="button"
                  onClick={() => setShowIdentityModal(true)}
                  class="px-3 py-1 bg-lime-500 text-black font-bold rounded-lg text-xs hover:bg-lime-400"
                >
                  Set Fan Identity
                </button>
              </div>
            )}

            {/* Comment Area */}
            <div class="space-y-1.5">
              <label class="text-xs font-semibold text-zinc-300">Comment / Message for Fakhar Zaman *</label>
              <textarea
                value={feedbackComment}
                onChange={(e) => setFeedbackComment(e.target.value)}
                placeholder="Share your encouragement, match feedback, or suggestions for Fakhar Zaman..."
                rows={4}
                required
                class="w-full bg-zinc-900 border border-zinc-700 rounded-xl p-3.5 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-lime-400"
              ></textarea>
            </div>

            <button
              type="submit"
              disabled={feedbackSubmitting}
              class="w-full py-3.5 bg-lime-500 hover:bg-lime-400 text-black font-extrabold text-sm uppercase tracking-wider rounded-xl transition-all shadow-lg cursor-pointer flex items-center justify-center space-x-2"
            >
              {feedbackSubmitting ? (
                <span>Submitting Feedback...</span>
              ) : (
                <>
                  <i data-lucide="send" class="w-4 h-4"></i>
                  <span>Send Fan Feedback</span>
                </>
              )}
            </button>

            {feedbackSuccess && (
              <p class="text-xs text-center font-bold text-lime-400 bg-lime-500/10 p-3 rounded-xl border border-lime-500/30">
                {feedbackSuccess}
              </p>
            )}
          </form>
        </div>
      </section>

      {/* USER IDENTITY CAPTURE MODAL */}
      {showIdentityModal && (
        <div class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-fade-in">
          <div class="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-md w-full p-6 sm:p-8 shadow-2xl relative space-y-6">
            <button
              onClick={() => setShowIdentityModal(false)}
              class="absolute top-4 right-4 text-zinc-400 hover:text-white text-xl cursor-pointer"
            >
              ✕
            </button>

            <div class="space-y-2">
              <div class="w-10 h-10 rounded-xl bg-lime-500/20 text-lime-400 border border-lime-500/40 flex items-center justify-center font-black">
                🆔
              </div>
              <h3 class="display-font text-xl font-bold text-white">Fan Portal Identity</h3>
              <p class="text-xs text-zinc-400">
                Enter your details to vote, play quizzes, and secure your place on the Team FZ39 Leaderboard!
              </p>
            </div>

            <form onSubmit={handleIdentitySave} class="space-y-4">
              <div class="space-y-1">
                <label class="text-xs font-semibold text-zinc-300">Display Name / Full Name *</label>
                <input
                  type="text"
                  required
                  placeholder="e.g. Fakhar Fan39"
                  value={identityForm.userName}
                  onChange={(e) => setIdentityForm({ ...identityForm, userName: e.target.value })}
                  class="w-full bg-zinc-950 border border-zinc-700 rounded-xl p-3 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-lime-400"
                />
              </div>

              <div class="space-y-1">
                <label class="text-xs font-semibold text-zinc-300">Preferred Social Platform *</label>
                <select
                  value={identityForm.socialPlatform}
                  onChange={(e) => setIdentityForm({ ...identityForm, socialPlatform: e.target.value })}
                  class="w-full bg-zinc-950 border border-zinc-700 rounded-xl p-3 text-sm text-white focus:outline-none focus:border-lime-400"
                >
                  <option value="Twitter/X">Twitter / X</option>
                  <option value="Instagram">Instagram</option>
                  <option value="Facebook">Facebook</option>
                  <option value="TikTok">TikTok</option>
                  <option value="WhatsApp">WhatsApp</option>
                </select>
              </div>

              <div class="space-y-1">
                <label class="text-xs font-semibold text-zinc-300">Social Handle / Username *</label>
                <input
                  type="text"
                  required
                  placeholder="e.g. @fakhar_fan39"
                  value={identityForm.userHandle}
                  onChange={(e) => setIdentityForm({ ...identityForm, userHandle: e.target.value })}
                  class="w-full bg-zinc-950 border border-zinc-700 rounded-xl p-3 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-lime-400"
                />
              </div>

              <div class="pt-2 flex items-center justify-end space-x-3">
                <button
                  type="button"
                  onClick={() => setShowIdentityModal(false)}
                  class="px-4 py-2 bg-zinc-800 text-zinc-300 text-xs font-semibold rounded-xl hover:bg-zinc-700"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  class="px-6 py-2.5 bg-lime-500 hover:bg-lime-400 text-black font-extrabold text-xs uppercase tracking-wider rounded-xl shadow-lg cursor-pointer"
                >
                  Save & Continue
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* GRAPHIC POSTER & SOCIAL SHARE MODAL */}
      {showPosterModal && posterData && (
        <div class="fixed inset-0 bg-black/85 backdrop-blur-md z-50 flex items-center justify-center p-4 animate-fade-in overflow-y-auto">
          <div class="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-xl w-full p-6 sm:p-8 shadow-2xl relative space-y-6 my-8">
            <button
              onClick={() => setShowPosterModal(false)}
              class="absolute top-4 right-4 text-zinc-400 hover:text-white text-2xl font-bold cursor-pointer"
            >
              ✕
            </button>

            <div class="text-center space-y-2">
              <div class="inline-flex items-center space-x-2 bg-lime-500/15 border border-lime-500/30 px-3 py-1 rounded-full text-lime-400 text-xs font-bold uppercase tracking-wider">
                <span>🎨 Visual Score Poster</span>
              </div>
              <h3 class="display-font text-2xl font-black text-white">Your Official FZ39 Achievement Card</h3>
              <p class="text-xs text-zinc-400">
                Share this custom graphic poster on Instagram, Facebook, Twitter/X, or WhatsApp!
              </p>
            </div>

            {/* LIVE POSTER DESIGN CARD PREVIEW */}
            <div class="bg-[#090d16] border-2 border-lime-500/50 rounded-2xl p-6 shadow-2xl relative overflow-hidden space-y-5 text-center">
              {/* Background Radial Glow */}
              <div class="absolute inset-0 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-lime-500/20 via-transparent to-transparent pointer-events-none"></div>

              {/* Header Badge */}
              <div class="relative z-10 space-y-1">
                <p class="text-lime-400 text-[11px] font-extrabold uppercase tracking-widest display-font">
                  ⚡ OFFICIAL FZ39 FAN PORTAL
                </p>
                <h4 class="display-font text-2xl sm:text-3xl font-black text-white tracking-tight">
                  FAKHAR ZAMAN FAN QUIZ
                </h4>
                <div class="w-24 h-1 bg-lime-400 mx-auto rounded-full"></div>
              </div>

              {/* Center Certificate Box */}
              <div class="bg-[#121824] border border-zinc-800 p-5 rounded-xl relative z-10 space-y-4 shadow-xl">
                <div>
                  <p class="text-[10px] text-zinc-400 font-bold uppercase tracking-wider">OFFICIAL PERFORMANCE CERTIFICATE</p>
                  <h5 class="text-xl sm:text-2xl font-black text-white display-font mt-0.5">{posterData.userName}</h5>
                  <p class="text-xs text-lime-400 font-mono mt-0.5">{posterData.socialPlatform}: {posterData.userHandle}</p>
                </div>

                {/* Big Score Display */}
                <div class="bg-lime-500/10 border-2 border-lime-500/40 p-4 rounded-xl">
                  <div class="display-font text-4xl sm:text-5xl font-black text-lime-400 tracking-tight">
                    {posterData.score} / {posterData.totalQuestions || 5}
                  </div>
                  <p class="text-[11px] font-bold text-zinc-300 uppercase tracking-widest mt-1">OFFICIAL QUIZ SCORE</p>
                </div>

                {/* Rank Highlight Badge */}
                <div class="bg-lime-500 text-black py-2.5 px-4 rounded-xl font-black text-lg sm:text-xl display-font shadow-lg">
                  🏆 LEADERBOARD RANK #{posterData.rank || 1}
                </div>

                {/* Time & Accuracy */}
                <div class="flex items-center justify-center space-x-4 text-xs font-mono text-zinc-300">
                  <span>⚡ Time: {posterData.timeTakenSeconds || 10}s</span>
                  <span>|</span>
                  <span>Accuracy: {Math.round(((posterData.score || 0) / (posterData.totalQuestions || 5)) * 100)}%</span>
                </div>

                <div class="text-[11px] text-lime-400 font-bold uppercase tracking-wider pt-1">
                  ✓ VERIFIED FZ39 TRIVIA CHAMPION
                </div>
              </div>

              {/* Footer */}
              <div class="relative z-10 space-y-0.5">
                <p class="text-white font-bold text-sm tracking-wide display-font">www.teamfakharzaman.site/fan-portal</p>
                <p class="text-[10px] text-zinc-400">Join the official fan community & play daily cricket trivia!</p>
              </div>
            </div>

            {/* DOWNLOAD POSTER & DIRECT SOCIAL SHARE OPTIONS */}
            <div class="space-y-3 pt-2">
              <div class="flex flex-col sm:flex-row items-center gap-2">
                <button
                  onClick={() => downloadPosterGraphic(true)}
                  class="w-full sm:w-2/3 py-3.5 bg-lime-500 hover:bg-lime-400 text-black font-extrabold text-xs sm:text-sm uppercase tracking-wider rounded-xl transition-all shadow-xl shadow-lime-500/20 cursor-pointer flex items-center justify-center space-x-2 transform hover:scale-[1.02]"
                >
                  <i data-lucide="download" class="w-4 h-4"></i>
                  <span>📸 Download Poster (PNG)</span>
                </button>
                <button
                  onClick={() => setShowPosterModal(false)}
                  class="w-full sm:w-1/3 py-3.5 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 hover:text-white font-bold text-xs uppercase tracking-wider rounded-xl border border-zinc-700 transition-colors cursor-pointer flex items-center justify-center space-x-1.5"
                >
                  <span>✕ Close Poster</span>
                </button>
              </div>

              <div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
                {/* Twitter / X */}
                <a
                  href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(portalUrl)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  class="p-2.5 bg-zinc-800 hover:bg-zinc-700 text-white text-xs font-bold rounded-xl border border-zinc-700 transition-colors flex items-center justify-center space-x-1.5"
                >
                  <span>𝕏 Share</span>
                </a>

                {/* Facebook */}
                <a
                  href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(portalUrl)}&quote=${encodeURIComponent(shareText)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  class="p-2.5 bg-blue-600/20 hover:bg-blue-600/30 text-blue-400 text-xs font-bold rounded-xl border border-blue-500/30 transition-colors flex items-center justify-center space-x-1.5"
                >
                  <span>📘 Facebook</span>
                </a>

                {/* Instagram */}
                <a
                  href="https://www.instagram.com/"
                  target="_blank"
                  rel="noopener noreferrer"
                  onClick={() => {
                    downloadPosterGraphic(false);
                    navigator.clipboard.writeText(`${shareText} ${portalUrl}`);
                    setShareSuccessMessage('Poster downloaded & caption copied! Ready to post on Instagram!');
                  }}
                  class="p-2.5 bg-pink-600/20 hover:bg-pink-600/30 text-pink-400 text-xs font-bold rounded-xl border border-pink-500/30 transition-colors flex items-center justify-center space-x-1.5"
                >
                  <span>📸 Instagram</span>
                </a>

                {/* WhatsApp */}
                <a
                  href={`https://api.whatsapp.com/send?text=${encodeURIComponent(shareText + ' ' + portalUrl)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  class="p-2.5 bg-emerald-600/20 hover:bg-emerald-600/30 text-emerald-400 text-xs font-bold rounded-xl border border-emerald-500/30 transition-colors flex items-center justify-center space-x-1.5"
                >
                  <span>💬 WhatsApp</span>
                </a>
              </div>

              {shareSuccessMessage && (
                <p class="text-xs text-center font-bold text-lime-400 bg-lime-500/10 p-2 rounded-lg border border-lime-500/30">
                  {shareSuccessMessage}
                </p>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// Mount React Component to DOM
const rootElement = document.getElementById('fan-portal-root');
if (rootElement) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(<FanPortal />);
}
