import { useState, useRef } from "react";

const COLORS = {
  royalBlue: "#1a3a8f", royalBlueLight: "#2451c7", royalBlueDark: "#0f2260",
  gold: "#d4a017", goldLight: "#f0c040", goldDark: "#a07810",
  white: "#ffffff", black: "#0a0a0a", gray: "#1e1e2e",
  grayLight: "#2a2a3e", grayMid: "#3a3a54", textMuted: "#8888aa",
};

// ─── CONTEST DATA ─────────────────────────────────────────────────────────────
const initialContests = [
  { id: 1, type: "testimonial", title: "Best Testimonial Video — Q2 2026", description: "Share your TAG Markets success story in a 2-minute video. Most inspiring story wins!", prize: "₹50,000 + Thailand Trip", deadline: "2026-06-30", status: "active", submissions: 48, coverGradient: "linear-gradient(135deg, #1a3a8f 0%, #2451c7 50%, #d4a017 100%)" },
  { id: 2, type: "success_story", title: "Best Success Story — June", description: "Write your journey from Day 1 to your biggest achievement with TAG Markets.", prize: "₹25,000 Cash + Badge", deadline: "2026-06-25", status: "active", submissions: 31, coverGradient: "linear-gradient(135deg, #0f2260 0%, #1a3a8f 60%, #a07810 100%)" },
  { id: 3, type: "transformation", title: "Best Transformation Story — June", description: "Show your Before & After journey with TAG Markets. Photos + written story required.", prize: "₹30,000 + Platinum Badge", deadline: "2026-06-28", status: "active", submissions: 24, coverGradient: "linear-gradient(135deg, #6b21a8 0%, #1a3a8f 60%, #d4a017 100%)" },
  { id: 4, type: "team_builder", title: "Best Team Builder — June", description: "Auto-ranked by team growth, activity score, and training completion. Keep building!", prize: "₹75,000 + Dubai Trip", deadline: "2026-06-30", status: "active", submissions: 89, coverGradient: "linear-gradient(135deg, #d4a017 0%, #f0c040 40%, #1a3a8f 100%)" },
  { id: 5, type: "social_influencer", title: "Best Social Media Influencer — June", description: "Points based on content posted, engagement, and reach across all platforms.", prize: "₹20,000 + Crown Badge", deadline: "2026-06-30", status: "active", submissions: 55, coverGradient: "linear-gradient(135deg, #e11d48 0%, #1a3a8f 60%, #d4a017 100%)" },
  { id: 6, type: "fastest_qualifier", title: "Fastest Qualifier Contest", description: "Real-time rankings. First to hit qualifier targets wins. Clock is ticking!", prize: "₹40,000 + Special Badge", deadline: "2026-06-30", status: "active", submissions: 112, coverGradient: "linear-gradient(135deg, #047857 0%, #1a3a8f 60%, #d4a017 100%)" },
  { id: 7, type: "top_recruiter", title: "Top Recruiter Contest — June", description: "Most affiliates added this month wins. Rankings update in real-time.", prize: "Dubai Trip + ₹1,00,000", deadline: "2026-06-30", status: "active", submissions: 112, coverGradient: "linear-gradient(135deg, #0f2260 0%, #2451c7 50%, #f0c040 100%)" },
  { id: 8, type: "top_presenter", title: "Top Presenter Contest — June", description: "Most Zoom & one-to-one presentations conducted wins the crown.", prize: "₹30,000 + Crown Badge", deadline: "2026-06-30", status: "active", submissions: 77, coverGradient: "linear-gradient(135deg, #2451c7 0%, #0f2260 60%, #d4a017 100%)" },
];

const leaderboardData = {
  testimonial: [
    { rank: 1, name: "Priya Sharma", city: "Mumbai", score: 9.4, teamVotes: 142, publicVotes: 134, adminScore: 9.2, avatar: "PS", approved: true, winner: false },
    { rank: 2, name: "Rahul Verma", city: "Delhi", score: 8.9, teamVotes: 110, publicVotes: 120, adminScore: 8.7, avatar: "RV", approved: true, winner: false },
    { rank: 3, name: "Anita Patel", city: "Ahmedabad", score: 8.6, teamVotes: 98, publicVotes: 107, adminScore: 8.4, avatar: "AP", approved: true, winner: false },
    { rank: 4, name: "Suresh Kumar", city: "Bangalore", score: 8.1, teamVotes: 80, publicVotes: 90, adminScore: 7.9, avatar: "SK", approved: true, winner: false },
    { rank: 5, name: "Meera Nair", city: "Kochi", score: 7.8, teamVotes: 70, publicVotes: 78, adminScore: 7.6, avatar: "MN", approved: false, winner: false },
  ],
  success_story: [
    { rank: 1, name: "Arjun Singh", city: "Jaipur", score: 9.7, teamVotes: 180, publicVotes: 160, adminScore: 9.5, avatar: "AS", approved: true, winner: false },
    { rank: 2, name: "Kavya Reddy", city: "Hyderabad", score: 9.1, teamVotes: 150, publicVotes: 145, adminScore: 8.9, avatar: "KR", approved: true, winner: false },
    { rank: 3, name: "Deepak Joshi", city: "Pune", score: 8.8, teamVotes: 130, publicVotes: 120, adminScore: 8.6, avatar: "DJ", approved: true, winner: false },
    { rank: 4, name: "Sneha Gupta", city: "Chennai", score: 8.3, teamVotes: 100, publicVotes: 110, adminScore: 8.0, avatar: "SG", approved: true, winner: false },
    { rank: 5, name: "Vijay Malhotra", city: "Lucknow", score: 7.9, teamVotes: 85, publicVotes: 92, adminScore: 7.7, avatar: "VM", approved: false, winner: false },
  ],
  transformation: [
    { rank: 1, name: "Rekha Bose", city: "Kolkata", score: 9.5, teamVotes: 165, publicVotes: 148, adminScore: 9.3, avatar: "RB", approved: true, winner: false },
    { rank: 2, name: "Karan Mehta", city: "Surat", score: 9.0, teamVotes: 140, publicVotes: 132, adminScore: 8.8, avatar: "KM", approved: true, winner: false },
    { rank: 3, name: "Pooja Desai", city: "Vadodara", score: 8.5, teamVotes: 115, publicVotes: 108, adminScore: 8.2, avatar: "PD", approved: true, winner: false },
    { rank: 4, name: "Arun Nair", city: "Trivandrum", score: 8.0, teamVotes: 90, publicVotes: 95, adminScore: 7.8, avatar: "AN", approved: false, winner: false },
    { rank: 5, name: "Sonal Jain", city: "Indore", score: 7.6, teamVotes: 72, publicVotes: 80, adminScore: 7.4, avatar: "SJ", approved: false, winner: false },
  ],
  team_builder: [
    { rank: 1, name: "Rajesh Pandey", city: "Varanasi", avatar: "RP", teamGrowth: 47, activityScore: 980, trainingPct: 95, totalScore: 2210, winner: false, approved: true },
    { rank: 2, name: "Sunita Yadav", city: "Patna", avatar: "SY", teamGrowth: 39, activityScore: 870, trainingPct: 88, totalScore: 1930, winner: false, approved: true },
    { rank: 3, name: "Anil Bhatt", city: "Surat", avatar: "AB", teamGrowth: 34, activityScore: 810, trainingPct: 82, totalScore: 1740, winner: false, approved: true },
    { rank: 4, name: "Pooja Tiwari", city: "Indore", avatar: "PT", teamGrowth: 28, activityScore: 720, trainingPct: 78, totalScore: 1480, winner: false, approved: true },
    { rank: 5, name: "Manoj Saxena", city: "Bhopal", avatar: "MS", teamGrowth: 22, activityScore: 640, trainingPct: 70, totalScore: 1220, winner: false, approved: true },
  ],
  social_influencer: [
    { rank: 1, name: "Nisha Kapoor", city: "Mumbai", avatar: "NK", postsCount: 48, engagement: "12.4%", reach: "1.2L", totalScore: 9420, winner: false, approved: true },
    { rank: 2, name: "Rohan Das", city: "Bangalore", avatar: "RD", postsCount: 41, engagement: "10.8%", reach: "98K", totalScore: 8100, winner: false, approved: true },
    { rank: 3, name: "Preethi Raj", city: "Chennai", avatar: "PR", postsCount: 36, engagement: "9.1%", reach: "74K", totalScore: 6800, winner: false, approved: true },
    { rank: 4, name: "Vikram Rao", city: "Hyderabad", avatar: "VR", postsCount: 30, engagement: "8.4%", reach: "61K", totalScore: 5500, winner: false, approved: true },
    { rank: 5, name: "Asha Singh", city: "Jaipur", avatar: "AS2", postsCount: 24, engagement: "7.2%", reach: "48K", totalScore: 4200, winner: false, approved: true },
  ],
  fastest_qualifier: [
    { rank: 1, name: "Neha Kapoor", city: "Chandigarh", avatar: "NK2", daysToQualify: 4, qualifiedOn: "Jun 2", totalScore: 9800, winner: false, approved: true },
    { rank: 2, name: "Sanjay Dubey", city: "Nagpur", avatar: "SD", daysToQualify: 6, qualifiedOn: "Jun 4", totalScore: 9400, winner: false, approved: true },
    { rank: 3, name: "Rekha Mishra", city: "Agra", avatar: "RM", daysToQualify: 8, qualifiedOn: "Jun 6", totalScore: 8900, winner: false, approved: true },
    { rank: 4, name: "Harish Tomar", city: "Jodhpur", avatar: "HT", daysToQualify: 10, qualifiedOn: "Jun 8", totalScore: 8300, winner: false, approved: true },
    { rank: 5, name: "Usha Chandra", city: "Mysore", avatar: "UC", daysToQualify: 12, qualifiedOn: "Jun 10", totalScore: 7700, winner: false, approved: true },
  ],
  top_recruiter: [
    { rank: 1, name: "Rajesh Pandey", city: "Varanasi", avatar: "RP", affiliates: 47, winner: false, approved: true },
    { rank: 2, name: "Sunita Yadav", city: "Patna", avatar: "SY", affiliates: 39, winner: false, approved: true },
    { rank: 3, name: "Anil Bhatt", city: "Surat", avatar: "AB", affiliates: 34, winner: false, approved: true },
    { rank: 4, name: "Pooja Tiwari", city: "Indore", avatar: "PT", affiliates: 28, winner: false, approved: true },
    { rank: 5, name: "Manoj Saxena", city: "Bhopal", avatar: "MS", affiliates: 22, winner: false, approved: true },
  ],
  top_presenter: [
    { rank: 1, name: "Neha Kapoor", city: "Chandigarh", avatar: "NK", presentations: 89, winner: false, approved: true },
    { rank: 2, name: "Sanjay Dubey", city: "Nagpur", avatar: "SD", presentations: 74, winner: false, approved: true },
    { rank: 3, name: "Rekha Mishra", city: "Agra", avatar: "RM", presentations: 68, winner: false, approved: true },
    { rank: 4, name: "Harish Tomar", city: "Jodhpur", avatar: "HT", presentations: 55, winner: false, approved: true },
    { rank: 5, name: "Usha Chandra", city: "Mysore", avatar: "UC", presentations: 49, winner: false, approved: true },
  ],
};

// Video Testimonial Center entries
const testimonialVideos = [
  { id: 1, name: "Priya Sharma", city: "Mumbai", avatar: "PS", title: "From Housewife to Diamond Leader", duration: "2:14", likes: 342, comments: 28, rating: 4.8, shares: 56, approved: true, views: 1240 },
  { id: 2, name: "Rahul Verma", city: "Delhi", avatar: "RV", title: "₹0 to ₹1.2L/Month in 9 Months", duration: "1:58", likes: 287, comments: 19, rating: 4.6, shares: 41, approved: true, views: 980 },
  { id: 3, name: "Anita Patel", city: "Ahmedabad", avatar: "AP", title: "My TAG Markets Journey — Real Results", duration: "2:31", likes: 251, comments: 15, rating: 4.5, shares: 33, approved: true, views: 840 },
  { id: 4, name: "Suresh Kumar", city: "Bangalore", avatar: "SK", title: "How I Built a Team of 200+", duration: "2:02", likes: 198, comments: 12, rating: 4.3, shares: 27, approved: false, views: 0 },
];

const typeConfig = {
  testimonial:       { label: "Testimonial Video",      icon: "🎬", color: "#2451c7",  autoRanked: false },
  success_story:     { label: "Success Story",          icon: "✍️",  color: "#1a3a8f",  autoRanked: false },
  transformation:    { label: "Transformation Story",   icon: "🔄", color: "#6b21a8",  autoRanked: false },
  team_builder:      { label: "Best Team Builder",      icon: "🏗️",  color: "#d4a017",  autoRanked: true  },
  social_influencer: { label: "Social Media Influencer",icon: "📱", color: "#e11d48",  autoRanked: true  },
  fastest_qualifier: { label: "Fastest Qualifier",      icon: "⚡", color: "#047857",  autoRanked: true  },
  top_recruiter:     { label: "Top Recruiter",          icon: "🏆", color: "#d4a017",  autoRanked: true  },
  top_presenter:     { label: "Top Presenter",          icon: "🎤", color: "#2451c7",  autoRanked: true  },
};

const rankColors  = ["#d4a017","#9e9e9e","#cd7f32","#8888aa","#8888aa"];
const rankIcons   = ["👑","🥈","🥉","",""];
const PERIODS     = ["daily","weekly","monthly","quarterly"];

// ─── SHARED UI COMPONENTS ────────────────────────────────────────────────────

function GlowButton({ children, onClick, variant="primary", style={}, small=false }) {
  return (
    <button onClick={onClick} style={{
      padding: small ? "7px 14px" : "12px 28px", borderRadius: 10,
      border: variant==="outline" ? `1.5px solid ${COLORS.gold}` : "none",
      background: variant==="primary" ? `linear-gradient(135deg,${COLORS.gold},${COLORS.goldLight})`
                : variant==="blue"    ? `linear-gradient(135deg,${COLORS.royalBlue},${COLORS.royalBlueLight})`
                : variant==="danger"  ? `linear-gradient(135deg,#dc2626,#ef4444)`
                : variant==="green"   ? `linear-gradient(135deg,#047857,#10b981)`
                : "transparent",
      color: (variant==="outline") ? COLORS.gold : COLORS.black,
      fontWeight:700, fontSize: small?12:14, cursor:"pointer",
      fontFamily:"inherit", letterSpacing:"0.5px",
      boxShadow: variant==="primary"?"0 4px 24px #d4a01755":variant==="blue"?"0 4px 24px #2451c755":variant==="danger"?"0 4px 16px #dc262655":variant==="green"?"0 4px 16px #04785755":"none",
      transition:"all 0.2s", ...style,
    }}>{children}</button>
  );
}

function Avatar({ initials, size=44, rank }) {
  const bg = rank ? rankColors[rank-1] : COLORS.royalBlue;
  return (
    <div style={{ width:size,height:size,borderRadius:"50%",
      background:`linear-gradient(135deg,${bg},${bg}88)`,
      display:"flex",alignItems:"center",justifyContent:"center",
      color:COLORS.white,fontWeight:800,fontSize:size*0.35,
      border:`2px solid ${bg}55`,flexShrink:0,fontFamily:"inherit",
    }}>{initials}</div>
  );
}

function StarRating({ value, onChange, size=16 }) {
  const [hover, setHover] = useState(0);
  return (
    <div style={{ display:"flex", gap:2 }}>
      {[1,2,3,4,5].map(s => (
        <span key={s}
          onClick={()=>onChange&&onChange(s)}
          onMouseEnter={()=>onChange&&setHover(s)}
          onMouseLeave={()=>onChange&&setHover(0)}
          style={{ fontSize:size, cursor:onChange?"pointer":"default",
            color:(hover||value)>=s ? COLORS.gold : "#444466", transition:"color 0.15s" }}>★</span>
      ))}
    </div>
  );
}

function ApprovalBadge({ approved }) {
  return (
    <span style={{
      fontSize:10, fontWeight:700, padding:"3px 8px", borderRadius:20,
      background: approved ? "#04785720" : "#dc262620",
      color: approved ? "#10b981" : "#ef4444",
      border: `1px solid ${approved ? "#04785760" : "#dc262660"}`,
    }}>
      {approved ? "✓ Approved" : "⏳ Pending"}
    </span>
  );
}

function WinnerBadge() {
  return (
    <span style={{
      fontSize:10, fontWeight:800, padding:"4px 10px", borderRadius:20,
      background:"linear-gradient(135deg,#d4a017,#f0c040)",
      color:COLORS.black, letterSpacing:0.5,
    }}>👑 WINNER</span>
  );
}

// ─── LEADERBOARD ROW ────────────────────────────────────────────────────────

function LeaderboardRow({ entry, type, isAdmin, onSelectWinner }) {
  const isTop3 = entry.rank <= 3;
  const isAutoRanked = typeConfig[type]?.autoRanked;

  const subLabel = () => {
    if (type==="team_builder")      return `${entry.teamGrowth} members · Score ${entry.totalScore}`;
    if (type==="social_influencer") return `${entry.postsCount} posts · ${entry.engagement} eng · ${entry.reach} reach`;
    if (type==="fastest_qualifier") return `Qualified in ${entry.daysToQualify} days (${entry.qualifiedOn})`;
    if (type==="top_recruiter")     return `${entry.affiliates} affiliates`;
    if (type==="top_presenter")     return `${entry.presentations} presentations`;
    if (entry.score)                return `Score ${entry.score}`;
    return "";
  };

  const voteBreakdown = (!isAutoRanked && entry.teamVotes) ? (
    <div style={{ display:"flex", gap:8, fontSize:10, color:COLORS.textMuted, marginTop:2 }}>
      <span>👥 Team {entry.teamVotes}</span>
      <span>🌍 Public {entry.publicVotes}</span>
      <span>⭐ Admin {entry.adminScore}</span>
    </div>
  ) : null;

  return (
    <div style={{
      display:"flex", alignItems:"flex-start", gap:12, padding:"14px 16px",
      background: entry.winner ? `linear-gradient(90deg,${COLORS.gold}18,transparent)` :
                  isTop3 ? `linear-gradient(90deg,${rankColors[entry.rank-1]}12,transparent)` : "transparent",
      borderRadius:12,
      borderLeft: entry.winner ? `3px solid ${COLORS.gold}` :
                  isTop3 ? `3px solid ${rankColors[entry.rank-1]}` : "3px solid transparent",
      marginBottom:6, transition:"background 0.2s",
    }}>
      <div style={{ width:28, textAlign:"center", fontWeight:900,
        fontSize: isTop3?18:14, color: rankColors[entry.rank-1]||COLORS.textMuted, paddingTop:2 }}>
        {rankIcons[entry.rank-1]||entry.rank}
      </div>
      <Avatar initials={entry.avatar} size={40} rank={isTop3?entry.rank:null} />
      <div style={{ flex:1 }}>
        <div style={{ display:"flex", alignItems:"center", gap:8, flexWrap:"wrap" }}>
          <span style={{ color:COLORS.white, fontWeight:700, fontSize:14 }}>{entry.name}</span>
          {entry.winner && <WinnerBadge />}
          {!isAutoRanked && <ApprovalBadge approved={entry.approved} />}
        </div>
        <div style={{ color:COLORS.textMuted, fontSize:11 }}>{entry.city}</div>
        <div style={{ color:COLORS.textMuted, fontSize:11, marginTop:2 }}>{subLabel()}</div>
        {voteBreakdown}
      </div>
      {isAdmin && !entry.winner && (
        <GlowButton variant="green" small onClick={()=>onSelectWinner(entry.rank)}>
          🏆 Select Winner
        </GlowButton>
      )}
    </div>
  );
}

// ─── SUBMISSION MODAL ────────────────────────────────────────────────────────

function SubmissionModal({ contest, onClose }) {
  const [form, setForm]       = useState({ title:"", description:"", videoFile:"", imageFile:"", beforeFile:"", afterFile:"" });
  const [rating, setRating]   = useState(0);
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const videoRef = useRef(); const imgRef = useRef();
  const beforeRef = useRef(); const afterRef = useRef();
  if (!contest) return null;
  const cfg = typeConfig[contest.type];
  const isAuto = cfg?.autoRanked;

  const handleSubmit = () => {
    setLoading(true);
    setTimeout(()=>{ setLoading(false); setSubmitted(true); }, 1800);
  };

  return (
    <div style={{ position:"fixed",inset:0,background:"#00000088",zIndex:1000,
      display:"flex",alignItems:"center",justifyContent:"center",
      backdropFilter:"blur(6px)",padding:16 }}
      onClick={e=>e.target===e.currentTarget&&onClose()}>
      <div style={{ background:COLORS.gray,borderRadius:22,width:"100%",maxWidth:520,
        border:`1px solid ${COLORS.gold}33`,boxShadow:`0 20px 80px #00000088`,
        maxHeight:"90vh",overflowY:"auto" }}>
        {/* Header */}
        <div style={{ padding:"24px 28px 16px",borderBottom:`1px solid #ffffff11`,
          display:"flex",justifyContent:"space-between",alignItems:"flex-start" }}>
          <div>
            <div style={{ fontSize:11,color:COLORS.gold,fontWeight:700,letterSpacing:2,marginBottom:4 }}>
              {cfg.icon} SUBMIT ENTRY
            </div>
            <div style={{ fontSize:17,color:COLORS.white,fontWeight:800 }}>{contest.title}</div>
          </div>
          <button onClick={onClose} style={{ background:"none",border:"none",color:COLORS.textMuted,cursor:"pointer",fontSize:22 }}>✕</button>
        </div>

        <div style={{ padding:"24px 28px" }}>
          {submitted ? (
            <div style={{ textAlign:"center",padding:"32px 0" }}>
              <div style={{ fontSize:60,marginBottom:16 }}>🎉</div>
              <div style={{ color:COLORS.gold,fontWeight:800,fontSize:22,marginBottom:8 }}>Entry Submitted!</div>
              <div style={{ color:COLORS.textMuted,fontSize:13,marginBottom:6 }}>Your submission is pending admin approval.</div>
              <div style={{ color:COLORS.textMuted,fontSize:12,marginBottom:24 }}>You'll be notified once it's live on the leaderboard.</div>
              <GlowButton onClick={onClose}>Close</GlowButton>
            </div>
          ) : isAuto ? (
            <div style={{ textAlign:"center",padding:"24px 0" }}>
              <div style={{ fontSize:48,marginBottom:16 }}>{cfg.icon}</div>
              <div style={{ color:COLORS.white,fontWeight:700,fontSize:16,marginBottom:8 }}>Auto-Tracked Contest</div>
              <div style={{ color:COLORS.textMuted,fontSize:13,marginBottom:24,lineHeight:1.6 }}>
                {contest.type==="team_builder" && "Rankings auto-calculated from: Team Growth, Activity Score, and Training Completion %."}
                {contest.type==="social_influencer" && "Points auto-tracked from: Content Posted, Engagement Rate, and Platform Reach."}
                {contest.type==="fastest_qualifier" && "Rankings update in real-time as members hit qualifier targets. Keep logging your daily activity!"}
                {contest.type==="top_recruiter" && "Ranked by total affiliates added this month from your daily reports."}
                {contest.type==="top_presenter" && "Ranked by total presentations conducted this month from your daily activity tracker."}
              </div>
              <div style={{ background:COLORS.grayLight,borderRadius:12,padding:"16px 20px",marginBottom:24,textAlign:"left" }}>
                <div style={{ fontSize:11,color:COLORS.textMuted,marginBottom:4 }}>YOUR CURRENT RANKING</div>
                <div style={{ color:COLORS.gold,fontWeight:900,fontSize:24 }}>#14</div>
                <div style={{ color:COLORS.textMuted,fontSize:12,marginTop:2 }}>Keep going — top 3 wins!</div>
              </div>
              <GlowButton onClick={onClose}>View Leaderboard</GlowButton>
            </div>
          ) : (
            <>
              {/* Title */}
              <FieldInput label="TITLE" value={form.title}
                onChange={v=>setForm(f=>({...f,title:v}))}
                placeholder={contest.type==="testimonial"?"E.g., My Journey to Diamond Leader":
                             contest.type==="transformation"?"E.g., 6 Months — Before & After":"E.g., From Zero to ₹1L/month"} />
              {/* Description / Story */}
              <FieldTextarea label={contest.type==="success_story"?"FULL STORY":"DESCRIPTION"}
                value={form.description} onChange={v=>setForm(f=>({...f,description:v}))}
                placeholder={contest.type==="success_story"?"Write your complete journey here — be specific and inspiring...":
                             contest.type==="transformation"?"Describe your transformation in detail. What changed? How did TAG Markets help?":"Brief description..."} rows={contest.type==="success_story"?8:4} />

              {/* Video Upload for testimonial */}
              {contest.type==="testimonial" && (
                <UploadBox ref={videoRef} label="UPLOAD VIDEO (MP4, MOV — max 500MB)"
                  icon="📹" value={form.videoFile}
                  onPick={()=>videoRef.current.click()}
                  accept="video/*"
                  onFile={name=>setForm(f=>({...f,videoFile:name}))} />
              )}

              {/* Before / After Images for transformation */}
              {contest.type==="transformation" && (
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12, marginBottom:18 }}>
                  <UploadBox ref={beforeRef} label="BEFORE PHOTO" icon="📷" value={form.beforeFile}
                    onPick={()=>beforeRef.current.click()} accept="image/*"
                    onFile={name=>setForm(f=>({...f,beforeFile:name}))} compact />
                  <UploadBox ref={afterRef} label="AFTER PHOTO" icon="🌟" value={form.afterFile}
                    onPick={()=>afterRef.current.click()} accept="image/*"
                    onFile={name=>setForm(f=>({...f,afterFile:name}))} compact />
                </div>
              )}

              {/* Optional image for success story */}
              {contest.type==="success_story" && (
                <UploadBox ref={imgRef} label="UPLOAD PHOTO (Optional)" icon="🖼️" value={form.imageFile}
                  onPick={()=>imgRef.current.click()} accept="image/*"
                  onFile={name=>setForm(f=>({...f,imageFile:name}))} />
              )}

              {/* Customer Rating (testimonial) */}
              {contest.type==="testimonial" && (
                <div style={{ marginBottom:18 }}>
                  <label style={{ display:"block",color:COLORS.textMuted,fontSize:12,fontWeight:700,marginBottom:8 }}>YOUR RATING FOR THIS EXPERIENCE</label>
                  <StarRating value={rating} onChange={setRating} size={28} />
                </div>
              )}

              <GlowButton onClick={handleSubmit} style={{ width:"100%",padding:"14px",fontSize:15 }}>
                {loading ? "Submitting..." : "🚀 Submit My Entry"}
              </GlowButton>
              <div style={{ textAlign:"center",color:COLORS.textMuted,fontSize:11,marginTop:10 }}>
                Submissions are reviewed by admin before going live on the leaderboard
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function FieldInput({ label, value, onChange, placeholder }) {
  return (
    <div style={{ marginBottom:16 }}>
      <label style={{ display:"block",color:COLORS.textMuted,fontSize:12,fontWeight:700,marginBottom:6 }}>{label}</label>
      <input value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
        style={{ width:"100%",background:COLORS.grayLight,border:`1px solid #ffffff22`,
          borderRadius:10,padding:"12px 16px",color:COLORS.white,fontSize:14,
          fontFamily:"inherit",boxSizing:"border-box",outline:"none" }} />
    </div>
  );
}

function FieldTextarea({ label, value, onChange, placeholder, rows=4 }) {
  return (
    <div style={{ marginBottom:16 }}>
      <label style={{ display:"block",color:COLORS.textMuted,fontSize:12,fontWeight:700,marginBottom:6 }}>{label}</label>
      <textarea value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} rows={rows}
        style={{ width:"100%",background:COLORS.grayLight,border:`1px solid #ffffff22`,
          borderRadius:10,padding:"12px 16px",color:COLORS.white,fontSize:14,
          fontFamily:"inherit",resize:"vertical",boxSizing:"border-box",outline:"none" }} />
    </div>
  );
}

function UploadBox({ label, icon, value, onPick, accept, onFile, compact=false }, ref) {
  return (
    <div style={{ marginBottom:compact?0:18 }}>
      <label style={{ display:"block",color:COLORS.textMuted,fontSize:12,fontWeight:700,marginBottom:6 }}>{label}</label>
      <div onClick={onPick}
        style={{ border:`2px dashed ${value?COLORS.gold:"#ffffff33"}`,borderRadius:12,
          padding: compact?"16px 10px":"24px 20px",textAlign:"center",cursor:"pointer",
          background:value?`${COLORS.gold}11`:"transparent",transition:"all 0.2s" }}>
        <div style={{ fontSize:compact?24:32,marginBottom:4 }}>{value?"✅":icon}</div>
        <div style={{ color:value?COLORS.gold:COLORS.textMuted,fontSize:compact?11:13,fontWeight:600 }}>
          {value||(compact?label:"Click to upload")}
        </div>
        <input ref={ref} type="file" accept={accept} style={{ display:"none" }}
          onChange={e=>e.target.files[0]&&onFile(e.target.files[0].name)} />
      </div>
    </div>
  );
}
const UploadBoxFwd = UploadBox; // simplified — in real Next.js use forwardRef

// ─── VIDEO TESTIMONIAL CENTER ────────────────────────────────────────────────

function VideoTestimonialCenter({ isAdmin }) {
  const [videoLikes, setVideoLikes]       = useState({});
  const [videoRatings, setVideoRatings]   = useState({});
  const [approvals, setApprovals]         = useState(
    Object.fromEntries(testimonialVideos.map(v=>[v.id,v.approved]))
  );
  const [comments, setComments]           = useState({});
  const [commentInput, setCommentInput]   = useState({});

  const toggleLike  = id => setVideoLikes(l=>({...l,[id]:!l[id]}));
  const setRating   = (id,r) => setVideoRatings(rv=>({...rv,[id]:r}));
  const toggleApproval = id => setApprovals(a=>({...a,[id]:!a[id]}));

  const addComment = id => {
    if (!commentInput[id]?.trim()) return;
    setComments(c=>({...c,[id]:[...(c[id]||[]),{ text:commentInput[id], user:"You", time:"Just now" }]}));
    setCommentInput(ci=>({...ci,[id]:""}));
  };

  return (
    <div>
      <div style={{ fontSize:11,color:COLORS.textMuted,fontWeight:700,letterSpacing:1.5,marginBottom:16 }}>
        🎬 VIDEO TESTIMONIAL CENTER
      </div>
      {isAdmin && (
        <div style={{ background:`${COLORS.gold}15`,border:`1px solid ${COLORS.gold}33`,borderRadius:12,
          padding:"12px 16px",marginBottom:20,fontSize:12,color:COLORS.gold,fontWeight:700 }}>
          👑 Admin Mode — You can approve/reject submissions below
        </div>
      )}
      {testimonialVideos.map(v=>(
        <div key={v.id} style={{ background:COLORS.grayLight,borderRadius:16,marginBottom:16,
          border:`1px solid ${approvals[v.id]?"#04785720":"#dc262620"}`,overflow:"hidden" }}>
          {/* Video Thumb */}
          <div style={{ height:150,background:`linear-gradient(135deg,${COLORS.royalBlueDark},${COLORS.grayMid})`,
            display:"flex",alignItems:"center",justifyContent:"center",position:"relative",cursor:"pointer" }}>
            <div style={{ textAlign:"center" }}>
              <div style={{ fontSize:44 }}>▶️</div>
              <div style={{ color:COLORS.textMuted,fontSize:11 }}>{v.duration}</div>
            </div>
            <div style={{ position:"absolute",top:10,right:10 }}>
              <ApprovalBadge approved={approvals[v.id]} />
            </div>
            <div style={{ position:"absolute",bottom:10,left:10,background:"#00000066",
              borderRadius:8,padding:"3px 10px",fontSize:11,color:COLORS.white }}>
              👁 {approvals[v.id] ? `${v.views} views` : "Pending"}
            </div>
          </div>
          <div style={{ padding:"14px 16px" }}>
            {/* Header */}
            <div style={{ display:"flex",alignItems:"center",gap:10,marginBottom:10 }}>
              <Avatar initials={v.avatar} size={36} />
              <div>
                <div style={{ color:COLORS.white,fontWeight:700,fontSize:13 }}>{v.name}</div>
                <div style={{ color:COLORS.textMuted,fontSize:11 }}>{v.city}</div>
              </div>
            </div>
            <div style={{ color:COLORS.white,fontWeight:700,fontSize:14,marginBottom:8 }}>{v.title}</div>
            {/* Rating */}
            <div style={{ display:"flex",alignItems:"center",gap:8,marginBottom:12 }}>
              <StarRating value={videoRatings[v.id]||v.rating} onChange={r=>setRating(v.id,r)} size={16} />
              <span style={{ color:COLORS.gold,fontWeight:700,fontSize:13 }}>{videoRatings[v.id]||v.rating}</span>
              <span style={{ color:COLORS.textMuted,fontSize:11 }}>({v.likes} ratings)</span>
            </div>
            {/* Actions */}
            <div style={{ display:"flex",gap:8,flexWrap:"wrap",marginBottom:12 }}>
              <ActionBtn active={videoLikes[v.id]} onClick={()=>toggleLike(v.id)}
                label={`${videoLikes[v.id]?"❤️":"🤍"} ${v.likes+(videoLikes[v.id]?1:0)}`} />
              <ActionBtn label={`💬 ${v.comments}`} />
              <ActionBtn label={`📤 ${v.shares}`} />
              {isAdmin && (
                <ActionBtn onClick={()=>toggleApproval(v.id)}
                  label={approvals[v.id]?"🚫 Reject":"✅ Approve"}
                  active={approvals[v.id]} color={approvals[v.id]?"#dc2626":COLORS.gold} />
              )}
            </div>
            {/* Comments */}
            {(comments[v.id]||[]).map((c,i)=>(
              <div key={i} style={{ background:COLORS.gray,borderRadius:8,padding:"8px 12px",marginBottom:6,fontSize:12,color:COLORS.textMuted }}>
                <span style={{ color:COLORS.white,fontWeight:700 }}>{c.user}: </span>{c.text}
                <span style={{ float:"right",fontSize:10 }}>{c.time}</span>
              </div>
            ))}
            <div style={{ display:"flex",gap:8,marginTop:8 }}>
              <input value={commentInput[v.id]||""} onChange={e=>setCommentInput(ci=>({...ci,[v.id]:e.target.value}))}
                placeholder="Write a comment..." onKeyDown={e=>e.key==="Enter"&&addComment(v.id)}
                style={{ flex:1,background:COLORS.gray,border:`1px solid #ffffff22`,borderRadius:8,
                  padding:"8px 12px",color:COLORS.white,fontSize:12,fontFamily:"inherit",outline:"none" }} />
              <button onClick={()=>addComment(v.id)} style={{ background:COLORS.royalBlue,border:"none",
                borderRadius:8,padding:"8px 14px",color:COLORS.white,fontWeight:700,cursor:"pointer",fontSize:12,fontFamily:"inherit" }}>
                Send
              </button>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ActionBtn({ label, onClick, active, color }) {
  return (
    <button onClick={onClick} style={{ background: active?`${color||COLORS.gold}22`:"transparent",
      border:`1.5px solid ${active?(color||COLORS.gold):"#ffffff22"}`,
      color: active?(color||COLORS.gold):COLORS.textMuted,
      borderRadius:8,padding:"6px 12px",cursor:"pointer",fontWeight:700,fontSize:12,
      fontFamily:"inherit",transition:"all 0.2s" }}>
      {label}
    </button>
  );
}

// ─── CONTEST CARD ────────────────────────────────────────────────────────────

function ContestCard({ contest, onClick }) {
  const cfg = typeConfig[contest.type];
  const daysLeft = Math.ceil((new Date(contest.deadline)-new Date())/86400000);
  return (
    <div onClick={()=>onClick(contest)}
      style={{ background:COLORS.grayLight,borderRadius:18,overflow:"hidden",cursor:"pointer",
        border:`1px solid #ffffff11`,transition:"transform 0.2s,box-shadow 0.2s",
        boxShadow:"0 4px 24px #00000033" }}
      onMouseEnter={e=>{ e.currentTarget.style.transform="translateY(-4px)"; e.currentTarget.style.boxShadow="0 12px 40px #00000055"; }}
      onMouseLeave={e=>{ e.currentTarget.style.transform="translateY(0)"; e.currentTarget.style.boxShadow="0 4px 24px #00000033"; }}>
      <div style={{ height:100,background:contest.coverGradient,position:"relative",
        display:"flex",alignItems:"center",justifyContent:"center" }}>
        <span style={{ fontSize:38 }}>{cfg.icon}</span>
        <div style={{ position:"absolute",top:10,right:10,
          background:daysLeft<=5?"#e53e3e":COLORS.royalBlueDark,
          color:COLORS.white,fontSize:10,fontWeight:700,padding:"3px 8px",borderRadius:20 }}>
          {daysLeft}d left
        </div>
        {cfg.autoRanked && (
          <div style={{ position:"absolute",bottom:8,left:8,background:"#00000066",
            color:COLORS.goldLight,fontSize:9,fontWeight:700,padding:"3px 8px",borderRadius:20 }}>
            AUTO-RANKED
          </div>
        )}
      </div>
      <div style={{ padding:"14px 16px" }}>
        <div style={{ fontSize:9,color:COLORS.textMuted,fontWeight:700,letterSpacing:1.5,marginBottom:4 }}>{cfg.label.toUpperCase()}</div>
        <div style={{ fontWeight:800,fontSize:13,color:COLORS.white,marginBottom:6,lineHeight:1.3 }}>{contest.title}</div>
        <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between" }}>
          <div style={{ fontSize:12,color:COLORS.gold,fontWeight:800 }}>{contest.prize}</div>
          <div style={{ fontSize:13,color:COLORS.white,fontWeight:800 }}>{contest.submissions}</div>
        </div>
      </div>
    </div>
  );
}

// ─── ADMIN CREATE CONTEST ────────────────────────────────────────────────────

function AdminCreateContest({ onClose }) {
  const [form, setForm] = useState({ title:"",type:"testimonial",prize:"",deadline:"",description:"" });
  const [done, setDone] = useState(false);

  return (
    <div style={{ position:"fixed",inset:0,background:"#00000088",zIndex:1000,
      display:"flex",alignItems:"center",justifyContent:"center",
      backdropFilter:"blur(6px)",padding:16 }}
      onClick={e=>e.target===e.currentTarget&&onClose()}>
      <div style={{ background:COLORS.gray,borderRadius:22,width:"100%",maxWidth:520,
        border:`1px solid ${COLORS.gold}33`,boxShadow:`0 20px 80px #00000088`,
        maxHeight:"90vh",overflowY:"auto" }}>
        <div style={{ padding:"24px 28px 16px",borderBottom:`1px solid #ffffff11`,
          display:"flex",justifyContent:"space-between",alignItems:"center" }}>
          <div>
            <div style={{ fontSize:11,color:COLORS.gold,fontWeight:700,letterSpacing:2,marginBottom:4 }}>ADMIN</div>
            <div style={{ fontSize:18,color:COLORS.white,fontWeight:800 }}>Create New Contest</div>
          </div>
          <button onClick={onClose} style={{ background:"none",border:"none",color:COLORS.textMuted,cursor:"pointer",fontSize:22 }}>✕</button>
        </div>
        <div style={{ padding:"24px 28px" }}>
          {done ? (
            <div style={{ textAlign:"center",padding:"24px 0" }}>
              <div style={{ fontSize:56,marginBottom:12 }}>✅</div>
              <div style={{ color:COLORS.gold,fontWeight:800,fontSize:20,marginBottom:8 }}>Contest Created!</div>
              <div style={{ color:COLORS.textMuted,fontSize:13,marginBottom:20 }}>All members will be notified immediately.</div>
              <GlowButton onClick={onClose}>Done</GlowButton>
            </div>
          ) : (
            <>
              <FieldInput label="CONTEST TITLE" value={form.title} onChange={v=>setForm(f=>({...f,title:v}))} placeholder="E.g., Best Testimonial — July 2026" />
              <FieldInput label="PRIZE" value={form.prize} onChange={v=>setForm(f=>({...f,prize:v}))} placeholder="E.g., ₹50,000 + Thailand Trip" />
              <div style={{ marginBottom:16 }}>
                <label style={{ display:"block",color:COLORS.textMuted,fontSize:12,fontWeight:700,marginBottom:6 }}>DEADLINE</label>
                <input type="date" value={form.deadline} onChange={e=>setForm(f=>({...f,deadline:e.target.value}))}
                  style={{ width:"100%",background:COLORS.grayLight,border:`1px solid #ffffff22`,borderRadius:10,
                    padding:"12px 16px",color:COLORS.white,fontSize:14,fontFamily:"inherit",outline:"none",colorScheme:"dark" }} />
              </div>
              <div style={{ marginBottom:16 }}>
                <label style={{ display:"block",color:COLORS.textMuted,fontSize:12,fontWeight:700,marginBottom:6 }}>CONTEST TYPE</label>
                <select value={form.type} onChange={e=>setForm(f=>({...f,type:e.target.value}))}
                  style={{ width:"100%",background:COLORS.grayLight,border:`1px solid #ffffff22`,borderRadius:10,
                    padding:"12px 16px",color:COLORS.white,fontSize:14,fontFamily:"inherit",outline:"none",colorScheme:"dark" }}>
                  {Object.entries(typeConfig).map(([k,v])=>(
                    <option key={k} value={k}>{v.icon} {v.label}</option>
                  ))}
                </select>
              </div>
              <FieldTextarea label="DESCRIPTION" value={form.description}
                onChange={v=>setForm(f=>({...f,description:v}))}
                placeholder="Describe the contest, rules, and eligibility..." rows={4} />
              <GlowButton onClick={()=>setTimeout(()=>setDone(true),800)}
                style={{ width:"100%",padding:"14px",fontSize:15 }}>
                🚀 Launch Contest
              </GlowButton>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── CONTEST DETAIL VIEW ─────────────────────────────────────────────────────

function ContestDetailView({ contest, isAdmin }) {
  const [showSubmit, setShowSubmit] = useState(false);
  const [activeTab, setActiveTab]   = useState("leaderboard");
  const [lbPeriod, setLbPeriod]     = useState("weekly");
  const [entries, setEntries]       = useState(leaderboardData[contest.type] || []);
  const [votes, setVotes]           = useState({});

  const cfg = typeConfig[contest.type];
  const daysLeft = Math.ceil((new Date(contest.deadline)-new Date())/86400000);

  const handleVote = id => setVotes(v=>({...v,[id]:!v[id]}));

  const handleSelectWinner = rank => {
    setEntries(e=>e.map(en=>({...en, winner: en.rank===rank})));
  };

  const tabs = [
    { id:"leaderboard", label:"Leaderboard" },
    { id:"submissions", label:"Submissions" },
    { id:"videos",      label:"📹 Videos", show: contest.type==="testimonial" },
    { id:"info",        label:"Info" },
  ].filter(t=>t.show!==false);

  return (
    <div>
      {/* Hero Banner */}
      <div style={{ borderRadius:20,overflow:"hidden",marginBottom:24,
        background:contest.coverGradient,position:"relative",minHeight:170,
        display:"flex",alignItems:"flex-end" }}>
        <div style={{ position:"absolute",inset:0,background:"linear-gradient(to top,#00000099,transparent)" }} />
        <div style={{ position:"relative",padding:"20px 24px",width:"100%",boxSizing:"border-box" }}>
          <div style={{ fontSize:10,color:COLORS.goldLight,fontWeight:700,letterSpacing:2,marginBottom:4 }}>
            {cfg.icon} {cfg.label.toUpperCase()} {cfg.autoRanked&&"· AUTO-RANKED"}
          </div>
          <div style={{ fontSize:20,fontWeight:900,color:COLORS.white,marginBottom:6 }}>{contest.title}</div>
          <div style={{ display:"flex",gap:16,flexWrap:"wrap" }}>
            <span style={{ fontSize:13,color:COLORS.goldLight,fontWeight:700 }}>🏆 {contest.prize}</span>
            <span style={{ fontSize:13,color:"#ffffff88" }}>⏳ {daysLeft} days left</span>
            <span style={{ fontSize:13,color:"#ffffff88" }}>👥 {contest.submissions} entries</span>
          </div>
        </div>
      </div>

      {/* Action Row */}
      <div style={{ display:"flex",gap:10,marginBottom:20 }}>
        <GlowButton onClick={()=>setShowSubmit(true)} style={{ flex:1 }}>✍️ Submit Entry</GlowButton>
        <GlowButton variant="blue" style={{ flex:1 }}>📤 Share</GlowButton>
        {isAdmin && <GlowButton variant="outline" style={{ flex:1 }} onClick={()=>{}}>⚙️ Manage</GlowButton>}
      </div>

      {/* Period Filter (leaderboard tab only) */}
      {activeTab==="leaderboard" && (
        <div style={{ display:"flex",gap:4,overflowX:"auto",paddingBottom:4,marginBottom:16 }}>
          {PERIODS.map(p=>(
            <button key={p} onClick={()=>setLbPeriod(p)} style={{
              background:lbPeriod===p?COLORS.royalBlue:"transparent",
              border:`1px solid ${lbPeriod===p?COLORS.royalBlueLight:"#ffffff22"}`,
              color:lbPeriod===p?COLORS.white:COLORS.textMuted,
              borderRadius:20,padding:"7px 14px",cursor:"pointer",
              fontWeight:700,fontSize:11,fontFamily:"inherit",
              whiteSpace:"nowrap",flexShrink:0,textTransform:"capitalize",
            }}>{p}</button>
          ))}
        </div>
      )}

      {/* Tabs */}
      <div style={{ display:"flex",gap:4,background:COLORS.grayLight,borderRadius:12,padding:4,marginBottom:20 }}>
        {tabs.map(t=>(
          <button key={t.id} onClick={()=>setActiveTab(t.id)} style={{
            flex:1,padding:"9px 4px",borderRadius:9,border:"none",
            background:activeTab===t.id?COLORS.royalBlue:"transparent",
            color:activeTab===t.id?COLORS.white:COLORS.textMuted,
            fontWeight:700,fontSize:11,cursor:"pointer",fontFamily:"inherit",transition:"all 0.2s",
          }}>{t.label}</button>
        ))}
      </div>

      {/* ── LEADERBOARD TAB ── */}
      {activeTab==="leaderboard" && (
        <div style={{ background:COLORS.grayLight,borderRadius:16,padding:"18px 12px" }}>
          <div style={{ fontSize:12,color:COLORS.textMuted,fontWeight:700,marginBottom:4,letterSpacing:1 }}>
            LIVE RANKINGS · {lbPeriod.toUpperCase()}
          </div>
          {!cfg.autoRanked && (
            <div style={{ fontSize:11,color:COLORS.textMuted,marginBottom:14 }}>
              Score = Team Votes (40%) + Public Votes (40%) + Admin Score (20%)
            </div>
          )}
          {entries.map((e,i)=>(
            <LeaderboardRow key={i} entry={e} type={contest.type}
              isAdmin={isAdmin} onSelectWinner={handleSelectWinner} />
          ))}
          {isAdmin && entries.some(e=>e.winner) && (
            <div style={{ margin:"16px 0 0",background:`${COLORS.gold}15`,
              border:`1px solid ${COLORS.gold}33`,borderRadius:12,padding:"12px 16px",
              fontSize:12,color:COLORS.gold,fontWeight:700,textAlign:"center" }}>
              🏆 Winner selected! Announcement will go to all members.
            </div>
          )}
        </div>
      )}

      {/* ── SUBMISSIONS TAB ── */}
      {activeTab==="submissions" && (
        <div>
          {entries.filter(e=>e.approved!==undefined).map((e,i)=>(
            <div key={i} style={{ background:COLORS.grayLight,borderRadius:16,padding:"18px 20px",
              marginBottom:12,border:`1px solid #ffffff11` }}>
              <div style={{ display:"flex",alignItems:"center",gap:12,marginBottom:12 }}>
                <Avatar initials={e.avatar} size={40} />
                <div style={{ flex:1 }}>
                  <div style={{ display:"flex",alignItems:"center",gap:8,flexWrap:"wrap" }}>
                    <span style={{ color:COLORS.white,fontWeight:700,fontSize:14 }}>{e.name}</span>
                    {e.winner && <WinnerBadge />}
                    <ApprovalBadge approved={e.approved} />
                  </div>
                  <div style={{ color:COLORS.textMuted,fontSize:11 }}>{e.city}</div>
                </div>
                {e.rank<=3&&<span style={{ fontSize:20 }}>{rankIcons[e.rank-1]}</span>}
              </div>

              {/* Transformation Before/After */}
              {contest.type==="transformation" && (
                <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:12 }}>
                  {["BEFORE","AFTER"].map(label=>(
                    <div key={label} style={{ background:COLORS.gray,borderRadius:10,
                      height:100,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:4 }}>
                      <span style={{ fontSize:20 }}>{label==="BEFORE"?"📷":"🌟"}</span>
                      <span style={{ fontSize:10,color:COLORS.textMuted,fontWeight:700 }}>{label} PHOTO</span>
                    </div>
                  ))}
                </div>
              )}

              {/* Video placeholder for testimonial */}
              {contest.type==="testimonial" && (
                <div style={{ background:COLORS.gray,borderRadius:12,height:120,
                  display:"flex",alignItems:"center",justifyContent:"center",
                  marginBottom:12,border:`1px solid #ffffff11`,cursor:"pointer" }}>
                  <div style={{ textAlign:"center" }}>
                    <div style={{ fontSize:36,marginBottom:4 }}>▶️</div>
                    <div style={{ color:COLORS.textMuted,fontSize:12 }}>Testimonial Video</div>
                  </div>
                </div>
              )}

              {/* Success story excerpt */}
              {contest.type==="success_story" && (
                <div style={{ background:COLORS.gray,borderRadius:10,padding:"12px 14px",
                  marginBottom:12,fontSize:12,color:COLORS.textMuted,lineHeight:1.7,fontStyle:"italic" }}>
                  "Started with zero knowledge. TAG Markets gave me the system, the training, and the community to build a life-changing income..."
                </div>
              )}

              {/* Voting Breakdown */}
              {!cfg.autoRanked && (
                <div style={{ background:COLORS.gray,borderRadius:10,padding:"10px 14px",marginBottom:12 }}>
                  <div style={{ fontSize:10,color:COLORS.textMuted,fontWeight:700,marginBottom:8 }}>VOTE BREAKDOWN</div>
                  <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,textAlign:"center" }}>
                    {[
                      { label:"Team Votes", val:e.teamVotes, icon:"👥" },
                      { label:"Public Votes", val:e.publicVotes, icon:"🌍" },
                      { label:"Admin Score", val:e.adminScore, icon:"⭐" },
                    ].map(item=>(
                      <div key={item.label} style={{ background:COLORS.grayLight,borderRadius:8,padding:"8px 4px" }}>
                        <div style={{ fontSize:14 }}>{item.icon}</div>
                        <div style={{ color:COLORS.white,fontWeight:800,fontSize:14 }}>{item.val}</div>
                        <div style={{ color:COLORS.textMuted,fontSize:9,fontWeight:600 }}>{item.label}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Rating */}
              <div style={{ display:"flex",alignItems:"center",gap:8,marginBottom:12 }}>
                <StarRating value={e.score?Math.round(e.score):4} size={16} />
                {e.score&&<span style={{ color:COLORS.gold,fontWeight:800,fontSize:13 }}>{e.score}</span>}
              </div>

              {/* Actions */}
              <div style={{ display:"flex",gap:8,flexWrap:"wrap" }}>
                <ActionBtn active={votes[e.rank]} onClick={()=>handleVote(e.rank)}
                  label={`${votes[e.rank]?"❤️":"👍"} ${votes[e.rank]?"Voted!":"Vote"}`} color={COLORS.gold} />
                <ActionBtn label="💬 Comment" />
                <ActionBtn label="📤 Share" />
                {isAdmin && !e.winner && (
                  <ActionBtn onClick={()=>handleSelectWinner(e.rank)} label="🏆 Select Winner" color="#10b981" active={false} />
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ── VIDEOS TAB (Testimonial only) ── */}
      {activeTab==="videos" && (
        <VideoTestimonialCenter isAdmin={isAdmin} />
      )}

      {/* ── INFO TAB ── */}
      {activeTab==="info" && (
        <div style={{ background:COLORS.grayLight,borderRadius:16,padding:"24px 20px" }}>
          <div style={{ marginBottom:20 }}>
            <div style={{ fontSize:11,color:COLORS.gold,fontWeight:700,letterSpacing:2,marginBottom:8 }}>ABOUT THIS CONTEST</div>
            <div style={{ color:COLORS.textMuted,fontSize:13,lineHeight:1.7 }}>{contest.description}</div>
          </div>
          {[
            { label:"Prize",          value: contest.prize },
            { label:"Deadline",       value: new Date(contest.deadline).toLocaleDateString("en-IN",{day:"numeric",month:"long",year:"numeric"}) },
            { label:"Contest Type",   value: cfg.label },
            { label:"Ranking Method", value: cfg.autoRanked ? "Auto-calculated from daily activity" : "Team Votes + Public Votes + Admin Score" },
            { label:"Status",         value: "🟢 Active — Accepting Entries" },
            { label:"Admin Approval", value: cfg.autoRanked ? "Not required (auto-ranked)" : "Required before entries go live" },
          ].map((item,i,arr)=>(
            <div key={i} style={{ display:"flex",justifyContent:"space-between",alignItems:"flex-start",
              padding:"13px 0",borderBottom:i<arr.length-1?`1px solid #ffffff0f`:"none",gap:12 }}>
              <span style={{ color:COLORS.textMuted,fontSize:13,flexShrink:0 }}>{item.label}</span>
              <span style={{ color:COLORS.white,fontWeight:700,fontSize:13,textAlign:"right" }}>{item.value}</span>
            </div>
          ))}

          {/* Judging Criteria */}
          <div style={{ marginTop:20,background:`${COLORS.gold}15`,
            border:`1px solid ${COLORS.gold}33`,borderRadius:12,padding:"16px 18px" }}>
            <div style={{ fontSize:11,color:COLORS.gold,fontWeight:700,marginBottom:10 }}>JUDGING CRITERIA</div>
            {cfg.autoRanked ? (
              <ul style={{ margin:0,paddingLeft:18,color:COLORS.textMuted,fontSize:13,lineHeight:2 }}>
                {contest.type==="team_builder"&&<>
                  <li>Team Growth — 40%</li><li>Activity Score — 35%</li><li>Training Completion — 25%</li>
                </>}
                {contest.type==="social_influencer"&&<>
                  <li>Content Posted — 30%</li><li>Engagement Rate — 40%</li><li>Reach / Impressions — 30%</li>
                </>}
                {contest.type==="fastest_qualifier"&&<>
                  <li>Days to reach qualifier target</li><li>Verified from activity logs in real-time</li>
                </>}
                {(contest.type==="top_recruiter"||contest.type==="top_presenter")&&<>
                  <li>Auto-calculated from daily reports</li><li>Verified by system data only</li>
                </>}
              </ul>
            ) : (
              <ul style={{ margin:0,paddingLeft:18,color:COLORS.textMuted,fontSize:13,lineHeight:2 }}>
                <li>Team Votes — 40%</li>
                <li>Public Votes — 40%</li>
                <li>Admin Score — 20%</li>
              </ul>
            )}
          </div>
        </div>
      )}

      {showSubmit && <SubmissionModal contest={contest} onClose={()=>setShowSubmit(false)} />}
    </div>
  );
}

// ─── MAIN APP ────────────────────────────────────────────────────────────────

export default function TagMarketsContest() {
  const [activeContest, setActiveContest] = useState(null);
  const [showCreate, setShowCreate]       = useState(false);
  const [filter, setFilter]               = useState("all");
  const [lbPeriod, setLbPeriod]           = useState("weekly");
  const [isAdmin, setIsAdmin]             = useState(false);
  const [activeSection, setActiveSection] = useState("contests"); // contests | testimonials

  const filtered = filter==="all" ? initialContests : initialContests.filter(c=>c.type===filter);

  const globalLeaders = [
    { rank:1, name:"Arjun Singh",    city:"Jaipur",     avatar:"AS",  points:4820 },
    { rank:2, name:"Priya Sharma",   city:"Mumbai",     avatar:"PS",  points:4301 },
    { rank:3, name:"Rajesh Pandey",  city:"Varanasi",   avatar:"RP",  points:3988 },
    { rank:4, name:"Neha Kapoor",    city:"Chandigarh", avatar:"NK",  points:3412 },
    { rank:5, name:"Kavya Reddy",    city:"Hyderabad",  avatar:"KR",  points:3201 },
  ];

  const filterTypes = [
    ["all","All"],
    ["testimonial","🎬 Video"],
    ["success_story","✍️ Story"],
    ["transformation","🔄 Transform"],
    ["team_builder","🏗️ Team Builder"],
    ["social_influencer","📱 Influencer"],
    ["fastest_qualifier","⚡ Qualifier"],
    ["top_recruiter","🏆 Recruiter"],
    ["top_presenter","🎤 Presenter"],
  ];

  return (
    <div style={{ minHeight:"100vh",background:COLORS.black,
      fontFamily:"'Segoe UI','SF Pro Display',system-ui,sans-serif",color:COLORS.white,position:"relative" }}>
      {/* BG gradient */}
      <div style={{ position:"fixed",inset:0,pointerEvents:"none",zIndex:0,
        background:`radial-gradient(ellipse at 20% 10%,${COLORS.royalBlue}22 0%,transparent 60%),
          radial-gradient(ellipse at 80% 80%,${COLORS.gold}11 0%,transparent 50%)` }} />

      <div style={{ position:"relative",zIndex:1,maxWidth:480,margin:"0 auto",padding:"0 0 90px" }}>

        {/* ── HEADER ── */}
        <div style={{ padding:"22px 16px 14px",
          background:`linear-gradient(180deg,${COLORS.royalBlueDark} 0%,${COLORS.black}00 100%)` }}>
          <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between" }}>
            <div style={{ display:"flex",alignItems:"center",gap:8 }}>
              {activeContest && (
                <button onClick={()=>setActiveContest(null)} style={{
                  background:"none",border:"none",color:COLORS.gold,fontSize:22,cursor:"pointer",padding:0,lineHeight:1 }}>←</button>
              )}
              <div>
                <div style={{ fontSize:10,color:COLORS.gold,fontWeight:700,letterSpacing:3 }}>TAG MARKETS</div>
                <div style={{ fontSize:20,fontWeight:900,color:COLORS.white,lineHeight:1.1 }}>
                  {activeContest ? activeContest.title.split("—")[0].trim() : "Contest Arena"}
                </div>
              </div>
            </div>
            <div style={{ display:"flex",gap:8,alignItems:"center" }}>
              {/* Admin Toggle (demo) */}
              <button onClick={()=>setIsAdmin(a=>!a)} style={{
                background:isAdmin?`${COLORS.gold}22`:"transparent",
                border:`1px solid ${isAdmin?COLORS.gold:"#ffffff33"}`,
                color:isAdmin?COLORS.gold:COLORS.textMuted,
                borderRadius:8,padding:"6px 10px",cursor:"pointer",
                fontSize:11,fontWeight:700,fontFamily:"inherit" }}>
                {isAdmin?"👑 Admin":"👤 Member"}
              </button>
              <button onClick={()=>setShowCreate(true)} style={{
                background:`linear-gradient(135deg,${COLORS.gold},${COLORS.goldLight})`,
                border:"none",borderRadius:10,padding:"8px 14px",
                color:COLORS.black,fontWeight:800,fontSize:12,cursor:"pointer",fontFamily:"inherit" }}>
                + Create
              </button>
            </div>
          </div>
        </div>

        <div style={{ padding:"0 14px" }}>
          {/* ── CONTEST LIST VIEW ── */}
          {!activeContest && (
            <>
              {/* Stats */}
              <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10,marginBottom:22 }}>
                {[
                  { label:"Active",    value:"8",      icon:"🏆" },
                  { label:"Entries",   value:"548",    icon:"📝" },
                  { label:"Prize Pool",value:"₹3.7L",  icon:"💰" },
                ].map((s,i)=>(
                  <div key={i} style={{ background:COLORS.grayLight,borderRadius:14,padding:"13px 10px",textAlign:"center",border:`1px solid #ffffff0a` }}>
                    <div style={{ fontSize:20 }}>{s.icon}</div>
                    <div style={{ fontSize:17,fontWeight:900,color:COLORS.gold }}>{s.value}</div>
                    <div style={{ fontSize:9,color:COLORS.textMuted,fontWeight:600 }}>{s.label}</div>
                  </div>
                ))}
              </div>

              {/* Section switcher */}
              <div style={{ display:"flex",gap:4,background:COLORS.grayLight,borderRadius:12,padding:4,marginBottom:20 }}>
                {[["contests","🏆 Contests"],["testimonials","🎬 Testimonials"]].map(([k,v])=>(
                  <button key={k} onClick={()=>setActiveSection(k)} style={{
                    flex:1,padding:"9px 4px",borderRadius:9,border:"none",
                    background:activeSection===k?COLORS.royalBlue:"transparent",
                    color:activeSection===k?COLORS.white:COLORS.textMuted,
                    fontWeight:700,fontSize:13,cursor:"pointer",fontFamily:"inherit" }}>{v}</button>
                ))}
              </div>

              {activeSection==="contests" && (
                <>
                  {/* Global Leaderboard */}
                  <div style={{ marginBottom:24 }}>
                    <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:12 }}>
                      <div style={{ fontSize:14,color:COLORS.white,fontWeight:800 }}>🌍 Global Leaderboard</div>
                      <div style={{ display:"flex",gap:4 }}>
                        {PERIODS.map(p=>(
                          <button key={p} onClick={()=>setLbPeriod(p)} style={{
                            background:lbPeriod===p?COLORS.royalBlue:"transparent",
                            border:`1px solid ${lbPeriod===p?COLORS.royalBlueLight:"#ffffff22"}`,
                            color:lbPeriod===p?COLORS.white:COLORS.textMuted,
                            borderRadius:8,padding:"4px 10px",cursor:"pointer",
                            fontSize:10,fontWeight:700,fontFamily:"inherit",textTransform:"capitalize" }}>{p}</button>
                        ))}
                      </div>
                    </div>
                    <div style={{ background:COLORS.grayLight,borderRadius:16,padding:"12px 10px" }}>
                      {globalLeaders.map((l,i)=>(
                        <div key={i} style={{ display:"flex",alignItems:"center",gap:12,padding:"10px 6px",
                          borderBottom:i<4?`1px solid #ffffff08`:"none" }}>
                          <span style={{ fontSize:l.rank<=3?18:13,width:28,textAlign:"center",
                            color:rankColors[l.rank-1],fontWeight:900 }}>
                            {rankIcons[l.rank-1]||l.rank}
                          </span>
                          <Avatar initials={l.avatar} size={34} rank={l.rank<=3?l.rank:null} />
                          <div style={{ flex:1 }}>
                            <div style={{ fontSize:13,color:COLORS.white,fontWeight:700 }}>{l.name}</div>
                            <div style={{ fontSize:11,color:COLORS.textMuted }}>{l.city}</div>
                          </div>
                          <div style={{ fontSize:13,color:COLORS.gold,fontWeight:800 }}>{l.points.toLocaleString()}</div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Filter Bar */}
                  <div style={{ display:"flex",gap:8,overflowX:"auto",paddingBottom:6,marginBottom:16 }}>
                    {filterTypes.map(([k,v])=>(
                      <button key={k} onClick={()=>setFilter(k)} style={{
                        background:filter===k?COLORS.royalBlue:COLORS.grayLight,
                        border:filter===k?`1px solid ${COLORS.royalBlueLight}`:`1px solid #ffffff11`,
                        color:filter===k?COLORS.white:COLORS.textMuted,
                        borderRadius:20,padding:"7px 14px",cursor:"pointer",
                        fontWeight:700,fontSize:11,fontFamily:"inherit",
                        whiteSpace:"nowrap",flexShrink:0 }}>{v}</button>
                    ))}
                  </div>

                  {/* Contest Cards Grid */}
                  <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:12 }}>
                    {filtered.map(c=><ContestCard key={c.id} contest={c} onClick={setActiveContest} />)}
                  </div>
                </>
              )}

              {/* Testimonial Center Section */}
              {activeSection==="testimonials" && (
                <VideoTestimonialCenter isAdmin={isAdmin} />
              )}
            </>
          )}

          {/* ── CONTEST DETAIL VIEW ── */}
          {activeContest && (
            <ContestDetailView contest={activeContest} isAdmin={isAdmin} />
          )}
        </div>
      </div>

      {showCreate && <AdminCreateContest onClose={()=>setShowCreate(false)} />}

      {/* Bottom Nav */}
      <div style={{ position:"fixed",bottom:0,left:0,right:0,
        background:`${COLORS.gray}ee`,backdropFilter:"blur(20px)",
        borderTop:`1px solid #ffffff11`,padding:"10px 0",
        display:"flex",justifyContent:"space-around",maxWidth:480,margin:"0 auto" }}>
        {[
          { icon:"🏠",label:"Home" },
          { icon:"🏆",label:"Contests",active:true },
          { icon:"📊",label:"Reports" },
          { icon:"👤",label:"Profile" },
        ].map((n,i)=>(
          <button key={i} style={{ background:"none",border:"none",cursor:"pointer",
            display:"flex",flexDirection:"column",alignItems:"center",gap:4,
            color:n.active?COLORS.gold:COLORS.textMuted,fontFamily:"inherit" }}>
            <span style={{ fontSize:20 }}>{n.icon}</span>
            <span style={{ fontSize:10,fontWeight:700,letterSpacing:0.5 }}>{n.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}
