/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  Calendar,
  MapPin,
  Building2,
  Users,
  PlusCircle,
  CheckCircle2,
  AlertCircle,
  ChevronRight,
  ShieldCheck,
  X,
  Split,
  Layers,
  ArrowRight,
  Globe,
  Briefcase,
  FileText,
  Heart,
  Wallet,
  Zap,
  Ticket,
  ChevronDown,
  AlertTriangle,
  FileSpreadsheet
} from 'lucide-react';
/* eslint-enable @typescript-eslint/no-unused-vars */
import { useAuth } from '../../context/AuthContext';
import { cn } from '../../lib/utils';
import { API_BASE_URL } from '../../lib/config';
import { INSTITUTIONAL_EVENTS } from '../../constants/institutionalEvents';
import { getCurrentAcademicYear } from '../../lib/dateUtils';

const eventTypes = ['Workshop', 'Seminar', 'Conference', 'Guest Lecture', 'Industrial Visit', 'Techfest', 'Cultural Event', 'Other'];
const ritDepartments = ['AI&DS', 'AI&ML', 'CSE', 'CCE', 'CSBS', 'ECE', 'MECH', 'EE(VLSI)', 'BIOTECH', 'Placement Department', 'H&S Dept'];
const rsbDepartments = ['PGDM'];
const amenitiesList = [
  'Sound System', 'Projector', 'Wi-Fi', 'Refreshments', 'Photography',
  'Stage Decor', 'Mementos', 'Certificates', 'Mike/PA System', 'White Board',
  'Lunch', 'Breakfast', 'Guest Transport', 'Remuneration', 'Bouquet',
  'LED Screen', 'Flower decoration', 'Computer lab', 'Board Room',
  'Guest Hospitality', 'Transportation for Guest'
];

const CENTRE_MAPPING: Record<string, string[]> = {
  'CSE': ['AI Centre', 'Apple iOS App Development Centre', 'Cyber Security Centre'],
  'AI&DS': ['AR, VR & MR Centre', 'Cloud Computing', 'ZF Data Analytics [COE]'],
  'CCE': ['Data Analytics Centre', 'Space Tech Centre'],
  'ECE': ['Centre for IoT', 'RADAR', 'Centre for Image Processing', 'Quantum Computing'],
  'MECH': ['Electric Vehicle & Energy', 'Advanced Manufacturing Centre', 'Robotics and Drone Tech'],
  'Placement Department': ['Placement Cell', 'Incubation cell']
};

interface ClassMapping {
  id: number;
  institution: string;
  department: string;
  academicYear: string;
  sections: string[];
}

interface Event {
  id: number;
  title: string;
  type: string;
  status: string;
  department: string;
  academicYears: string[];
  targetedSections: string[];
  openToAll?: boolean;
}

interface EventProposalFormProps {
  initialData?: {
    department?: string;
    eventType?: string;
    academicYears?: string[];
    startDate?: string;
    isClubEvent?: boolean;
    eventName?: string;
    id?: number;
    isEditMode?: boolean;
    endDate?: string;
    category?: string;
    institution?: string;
    venue?: string;
    guestName?: string;
    socialProfile?: string;
    requirements?: string[];
    targetedSections?: string[];
    budget?: string | number;
    hasRegistrationFee?: boolean;
    registrationFee?: string | number;
    paymentLink?: string;
    targetDepartments?: string[];
    description?: string;
    sponsors?: string[];
    centreName?: string;
    isPublicEvent?: boolean;
    image?: string;
    status?: string;
  } | null;
}

export const EventProposalForm: React.FC<EventProposalFormProps> = ({ initialData }) => {
  const { user } = useAuth();
  const isClubVariant = initialData?.isClubEvent || false;
  const isFaculty = user?.role === 'FACULTY';
  const isPlacementCell = user?.isPlacementStaff || user?.role === 'PLACEMENT' || user?.department === 'Placement Department';

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState('');
  const [classes, setClasses] = useState<ClassMapping[]>([]);
  const [existingEvents, setExistingEvents] = useState<Event[]>([]);
  const [classStrengths, setClassStrengths] = useState<any[]>([]);

  const fileInputRef = useRef<HTMLInputElement>(null);

  const [venues, setVenues] = useState<{ name: string, capacity: number | null }[]>([
    { name: 'N/A', capacity: null },
    { name: 'Others.', capacity: null }
  ]);

  useEffect(() => {
    const fetchVenues = async () => {
      try {
        const res = await fetch(API_BASE_URL + '/api/venues');
        if (res.ok) {
          const list = await res.json();
          const formatted = list.map((v: any) => ({ name: v.name, capacity: v.capacity }));
          setVenues([
            { name: 'N/A', capacity: null },
            ...formatted,
            { name: 'Others.', capacity: null }
          ]);
        }
      } catch (err) {
        console.error('Failed to fetch venues:', err);
      }
    };
    fetchVenues();
  }, []);

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        const img = new window.Image();
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const max_width = 800;
          let width = img.width;
          let height = img.height;

          if (width > max_width) {
            height = Math.round((height * max_width) / width);
            width = max_width;
          }

          canvas.width = width;
          canvas.height = height;
          const ctx = canvas.getContext('2d');
          if (ctx) {
            ctx.drawImage(img, 0, 0, width, height);
            const compressedBase64 = canvas.toDataURL('image/jpeg', 0.7);
            setFormData(prev => ({ ...prev, image: compressedBase64 }));
          } else {
            setFormData(prev => ({ ...prev, image: reader.result as string }));
          }
        };
        img.src = reader.result as string;
      };
      reader.readAsDataURL(file);
    }
  };

  const getInitialScope = () => {
    if (initialData?.category) {
      if (['TECHNICAL', 'NON-TECHNICAL', 'WORKSHOP', 'ACADEMIC'].includes(initialData.category)) {
        return 'DEPARTMENT';
      }
      if (initialData.category === 'CENTRE-ACTIVITY') {
        return 'CENTRE';
      }
      return initialData.category as any;
    }
    return initialData?.isClubEvent ? 'INSTITUTIONAL' : (isPlacementCell ? 'PLACEMENT' : 'DEPARTMENT');
  };

  const [eventScope, setEventScope] = useState<'INSTITUTIONAL' | 'DEPARTMENT' | 'CLUB' | 'PLACEMENT' | 'CENTRE'>(
    getInitialScope()
  );
  const [conflictData, setConflictData] = useState<{ message: string, conflicts: any[], canOverride: boolean } | null>(null);

  const currentAcademicYear = getCurrentAcademicYear();

  // Filter institutional events that haven't been approved/completed this year
  const availableInstitutionalEvents = INSTITUTIONAL_EVENTS.filter(ie => {
    return !existingEvents.some(e =>
      e.title.toLowerCase() === ie.name.toLowerCase() &&
      (e.status?.toUpperCase() === 'APPROVED' || e.status?.toUpperCase() === 'COMPLETED') &&
      e.academicYears?.includes(currentAcademicYear)
    );
  });

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const parseDateForInput = (dateStr?: string) => {
    if (!dateStr) return '';
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '';
      const yyyy = date.getFullYear();
      const mm = String(date.getMonth() + 1).padStart(2, '0');
      const dd = String(date.getDate()).padStart(2, '0');
      return `${yyyy}-${mm}-${dd}`;
    } catch {
      return '';
    }
  };

  const formatDateTimeForInput = (dateStr?: string) => {
    if (!dateStr) return '';
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '';
      const offset = date.getTimezoneOffset();
      const localDate = new Date(date.getTime() - offset * 60 * 1000);
      return localDate.toISOString().substring(0, 16);
    } catch {
      return '';
    }
  };

  const deptLimits = {};
  const deptSectionLimits = {};

  const [formData, setFormData] = useState({
    eventName: initialData?.eventName || '',
    startDate: initialData?.startDate ? formatDateTimeForInput(initialData.startDate) : '',
    endDate: initialData?.endDate ? formatDateTimeForInput(initialData.endDate) : '',
    eventType: initialData?.eventType || (isClubVariant ? 'CLUB' : 'Guest Lecture'),
    category: initialData?.category || (isClubVariant ? 'CLUB' : 'TECHNICAL'),
    institution: initialData?.institution || 'RIT',
    department: initialData?.department || (isFaculty ? (user?.department || 'CSE') : 'CSE'),
    academicYears: initialData?.academicYears || [] as string[],
    venue: initialData?.venue || 'N/A',
    customVenue: '',
    guestName: initialData?.guestName || '',
    socialProfile: initialData?.socialProfile || '',
    requirements: initialData?.requirements || [] as string[],
    targetedSections: initialData?.targetedSections || [] as string[],
    budget: initialData?.budget || '' as string | number,
    customEventType: '',
    hasRegistrationFee: initialData?.hasRegistrationFee || false,
    registrationFee: initialData?.registrationFee || '' as string | number,
    paymentLink: initialData?.paymentLink || '',
    targetDepartments: initialData?.targetDepartments || (isFaculty ? (isPlacementCell ? [] : [user?.department || 'CSE']) : [] as string[]),
    allDepts: false,
    allBatches: false,
    allSections: false,
    description: initialData?.description || '',
    sponsors: initialData?.sponsors || [] as string[],
    centreName: initialData?.centreName || (eventScope === 'CENTRE' ? ((CENTRE_MAPPING[user?.department || ''] || CENTRE_MAPPING['Placement Department'] || [])[0] || '') : ''),
    isPublicEvent: initialData?.isPublicEvent || false,
    image: initialData?.image || '',
    openToAll: (initialData as any)?.openToAll || false,
    status: initialData?.status || 'REQUESTED',
    targetedBatch: (initialData as any)?.targetedBatch || '',
    refreshment_expense: (initialData as any)?.refreshment_expense?.toString() || '',
    transportation_expense: (initialData as any)?.transportation_expense?.toString() || '',
    session_coverage_fee: (initialData as any)?.session_coverage_fee?.toString() || '',
    total_expense: (initialData as any)?.total_expense?.toString() || '0',
    maxParticipants: (initialData as any)?.maxParticipants?.toString() || ''
  });

  // Sync financial totals
  useEffect(() => {
    const total = (parseFloat(formData.refreshment_expense) || 0) +
      (parseFloat(formData.transportation_expense) || 0) +
      (parseFloat(formData.session_coverage_fee) || 0);
    setFormData(prev => ({ ...prev, total_expense: total.toFixed(2) }));
  }, [formData.refreshment_expense, formData.transportation_expense, formData.session_coverage_fee]);





  const [newSponsor, setNewSponsor] = useState('');
  const [showAlternateEvent, setShowAlternateEvent] = useState(false);
  const [alternateEvent, setAlternateEvent] = useState({
    eventName: '',
    startDate: '',
    endDate: '',
    venue: 'N/A',
    customVenue: '',
  });

  const prevEventScope = useRef(eventScope);
  const hasInitializedEdit = useRef(!!initialData?.isEditMode);

  useEffect(() => {
    const scopeChanged = prevEventScope.current !== eventScope;
    prevEventScope.current = eventScope;

    // Skip reset entirely on initial mount when editing an existing event
    if (hasInitializedEdit.current) {
      hasInitializedEdit.current = false;
      if (!scopeChanged) return; // user?.department changed, not scope — don't reset
    }

    // Only reset when the scope actually changed (user clicked a different tab)
    if (!scopeChanged) return;

    // Reset event name and update default event type on scope change
    const availableCentres = CENTRE_MAPPING[user?.department || ''] || CENTRE_MAPPING['Placement Department'] || [];
    setFormData(prev => ({
      ...prev,
      eventName: '',
      eventType: eventScope === 'INSTITUTIONAL' ? '' :
        eventScope === 'CLUB' ? 'Club' :
          eventScope === 'PLACEMENT' ? 'Placement' : '',
      category: eventScope === 'CENTRE' ? 'CENTRE' : (eventScope === 'CLUB' ? 'CLUB' : 'ACADEMIC'),
      centreName: eventScope === 'CENTRE' ? (availableCentres[0] || '') : prev.centreName
    }));
  }, [eventScope, user?.department]);

  const [batches, setBatches] = useState<any[]>([]);

  // data-fetch effect is declared after the fetch functions below

  const fetchBatches = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/batches');
      if (response.ok) {
        const data = await response.json();
        setBatches(data);
      }
    } catch (err) {
      console.error('Failed to fetch batches:', err);
    }
  };

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const deptBatches = useMemo(() => {
    const dept = eventScope === 'DEPARTMENT' ? formData.department : (user?.department || 'CSE');
    return batches.filter(b => b.department === dept);
  }, [batches, formData.department, eventScope, user?.department]);

  const fetchClassStrengths = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/admin/users');
      if (response.ok) {
        const data = await response.json();

        // Count students dynamically in each class combo
        const studentCounts: Record<string, number> = {};
        data.forEach((u: any) => {
          if (u.role === 'STUDENT' && u.department && u.year && u.section) {
            const key = `${u.department.trim().toLowerCase()}_${u.year.trim().toLowerCase()}_${u.section.trim().toLowerCase()}`;
            studentCounts[key] = (studentCounts[key] || 0) + 1;
          }
        });

        const strengths = data
          .filter((u: any) => u.isClassIncharge)
          .map((u: any) => {
            const key = `${u.inchargeClass?.trim().toLowerCase()}_${u.inchargeBatch?.trim().toLowerCase()}_${u.inchargeSection?.trim().toLowerCase()}`;
            return {
              dept: u.inchargeClass,
              year: u.inchargeBatch,
              sec: u.inchargeSection,
              strength: studentCounts[key] || 0
            };
          });
        setClassStrengths(strengths);
      }
    } catch (err) {
      console.error('Failed to fetch class strengths:', err);
    }
  };

  const fetchClasses = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/classes');
      if (response.ok) {
        const data = await response.json();
        setClasses(data);
      }
    } catch (err) {
      console.error('Failed to fetch classes:', err);
    }
  };

  const fetchExistingEvents = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/events');
      if (response.ok) {
        const data = await response.json();
        setExistingEvents(data);
      }
    } catch (err) {
      console.error('Failed to fetch events:', err);
    }
  };

  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    fetchClasses();
    fetchExistingEvents();
    fetchClassStrengths();
    fetchBatches();
  }, []);
  /* eslint-enable react-hooks/set-state-in-effect */

  const availableYears = Array.from(new Set(
    classes
      .filter(c => c.institution.trim() === formData.institution.trim() &&
        (eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell) ? true : c.department.trim() === formData.department.trim()))
      .map(c => c.academicYear)
  )).sort();

  const availableSections = classes
    .filter(c =>
      c.institution.trim() === formData.institution.trim() &&
      ((eventScope === 'DEPARTMENT' || eventScope === 'PLACEMENT') ? (
        eventScope === 'DEPARTMENT' ? c.department.trim() === formData.department.trim() : formData.targetDepartments.includes(c.department.trim())
      ) : true) &&
      formData.academicYears.includes(c.academicYear.trim())
    )
    .reduce((acc, curr) => [...acc, ...curr.sections], [] as string[]);

  const toggleSelection = (field: 'academicYears' | 'targetedSections' | 'targetDepartments' | 'requirements', value: string) => {
    setFormData(prev => {
      const current = prev[field] as string[];
      const exists = current.includes(value);
      const updated = exists ? current.filter(v => v !== value) : [...current, value];

      if (field === 'academicYears') return { ...prev, academicYears: updated, allBatches: false };
      if (field === 'targetDepartments') return { ...prev, targetDepartments: updated, allDepts: false };
      if (field === 'targetedSections') return { ...prev, targetedSections: updated, allSections: false };
      return { ...prev, [field]: updated };
    });
  };

  const addSponsor = () => {
    if (newSponsor.trim()) {
      setFormData(prev => ({ ...prev, sponsors: [...prev.sponsors, newSponsor.trim()] }));
      setNewSponsor('');
    }
  };

  const removeSponsor = (index: number) => {
    setFormData(prev => ({ ...prev, sponsors: prev.sponsors.filter((_, i) => i !== index) }));
  };

  const isSectionDisabled = (section: string) => {
    if (formData.eventType === 'Other') return false;
    return existingEvents.some(e => {
      const status = e.status?.toUpperCase();
      const isActive = status === 'APPROVED' || status === 'COMPLETED' || status === 'PENDING_PR' || status === 'REQUESTED';
      return e.type?.toLowerCase() === formData.eventType?.toLowerCase() &&
        isActive &&
        e.targetedSections?.includes(section) &&
        formData.academicYears.some(y => e.academicYears?.includes(y));
    });
  };

  const leftOutSections = availableSections.filter(s =>
    !formData.targetedSections.includes(s) &&
    !isSectionDisabled(s)
  );

  const totalExpectedStrength = React.useMemo(() => {
    const deptsToTarget = (eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) ? formData.targetDepartments : [formData.department];
    const batchesToTarget = formData.allBatches ? availableYears : formData.academicYears;
    let total = 0;

    for (const d of deptsToTarget) {
      for (const y of batchesToTarget) {
        const availableSecsForThisCombo = classes
          .filter(c => c.department?.trim() === d?.trim() && c.academicYear?.trim() === y?.trim() && c.institution?.trim() === formData.institution?.trim())
          .reduce((acc, curr) => [...acc, ...curr.sections], [] as string[]);

        const sectionsToTarget = formData.allSections ? availableSecsForThisCombo : formData.targetedSections.filter(s => availableSecsForThisCombo.includes(s));

        for (const s of sectionsToTarget) {
          const match = classStrengths.find(cs => cs.dept === d && cs.year === y && cs.sec === s);
          if (match && match.strength > 0) {
            total += match.strength;
          }
        }
      }
    }
    return total;
  }, [formData.targetDepartments, formData.department, formData.academicYears, formData.targetedSections, formData.allBatches, formData.allSections, formData.institution, classStrengths, eventScope, isPlacementCell, availableYears, classes]);

  const filteredVenues = React.useMemo(() => {
    let list = venues;
    if (totalExpectedStrength > 0) {
      // Find the smallest capacity venue that can accommodate the totalExpectedStrength
      const validCapacities = venues
        .map(v => v.capacity)
        .filter((cap): cap is number => cap !== null && cap >= totalExpectedStrength);

      const minSufficientCapacity = validCapacities.length > 0 ? Math.min(...validCapacities) : totalExpectedStrength;

      list = venues.filter(v => {
        if (v.name === 'N/A' || v.name === 'Others.' || v.capacity === null) return true;
        if (initialData?.venue && v.name === initialData.venue) return true;

        // Capacity must be at least the audience size, and not exceed the max of (1.5x audience OR the smallest sufficient capacity)
        const maxAllowedCapacity = Math.max(totalExpectedStrength * 1.5, minSufficientCapacity);
        return v.capacity >= totalExpectedStrength && v.capacity <= maxAllowedCapacity;
      });
    }
    if (initialData?.venue && !list.some(v => v.name === initialData.venue)) {
      list = [...list, { name: initialData.venue, capacity: null }];
    }
    return list;
  }, [venues, totalExpectedStrength, initialData?.venue]);

  useEffect(() => {
    if (formData.venue && formData.venue !== 'N/A' && formData.venue !== 'Others.') {
      const isStillAvailable = filteredVenues.some(v => v.name === formData.venue);
      if (!isStillAvailable) {
        if (initialData?.isEditMode && formData.venue === initialData.venue) {
          return;
        }
        setFormData(prev => ({ ...prev, venue: 'N/A' }));
      }
    }
  }, [filteredVenues, formData.venue, initialData]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError('');

    const now = new Date();
    const earliestStart = new Date(formData.startDate);
    const latestEnd = new Date(formData.endDate);

    if (isNaN(earliestStart.getTime()) || isNaN(latestEnd.getTime())) {
      setError('Please select valid start and end dates & times.');
      setIsSubmitting(false);
      return;
    }

    if (earliestStart < now) {
      setError('Cannot schedule events in the past. Please select a future date and time.');
      setIsSubmitting(false);
      return;
    }

    if (latestEnd <= earliestStart) {
      setError('End date/time must be after the start date/time.');
      setIsSubmitting(false);
      return;
    }

    const groupRequestId = crypto.randomUUID();
    const batchesToAssign = formData.allBatches ? availableYears : formData.academicYears;

    if (eventScope === 'CENTRE' && !formData.centreName) {
      setError('Please select a centre.');
      setIsSubmitting(false);
      return;
    }

    if (formData.targetDepartments.length === 0 && (eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell))) {
      setError(`Please select at least one target department for this ${eventScope.toLowerCase()} event.`);
      setIsSubmitting(false);
      return;
    }

    if (eventScope !== 'CENTRE' && batchesToAssign.length === 0) {
      setError('Please select at least one target batch.');
      setIsSubmitting(false);
      return;
    }

    try {
      if (initialData?.isEditMode && initialData.id) {
        const updatePayload = {
          ...formData,
          title: formData.eventName,
          startDate: earliestStart.toISOString(),
          endDate: latestEnd.toISOString(),
          deptLimits,
          deptSectionLimits,
          maxParticipants: formData.maxParticipants === '' ? null : Number(formData.maxParticipants),
          durationDays: 1,
          dayConfigs: [],
          refreshment_expense: Number(formData.refreshment_expense) || 0,
          transportation_expense: Number(formData.transportation_expense) || 0,
          session_coverage_fee: Number(formData.session_coverage_fee) || 0,
          total_expense: Number(formData.total_expense) || 0,
          userId: user?.id,
          budget: formData.budget === '' ? 0 : Number(formData.budget),
          registrationFee: formData.hasRegistrationFee ? Number(formData.registrationFee) : 0,
          status: formData.status
        };

        const res = await fetch(`${API_BASE_URL}/api/events/${initialData.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(updatePayload),
        });

        if (!res.ok) {
          const err = await res.json();
        throw new Error(err.message || 'Update failed');
        }
      } else {
        const primaryPayload = {
          ...formData,
          startDate: earliestStart.toISOString(),
          endDate: latestEnd.toISOString(),
          deptLimits,
          deptSectionLimits,
          maxParticipants: formData.maxParticipants === '' ? null : Number(formData.maxParticipants),
          durationDays: 1,
          dayConfigs: [],
          refreshment_expense: Number(formData.refreshment_expense) || 0,
          transportation_expense: Number(formData.transportation_expense) || 0,
          session_coverage_fee: Number(formData.session_coverage_fee) || 0,
          total_expense: Number(formData.total_expense) || 0,
          department: formData.department,
          venue: formData.venue === 'Others.' ? formData.customVenue : formData.venue,
          groupRequestId,
          academicYears: batchesToAssign,
          targetedSections: formData.targetedSections,
          userId: user?.id,
          budget: formData.budget === '' ? 0 : Number(formData.budget),
          registrationFee: formData.hasRegistrationFee ? Number(formData.registrationFee) : 0,
          category: eventScope === 'INSTITUTIONAL' ? 'INSTITUTIONAL' :
            eventScope === 'CLUB' ? 'CLUB' :
            eventScope === 'CENTRE' ? 'CENTRE-ACTIVITY' :
              eventScope === 'PLACEMENT' ? 'PLACEMENT' :
                formData.category,
          eventType: formData.eventType,
          centreName: eventScope === 'CENTRE' ? formData.centreName : undefined,
          isPublicEvent: eventScope === 'CENTRE' ? formData.isPublicEvent : undefined,
          image: formData.image
        };

        const res = await fetch(API_BASE_URL + '/api/events/propose', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            ...primaryPayload,
            cancelConflicting: false
          }),
        });

        if (!res.ok) {
          const err = await res.json();
          if (res.status === 409 && err.canOverride) {
            setConflictData(err);
            setIsSubmitting(false);
            return;
          }
          throw new Error(err.message || 'Submission failed');
        }

        if (!formData.allSections && showAlternateEvent && (eventScope === 'DEPARTMENT' || eventScope === 'PLACEMENT') && leftOutSections.length > 0) {
          const altPayload = {
            ...formData,
            startDate: earliestStart.toISOString(),
            endDate: latestEnd.toISOString(),
            deptLimits,
            deptSectionLimits,
            maxParticipants: formData.maxParticipants === '' ? null : Number(formData.maxParticipants),
            durationDays: 1,
            dayConfigs: [],
            refreshment_expense: Number(formData.refreshment_expense) || 0,
            transportation_expense: Number(formData.transportation_expense) || 0,
            session_coverage_fee: Number(formData.session_coverage_fee) || 0,
            total_expense: Number(formData.total_expense) || 0,
            department: formData.department,
            groupRequestId,
            eventName: alternateEvent.eventName || `${formData.eventName} (Division 2)`,
            venue: alternateEvent.venue === 'Others.' ? alternateEvent.customVenue : alternateEvent.venue,
            targetedSections: leftOutSections,
            academicYears: batchesToAssign,
            userId: user?.id,
            budget: 0,
            registrationFee: formData.hasRegistrationFee ? Number(formData.registrationFee) : 0,
            eventType: formData.eventType
          };

          await fetch(API_BASE_URL + '/api/events/propose', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(altPayload),
          });
        }
      }
      setSubmitted(true);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <div className="bg-white rounded-[2.5rem] p-16 border border-slate-100 premium-shadow text-center max-w-2xl mx-auto">
        <CheckCircle2 className="w-20 h-20 text-emerald-500 mx-auto mb-6" />
        <h2 className="text-3xl font-black text-text-dark mb-4">Proposals Submitted!</h2>
        <p className="text-text-muted mb-8 italic">Your event proposals have been successfully queued for approval.</p>
        <button onClick={() => setSubmitted(false)} className="bg-brand-navy text-white px-8 py-4 rounded-2xl font-black uppercase tracking-widest hover:scale-105 transition-all">Done</button>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-8 pb-20">
      {(user?.role === 'ADMIN' || user?.role === 'PRINCIPAL') && (
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-brand-glow border border-brand-indigo/20 rounded-[2rem] p-8 flex flex-col md:flex-row items-center justify-between gap-6 premium-shadow-sm"
        >
          <div className="flex items-center gap-5">
            <div className="w-16 h-16 bg-white rounded-2xl flex items-center justify-center text-brand-indigo shadow-sm border border-brand-indigo/10">
              <FileSpreadsheet className="w-8 h-8" />
            </div>
            <div>
              <h3 className="text-lg font-black text-brand-navy leading-tight">Bulk Import via Excel</h3>
              <p className="text-[11px] font-bold text-brand-indigo/60 uppercase tracking-widest mt-1">Have many events? Upload a spreadsheet instead.</p>
            </div>
          </div>
          <button
            onClick={() => window.dispatchEvent(new CustomEvent('navigate', { detail: 'import-excel' }))}
            className="px-8 py-4 bg-brand-navy text-white rounded-2xl font-black text-[10px] uppercase tracking-[0.2em] hover:scale-105 transition-all shadow-lg shadow-brand-navy/20"
          >
            Open Import Tool
          </button>
        </motion.div>
      )}

      <div className="flex p-2 bg-slate-100 rounded-[2rem] gap-2">
        {!isPlacementCell && (
          <button
            type="button"
            onClick={() => setEventScope('DEPARTMENT')}
            className={cn(
              "flex-1 py-4 rounded-[1.5rem] text-[10px] font-black uppercase tracking-widest transition-all flex items-center justify-center gap-2",
              eventScope === 'DEPARTMENT' ? "bg-white text-brand-indigo shadow-sm" : "text-text-muted hover:bg-slate-50"
            )}
          >
            <Split className="w-4 h-4" />
            Departmental Event
          </button>
        )}
        {(isFaculty || isPlacementCell) && (
          <button
            type="button"
            onClick={() => setEventScope('CENTRE')}
            className={cn(
              "flex-1 py-4 rounded-[1.5rem] text-[10px] font-black uppercase tracking-widest transition-all flex items-center justify-center gap-2",
              eventScope === 'CENTRE' ? "bg-white text-brand-indigo shadow-sm" : "text-text-muted hover:bg-slate-50"
            )}
          >
            <Layers className="w-4 h-4" />
            Centre Event
          </button>
        )}
        {!isPlacementCell && (
          <button
            type="button"
            onClick={() => setEventScope('INSTITUTIONAL')}
            className={cn(
              "flex-1 py-4 rounded-[1.5rem] text-[10px] font-black uppercase tracking-widest transition-all flex items-center justify-center gap-2",
              eventScope === 'INSTITUTIONAL' ? "bg-white text-brand-indigo shadow-sm" : "text-text-muted hover:bg-slate-50"
            )}
          >
            <Globe className="w-4 h-4" />
            Institutional Event
          </button>
        )}
        {user?.isClubCoordinator && (
          <button
            type="button"
            onClick={() => setEventScope('CLUB')}
            className={cn(
              "flex-1 py-4 rounded-[1.5rem] text-[10px] font-black uppercase tracking-widest transition-all flex items-center justify-center gap-2",
              eventScope === 'CLUB' ? "bg-white text-brand-indigo shadow-sm" : "text-text-muted hover:bg-slate-50"
            )}
          >
            <ShieldCheck className="w-4 h-4" />
            Club Event
          </button>
        )}
        {isPlacementCell && (
          <button
            type="button"
            onClick={() => setEventScope('PLACEMENT')}
            className={cn(
              "flex-1 py-4 rounded-[1.5rem] text-[10px] font-black uppercase tracking-widest transition-all flex items-center justify-center gap-2",
              eventScope === 'PLACEMENT' ? "bg-white text-brand-indigo shadow-sm" : "text-text-muted hover:bg-slate-50"
            )}
          >
            <Zap className="w-4 h-4" />
            Placement Activity
          </button>
        )}
      </div>

      <form onSubmit={handleSubmit} className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden">
        <div className="p-10 bg-brand-navy text-white flex justify-between items-center">
          <div>
            <h2 className="text-3xl font-black tracking-tight mb-1">
              {eventScope === 'INSTITUTIONAL' ? 'Institutional Proposal' :
                eventScope === 'CLUB' ? 'Club Proposal' :
                  eventScope === 'CENTRE' ? 'Centre Event Proposal' :
                    eventScope === 'PLACEMENT' ? 'Placement Coordinator Schedule' : 'Departmental Proposal'}
            </h2>
            <p className="text-white/60 font-medium text-sm">
              {isFaculty ? `Faculty of ${user?.department}` : 'Administrative Portal'}
            </p>
          </div>
          <Building2 className="w-16 h-16 opacity-10" />
        </div>

        <div className="p-10 space-y-10">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            {(eventScope === 'DEPARTMENT' || eventScope === 'CENTRE') ? (
              <>
                <div>
                  <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Event Type</label>
                  <div className="relative group">
                    <select
                      required
                      value={formData.eventType}
                      onChange={e => setFormData({ ...formData, eventType: e.target.value })}
                      className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold appearance-none cursor-pointer group-hover:bg-slate-100 transition-all pr-12"
                    >
                      <option value="">Select Type</option>
                      {eventTypes.map(type => (
                        <option key={type} value={type}>{type}</option>
                      ))}
                    </select>
                    <ChevronDown className="absolute right-6 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted pointer-events-none" />
                  </div>
                </div>
                <div>
                  <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Event Name</label>
                  <input
                    type="text" required
                    value={formData.eventName}
                    onChange={e => setFormData({ ...formData, eventName: e.target.value })}
                    className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
                    placeholder="e.g. Workshop on Generative AI"
                  />
                </div>
              </>
            ) : eventScope === 'INSTITUTIONAL' ? (
              <>
                <div>
                  <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Select Institutional Event</label>
                  <div className="relative group">
                    <select
                      required
                      value={formData.eventType}
                      onChange={e => setFormData({ ...formData, eventType: e.target.value })}
                      className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold appearance-none cursor-pointer group-hover:bg-slate-100 transition-all pr-12"
                    >
                      <option value="">Choose Institutional Event...</option>
                      {availableInstitutionalEvents.map(ie => (
                        <option key={ie.id} value={ie.name}>{ie.name}</option>
                      ))}
                    </select>
                    <ChevronDown className="absolute right-6 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted pointer-events-none" />
                  </div>
                </div>
                <div>
                  <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Event Name</label>
                  <input
                    type="text" required
                    value={formData.eventName}
                    onChange={e => setFormData({ ...formData, eventName: e.target.value })}
                    className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
                    placeholder="e.g. Game Jam 2026"
                  />
                </div>
              </>
            ) : (
              <div className="md:col-span-2">
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Event Name</label>
                <input
                  type="text" required
                  value={formData.eventName}
                  onChange={e => setFormData({ ...formData, eventName: e.target.value, eventType: eventScope === 'CLUB' ? 'Club' : 'Placement' })}
                  className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
                  placeholder={eventScope === 'PLACEMENT' ? "Enter placement activity name..." : "Enter event title..."}
                />
              </div>
            )}

            <div className="md:col-span-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Hub Category</label>
              <div className="relative group">
                <select
                  required
                  value={formData.category}
                  onChange={e => setFormData({ ...formData, category: e.target.value })}
                  className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold appearance-none cursor-pointer group-hover:bg-slate-100 transition-all pr-12"
                >
                  <option value="TECHNICAL">Technical Event</option>
                  <option value="NON-TECHNICAL">Non-Technical Event</option>
                  <option value="WORKSHOP">Workshop</option>
                  <option value="CENTRE-ACTIVITY">Centre Based Activity</option>
                </select>
                <ChevronDown className="absolute right-6 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted pointer-events-none" />
              </div>
            </div>

            {initialData?.isEditMode && user?.role === 'ADMIN' && (
              <div className="md:col-span-2">
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Event Status (Admin Only)</label>
                <div className="relative group">
                  <select
                    value={formData.status}
                    onChange={e => setFormData({ ...formData, status: e.target.value })}
                    className="w-full bg-brand-glow border border-brand-indigo/20 rounded-2xl py-4 px-6 text-sm font-bold text-brand-indigo appearance-none cursor-pointer group-hover:bg-brand-glow/80 transition-all pr-12"
                  >
                    <option value="REQUESTED">REQUESTED</option>
                    <option value="PENDING_PR">PENDING PRINCIPAL</option>
                    <option value="APPROVED">APPROVED</option>
                    <option value="COMPLETED">COMPLETED</option>
                    <option value="CANCELLED">CANCELLED</option>
                    <option value="HOD_REJECTED">HOD REJECTED</option>
                    <option value="PRINCIPAL_REJECTED">PRINCIPAL REJECTED</option>
                  </select>
                  <ChevronDown className="absolute right-6 top-1/2 -translate-y-1/2 w-4 h-4 text-brand-indigo pointer-events-none" />
                </div>
              </div>
            )}

            <div className="md:col-span-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Event Description (Optional)</label>
              <div className="relative">
                <FileText className="absolute left-5 top-5 w-5 h-5 text-text-muted" />
                <textarea
                  value={formData.description}
                  onChange={e => setFormData({ ...formData, description: e.target.value })}
                  rows={4}
                  className="w-full bg-slate-50 border border-transparent rounded-2xl py-5 pl-14 pr-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all resize-none"
                  placeholder="Provide brief details about the event objective and highlights..."
                />
              </div>
            </div>

            <div className="md:col-span-2 relative group">
              <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">
                Venue {totalExpectedStrength > 0 && <span className="text-brand-indigo normal-case ml-2">(Est. Audience: {totalExpectedStrength})</span>}
              </label>
              <select
                value={formData.venue}
                onChange={e => setFormData({ ...formData, venue: e.target.value })}
                className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold appearance-none cursor-pointer group-hover:bg-slate-100 transition-all"
              >
                {filteredVenues.map(v => <option key={v.name} value={v.name}>{v.name} {v.capacity ? `(Max: ${v.capacity})` : ''}</option>)}
              </select>
              <ChevronDown className="absolute right-6 top-[52px] w-4 h-4 text-text-muted pointer-events-none" />
              {formData.venue === 'Others.' && (
                <div className="mt-4">
                  <input
                    type="text" required
                    value={formData.customVenue}
                    onChange={e => setFormData({ ...formData, customVenue: e.target.value })}
                    className="w-full bg-slate-50 border border-brand-indigo/30 rounded-2xl py-4 px-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo transition-all"
                    placeholder="Specify custom venue location..."
                  />
                </div>
              )}
              {totalExpectedStrength > 0 && (
                <p className="text-[9px] font-black text-brand-indigo uppercase tracking-widest mt-2 px-1">
                  ✨ Smart Allocation: Recommending venues matching ~{totalExpectedStrength} seats
                </p>
              )}
            </div>

            <div>
              <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Start Date & Time</label>
              <input
                type="datetime-local" required
                value={formData.startDate}
                onChange={e => setFormData({ ...formData, startDate: e.target.value })}
                className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
              />
            </div>

            <div>
              <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">End Date & Time</label>
              <input
                type="datetime-local" required
                value={formData.endDate}
                onChange={e => setFormData({ ...formData, endDate: e.target.value })}
                className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
              />
            </div>

            <div className="md:col-span-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">
                Total Capacity
              </label>
              <input
                type="number"
                placeholder="Unlimited"
                className="w-full border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold transition-all focus:bg-white bg-slate-50 text-text-dark focus:border-brand-indigo/30"
                value={formData.maxParticipants}
                onChange={e => setFormData({ ...formData, maxParticipants: e.target.value })}
              />
            </div>
          </div>



          <div className="space-y-8">
            <h3 className="text-xl font-black text-text-dark flex items-center gap-3">
              <Wallet className="w-6 h-6 text-brand-indigo" />
              Financial Details
            </h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Estimated Budget (₹)</label>
                <div className="relative">
                  <span className="absolute left-6 top-1/2 -translate-y-1/2 text-text-muted font-bold">₹</span>
                  <input
                    type="number"
                    value={formData.budget}
                    onChange={e => setFormData({ ...formData, budget: e.target.value })}
                    className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 pl-12 pr-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
                    placeholder="0.00"
                  />
                </div>
              </div>

              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Refreshment Expense (₹)</label>
                <div className="relative">
                  <span className="absolute left-6 top-1/2 -translate-y-1/2 text-text-muted font-bold">₹</span>
                  <input
                    type="number"
                    value={formData.refreshment_expense}
                    onChange={e => setFormData({ ...formData, refreshment_expense: e.target.value })}
                    className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 pl-12 pr-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
                    placeholder="0.00"
                  />
                </div>
              </div>

              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Transportation Expense (₹)</label>
                <div className="relative">
                  <span className="absolute left-6 top-1/2 -translate-y-1/2 text-text-muted font-bold">₹</span>
                  <input
                    type="number"
                    value={formData.transportation_expense}
                    onChange={e => setFormData({ ...formData, transportation_expense: e.target.value })}
                    className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 pl-12 pr-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
                    placeholder="0.00"
                  />
                </div>
              </div>

              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Session Coverage Fee (₹)</label>
                <div className="relative">
                  <span className="absolute left-6 top-1/2 -translate-y-1/2 text-text-muted font-bold">₹</span>
                  <input
                    type="number"
                    value={formData.session_coverage_fee}
                    onChange={e => setFormData({ ...formData, session_coverage_fee: e.target.value })}
                    className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 pl-12 pr-6 text-sm font-semibold focus:bg-white focus:border-brand-indigo/30 transition-all"
                    placeholder="0.00"
                  />
                </div>
              </div>

              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Total Projected Expense (₹)</label>
                <div className="relative">
                  <span className="absolute left-6 top-1/2 -translate-y-1/2 text-emerald-500 font-bold">₹</span>
                  <input
                    type="text"
                    readOnly
                    value={formData.total_expense}
                    className="w-full bg-emerald-50 border border-emerald-100 rounded-2xl py-4 pl-12 pr-6 text-sm font-black text-emerald-700 outline-none cursor-not-allowed"
                  />
                </div>
              </div>

              <div className="space-y-3">
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted block">Registration Fee Policy</label>
                <div
                  onClick={() => setFormData({ ...formData, hasRegistrationFee: !formData.hasRegistrationFee })}
                  className="flex items-center justify-between p-4 bg-slate-50 rounded-2xl border border-transparent hover:border-brand-indigo/20 cursor-pointer transition-all group"
                >
                  <div className="flex items-center gap-3">
                    <div className={cn(
                      "w-10 h-10 rounded-xl flex items-center justify-center transition-all",
                      formData.hasRegistrationFee ? "bg-brand-indigo text-white" : "bg-white text-slate-300"
                    )}>
                      <Ticket className="w-5 h-5" />
                    </div>
                    <div>
                      <p className="text-xs font-black text-text-dark uppercase tracking-widest">
                        {formData.hasRegistrationFee ? 'Paid Entry' : 'Free Entry'}
                      </p>
                      <p className="text-[9px] font-bold text-text-muted">Toggle to enable/disable fee</p>
                    </div>
                  </div>
                  <div className={cn(
                    "w-12 h-6 rounded-full relative transition-all duration-300",
                    formData.hasRegistrationFee ? "bg-brand-indigo" : "bg-slate-200"
                  )}>
                    <div className={cn(
                      "absolute top-1 w-4 h-4 bg-white rounded-full transition-all duration-300",
                      formData.hasRegistrationFee ? "left-7" : "left-1"
                    )} />
                  </div>
                </div>
              </div>

              <AnimatePresence>
                {formData.hasRegistrationFee && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="md:col-span-2 overflow-hidden"
                  >
                    <div className="p-6 bg-brand-glow border border-brand-indigo/10 rounded-[2rem] space-y-4 flex flex-col md:flex-row md:items-center gap-6">
                      <div className="flex-1">
                        <label className="text-[10px] font-black uppercase tracking-widest text-brand-indigo block mb-3">Fee per Delegate (₹)</label>
                        <div className="relative">
                          <span className="absolute left-6 top-1/2 -translate-y-1/2 text-brand-indigo font-bold">₹</span>
                          <input
                            type="number"
                            value={formData.registrationFee}
                            onChange={e => setFormData({ ...formData, registrationFee: e.target.value })}
                            className="w-full bg-white border border-brand-indigo/20 rounded-xl py-4 pl-12 pr-6 text-sm font-bold text-brand-indigo focus:ring-2 ring-brand-indigo/20 outline-none"
                            placeholder="Amount in INR"
                          />
                        </div>
                      </div>
                      <div className="flex-[2] w-full">
                        <label className="text-[10px] font-black uppercase tracking-widest text-brand-indigo block mb-3">Registration / Payment Link (e.g. Google Form, Sheets, GPay)</label>
                        <div className="relative">
                          <input
                            type="url"
                            value={formData.paymentLink}
                            onChange={e => setFormData({ ...formData, paymentLink: e.target.value })}
                            className="w-full bg-white border border-brand-indigo/20 rounded-xl py-4 px-6 text-sm font-bold text-brand-indigo focus:ring-2 ring-brand-indigo/20 outline-none"
                            placeholder="https://forms.gle/... or payment link"
                          />
                        </div>
                      </div>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </div>

          <div className="h-px bg-slate-100" />

          <div className="space-y-6">
            <h3 className="text-xl font-black text-text-dark flex items-center gap-3">
              <Zap className="w-6 h-6 text-brand-indigo" />
              Event Amenities
            </h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {amenitiesList.map(amenity => (
                <button
                  key={amenity}
                  type="button"
                  onClick={() => toggleSelection('requirements', amenity)}
                  className={cn(
                    "px-4 py-3 rounded-xl text-[10px] font-bold border transition-all flex items-center justify-center text-center",
                    formData.requirements.includes(amenity) ? "bg-brand-glow border-brand-indigo text-brand-indigo shadow-sm" : "bg-slate-50 border-transparent text-text-muted"
                  )}
                >
                  {amenity}
                </button>
              ))}
            </div>
          </div>

          <div className="h-px bg-slate-100" />

          <div className="space-y-6">
            <h3 className="text-xl font-black text-text-dark flex items-center gap-3">
              <Heart className="w-6 h-6 text-brand-indigo" />
              Event Sponsors
            </h3>

            <div className="flex gap-4">
              <div className="relative flex-1">
                <Briefcase className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-text-muted" />
                <input
                  type="text"
                  value={newSponsor}
                  onChange={e => setNewSponsor(e.target.value)}
                  onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), addSponsor())}
                  placeholder="Enter sponsor name (e.g. Google Cloud)"
                  className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 pl-14 pr-6 text-sm font-semibold"
                />
              </div>
              <button
                type="button"
                onClick={addSponsor}
                className="px-8 py-4 bg-brand-indigo text-white rounded-2xl font-black text-[10px] uppercase tracking-widest hover:scale-105 transition-all shadow-lg shadow-brand-indigo/20"
              >
                Add Sponsor
              </button>
            </div>

            <div className="flex flex-wrap gap-3">
              <AnimatePresence>
                {formData.sponsors.map((sponsor, idx) => (
                  <motion.div
                    key={idx}
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.8 }}
                    className="flex items-center gap-2 px-4 py-2 bg-brand-glow border border-brand-indigo/10 rounded-xl group"
                  >
                    <span className="text-xs font-black text-brand-indigo">{sponsor}</span>
                    <button
                      type="button"
                      onClick={() => removeSponsor(idx)}
                      className="p-1 hover:bg-brand-indigo hover:text-white rounded-md transition-all text-brand-indigo/40"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </motion.div>
                ))}
              </AnimatePresence>
            </div>
          </div>

          <div className="h-px bg-slate-100" />

          {/* Section 5: Audience Mapping */}
          {eventScope === 'CENTRE' ? (
            <div className="space-y-8">
              <h3 className="text-xl font-black text-text-dark flex items-center gap-3">
                <Layers className="w-6 h-6 text-brand-indigo" />
                Centre Details
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div>
                  <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Select Centre</label>
                  <div className="relative group">
                    <select
                      required
                      value={formData.centreName}
                      onChange={e => setFormData({ ...formData, centreName: e.target.value })}
                      className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold appearance-none cursor-pointer group-hover:bg-slate-100 transition-all pr-12"
                    >
                      {(CENTRE_MAPPING[user?.department || ''] || CENTRE_MAPPING['Placement Department'] || []).map(centre => (
                        <option key={centre} value={centre}>{centre}</option>
                      ))}
                    </select>
                    <ChevronDown className="absolute right-6 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted pointer-events-none" />
                  </div>
                </div>
                <div>
                  <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-3 block">Target Audience</label>
                  <div className="flex bg-slate-50 p-2 rounded-2xl gap-2">
                    <button
                      type="button"
                      onClick={() => setFormData({ ...formData, isPublicEvent: false })}
                      className={cn(
                        "flex-1 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all",
                        !formData.isPublicEvent ? "bg-white text-brand-indigo shadow-sm" : "text-text-muted hover:bg-slate-100"
                      )}
                    >
                      Centre Students Only
                    </button>
                    <button
                      type="button"
                      onClick={() => setFormData({ ...formData, isPublicEvent: true })}
                      className={cn(
                        "flex-1 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all",
                        formData.isPublicEvent ? "bg-white text-brand-indigo shadow-sm" : "text-text-muted hover:bg-slate-100"
                      )}
                    >
                      Public Event
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div className="space-y-8">
              <div className="p-6 bg-slate-50 rounded-3xl border border-slate-100 flex items-center justify-between mb-2">
                <div>
                  <h4 className="text-sm font-black text-text-dark uppercase">Open to All Students</h4>
                  <p className="text-[10px] text-text-muted mt-1">If enabled, this event will be visible and open to all departments, batches, and sections.</p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.openToAll}
                    onChange={e => setFormData({ ...formData, openToAll: e.target.checked })}
                    className="sr-only peer"
                  />
                  <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-indigo"></div>
                </label>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div className={cn((eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) && "md:col-span-2")}>
                  <div className="flex items-center justify-between mb-3">
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted block">
                      {(eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) ? 'Target Departments' : 'Proposing Department'}
                    </label>
                    {(eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) && (
                      <button
                        type="button"
                        onClick={() => {
                          const allD = formData.institution === 'RIT' ? ritDepartments : rsbDepartments;
                          const isAllSelected = formData.targetDepartments.length === allD.length;
                          setFormData({
                            ...formData,
                            allDepts: !isAllSelected,
                            targetDepartments: !isAllSelected ? allD : []
                          });
                        }}
                        className={cn(
                          "px-3 py-1 rounded-lg text-[8px] font-black uppercase tracking-widest border transition-all",
                          formData.targetDepartments.length === (formData.institution === 'RIT' ? ritDepartments : rsbDepartments).length ? "bg-brand-indigo text-white border-brand-indigo" : "bg-white text-text-muted border-slate-200"
                        )}
                      >
                        {formData.targetDepartments.length === (formData.institution === 'RIT' ? ritDepartments : rsbDepartments).length ? 'All Departments Selected' : 'Select All Departments'}
                      </button>
                    )}
                  </div>

                  {(eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) ? (
                    <div className="flex flex-wrap gap-2 p-6 bg-slate-50 rounded-[2.5rem] border border-slate-100">
                      {(formData.institution === 'RIT' ? ritDepartments : rsbDepartments).map(dept => (
                        <button
                          key={dept}
                          type="button"
                          onClick={() => toggleSelection('targetDepartments', dept)}
                          className={cn(
                            "px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all border",
                            formData.targetDepartments.includes(dept)
                              ? "bg-brand-navy text-white border-brand-navy shadow-md"
                              : "bg-white text-text-muted border-slate-200 hover:border-brand-indigo/30"
                          )}
                        >
                          {dept}
                        </button>
                      ))}
                    </div>
                  ) : (
                    <div className="p-4 bg-slate-50 rounded-2xl border border-slate-100 text-sm font-bold text-text-dark">
                      {formData.department}
                    </div>
                  )}
                </div>

                <div className={cn((eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) && "md:col-span-2")}>
                  <div className="flex items-center justify-between mb-3">
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted block">
                      {(eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) ? 'Target Batches' : 'Target Batch'}
                    </label>
                    {(eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) && (
                      <button
                        type="button"
                        onClick={() => {
                          const isAllSelected = formData.academicYears.length === availableYears.length;
                          setFormData({
                            ...formData,
                            allBatches: !isAllSelected,
                            academicYears: !isAllSelected ? availableYears : []
                          });
                        }}
                        className={cn(
                          "px-3 py-1 rounded-lg text-[8px] font-black uppercase tracking-widest border transition-all",
                          formData.academicYears.length === availableYears.length ? "bg-brand-indigo text-white border-brand-indigo" : "bg-white text-text-muted border-slate-200"
                        )}
                      >
                        {formData.academicYears.length === availableYears.length ? 'All Batches Selected' : 'Select All Batches'}
                      </button>
                    )}
                  </div>

                  {(eventScope === 'INSTITUTIONAL' || eventScope === 'CLUB' || eventScope === 'PLACEMENT' || (eventScope === 'DEPARTMENT' && isPlacementCell)) ? (
                    <div className="flex flex-wrap gap-2 p-6 bg-slate-50 rounded-[2.5rem] border border-slate-100">
                      {availableYears.map(year => (
                        <button
                          key={year}
                          type="button"
                          onClick={() => toggleSelection('academicYears', year)}
                          className={cn(
                            "px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all border",
                            formData.academicYears.includes(year)
                              ? "bg-brand-navy text-white border-brand-navy shadow-md"
                              : "bg-white text-text-muted border-slate-200 hover:border-brand-indigo/30"
                          )}
                        >
                          {year}
                        </button>
                      ))}
                    </div>
                  ) : (
                    <div className="space-y-4">
                      <select
                        value={formData.academicYears[0] || ''}
                        onChange={e => setFormData({ ...formData, targetedBatch: '', academicYears: [e.target.value], targetedSections: [], allSections: false })}
                        className="w-full bg-slate-50 border border-transparent rounded-2xl py-4 px-6 text-sm font-semibold appearance-none"
                      >
                        <option value="">Select Academic Year</option>
                        {availableYears.map(year => <option key={year} value={year}>{year}</option>)}
                      </select>
                    </div>
                  )}
                </div>
              </div>

              {(eventScope === 'DEPARTMENT' || eventScope === 'PLACEMENT') && formData.academicYears.length > 0 && (
                <div className="space-y-6">
                  <div className="flex items-center justify-between">
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted block">Select Sections</label>
                    <button
                      type="button"
                      onClick={() => {
                        const newVal = !formData.allSections;
                        setFormData({
                          ...formData,
                          allSections: newVal,
                          targetedSections: newVal ? availableSections.filter(s => !isSectionDisabled(s)) : []
                        });
                        if (newVal) setShowAlternateEvent(false);
                      }}
                      className={cn(
                        "px-3 py-1 rounded-lg text-[8px] font-black uppercase tracking-widest border transition-all",
                        formData.allSections ? "bg-brand-indigo text-white border-brand-indigo" : "bg-white text-text-muted border-slate-200"
                      )}
                    >
                      {formData.allSections ? 'All Sections Selected' : 'Select All Sections'}
                    </button>
                  </div>

                  <div className="flex flex-wrap gap-2">
                    {availableSections.map(section => {
                      const disabled = isSectionDisabled(section);
                      return (
                        <button
                          key={section}
                          type="button"
                          disabled={disabled}
                          onClick={() => toggleSelection('targetedSections', section)}
                          className={cn(
                            "w-12 h-12 rounded-xl flex items-center justify-center text-sm font-black transition-all border",
                            formData.targetedSections.includes(section) ? "bg-brand-indigo text-white" : disabled ? "bg-slate-100 text-slate-300 cursor-not-allowed" : "bg-slate-50 text-text-muted"
                          )}
                        >
                          {section}
                        </button>
                      );
                    })}
                  </div>

                  {formData.targetedSections.length > 0 && (
                    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="p-6 bg-slate-50 rounded-3xl space-y-4 border border-slate-100">
                      <div className="flex items-center justify-between">
                        <span className="text-[10px] font-black uppercase tracking-widest text-brand-indigo flex items-center gap-2">
                          {formData.allSections ? <Layers className="w-4 h-4" /> : <Split className="w-4 h-4" />}
                          {formData.allSections ? 'Single Combined Session' : 'Selective Allocation'}
                        </span>
                        {!formData.allSections && !showAlternateEvent && (
                          <button
                            type="button"
                            onClick={() => { setShowAlternateEvent(true); setAlternateEvent({ ...alternateEvent, eventName: `${formData.eventName} (Division 2)`, startDate: formData.startDate, endDate: formData.endDate }); }}
                            className="px-4 py-2 bg-brand-indigo text-white rounded-xl text-[8px] font-black uppercase tracking-widest"
                          >
                            Add Alternate Session
                          </button>
                        )}
                      </div>

                      <div className={cn("grid gap-4", formData.allSections ? "grid-cols-1" : "grid-cols-2")}>
                        <div className="p-4 bg-white rounded-2xl border border-brand-indigo/10">
                          <div className="text-[8px] font-black uppercase text-brand-indigo mb-1">
                            {formData.allSections ? 'Full Batch Audience' : 'Proposing For'}
                          </div>
                          <div className="text-xs font-bold">{formData.targetedSections.join(', ') || 'None'}</div>
                        </div>
                        {!formData.allSections && (
                          <div className="p-4 bg-white rounded-2xl border border-slate-200">
                            <div className="text-[8px] font-black uppercase text-text-muted mb-1">Remaining (Left Out)</div>
                            <div className="text-xs font-bold">
                              {leftOutSections.join(', ') || 'None'}
                            </div>
                          </div>
                        )}
                      </div>

                      {!formData.allSections && (
                        <p className="text-[9px] font-bold text-text-muted italic">
                          By default, only the selected sections are scheduled. The leftover sections appear in the second box and can be scheduled via an alternate session.
                        </p>
                      )}
                    </motion.div>
                  )}

                  <AnimatePresence>
                    {!formData.allSections && showAlternateEvent && (
                      <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} exit={{ opacity: 0, height: 0 }} className="p-6 border-2 border-dashed border-brand-indigo/20 rounded-3xl space-y-4">
                        <div className="flex items-center justify-between">
                          <span className="text-[10px] font-black uppercase tracking-widest text-brand-indigo">Alternate Session Details</span>
                          <X className="w-4 h-4 text-red-500 cursor-pointer" onClick={() => setShowAlternateEvent(false)} />
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <input type="text" placeholder="Session Name" value={alternateEvent.eventName} onChange={e => setAlternateEvent({ ...alternateEvent, eventName: e.target.value })} className="w-full bg-white border border-slate-100 rounded-xl py-3 px-4 text-xs font-bold" />
                          <div className="w-full">
                            <select value={alternateEvent.venue} onChange={e => setAlternateEvent({ ...alternateEvent, venue: e.target.value })} className="w-full bg-white border border-slate-100 rounded-xl py-3 px-4 text-xs font-bold">
                              {filteredVenues.map(v => <option key={v.name} value={v.name}>{v.name} {v.capacity ? `(Max: ${v.capacity})` : ''}</option>)}
                            </select>
                            {alternateEvent.venue === 'Others.' && (
                              <input type="text" required placeholder="Specify custom venue..." value={alternateEvent.customVenue} onChange={e => setAlternateEvent({ ...alternateEvent, customVenue: e.target.value })} className="w-full mt-3 bg-white border border-brand-indigo/30 rounded-xl py-3 px-4 text-xs font-bold" />
                            )}
                          </div>
                        </div>
                        <p className="text-[9px] font-bold text-brand-indigo italic">
                          This session will be scheduled for: {leftOutSections.join(', ')}
                        </p>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              )}
            </div>
          )}



          <div className="h-px bg-slate-100" />

          {/* Cover Image Upload Area */}
          <div className="space-y-4 pt-6">
            <label className="text-[10px] font-black uppercase tracking-widest text-text-muted block">
              Event Cover Banner
            </label>
            <div className="bg-slate-50/50 border border-slate-100 rounded-3xl p-6">
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="w-full h-48 bg-white border-2 border-dashed border-slate-200 rounded-2xl flex flex-col items-center justify-center gap-3 hover:border-brand-indigo transition-all overflow-hidden relative group"
              >
                {formData.image ? (
                  <div className="absolute inset-0">
                    <img src={formData.image} alt="Cover Banner" className="w-full h-full object-cover" />
                    <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-all flex items-center justify-center text-white text-[10px] font-black uppercase tracking-widest">
                      Change Cover Image
                    </div>
                  </div>
                ) : (
                  <>
                    <div className="w-12 h-12 bg-slate-50 rounded-full flex items-center justify-center text-slate-400 group-hover:text-brand-indigo transition-colors">
                      <i className="fas fa-image text-xl"></i>
                    </div>
                    <div className="text-center">
                      <span className="block text-[10px] font-black text-text-dark uppercase tracking-widest">
                        Upload Cover Image
                      </span>
                      <span className="block text-[8px] font-bold text-text-muted uppercase tracking-widest mt-1">
                        JPEG or PNG, Max width 800px (auto-resized)
                      </span>
                    </div>
                  </>
                )}
              </button>
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleImageChange}
                accept="image/*"
                className="hidden"
              />
            </div>
          </div>

          <div className="pt-6">
            {error && <div className="mb-4 p-4 bg-red-50 text-red-600 rounded-2xl text-xs font-bold flex items-center gap-2"><AlertCircle className="w-4 h-4" />{error}</div>}
            <button
              type="submit"
              disabled={isSubmitting}
              className="w-full h-20 bg-brand-navy text-white rounded-[1.5rem] font-black text-xs uppercase tracking-[0.3em] premium-shadow hover:scale-[1.02] transition-all flex items-center justify-center gap-4 disabled:opacity-50"
            >
              {isSubmitting ? 'Submitting Requests...' : 'Submit Proposals'}
              <ArrowRight className="w-5 h-5" />
            </button>
          </div>
        </div>
      </form>
      {/* Conflict Override Modal */}
      <AnimatePresence>
        {conflictData && (
          <div className="fixed inset-0 z-[200] flex items-center justify-center p-4">
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => setConflictData(null)} className="absolute inset-0 bg-slate-900/60 backdrop-blur-md" />
            <motion.div initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.9 }} className="relative w-full max-w-xl bg-white rounded-[3rem] premium-shadow p-10 text-center">
              <div className="w-20 h-20 bg-amber-100 rounded-3xl flex items-center justify-center mx-auto mb-6">
                <AlertTriangle className="w-10 h-10 text-amber-600" />
              </div>
              <h3 className="text-2xl font-black text-text-dark mb-4 tracking-tight">Scheduling Conflict Detected</h3>
              <p className="text-text-muted font-medium mb-8 leading-relaxed">
                The following events are already scheduled at this venue/time:
                <div className="mt-4 p-4 bg-slate-50 rounded-2xl border border-slate-100 text-left space-y-3">
                  {conflictData.conflicts.map((c: any) => (
                    <div key={c.id} className="flex items-center justify-between">
                      <div>
                        <p className="text-xs font-black text-brand-navy">{c.title}</p>
                        <p className="text-[10px] font-bold text-text-muted uppercase tracking-wider">{c.department} • {c.category}</p>
                      </div>
                      <div className="px-2 py-1 bg-red-50 text-red-600 text-[8px] font-black uppercase rounded-lg">Conflicting</div>
                    </div>
                  ))}
                </div>
              </p>

              <div className="grid grid-cols-2 gap-4 pt-4">
                <button
                  onClick={() => setConflictData(null)}
                  className="py-4 bg-slate-100 text-text-muted rounded-2xl font-black text-[10px] uppercase tracking-widest hover:bg-slate-200 transition-all"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    setConflictData(null);
                    (async () => {
                      setIsSubmitting(true);
                      const groupRequestId = crypto.randomUUID();
                      const earliestStart = new Date(formData.startDate);
                      const latestEnd = new Date(formData.endDate);
                      const payload = {
                        ...formData,
                        startDate: earliestStart.toISOString(),
                        endDate: latestEnd.toISOString(),
                        deptLimits,
                        deptSectionLimits,
                        maxParticipants: formData.maxParticipants === '' ? null : Number(formData.maxParticipants),
                        durationDays: 1,
                        refreshment_expense: Number(formData.refreshment_expense) || 0,
                        transportation_expense: Number(formData.transportation_expense) || 0,
                        session_coverage_fee: Number(formData.session_coverage_fee) || 0,
                        total_expense: Number(formData.total_expense) || 0,
                        department: formData.department,
                        groupRequestId,
                        academicYears: formData.allBatches ? availableYears : formData.academicYears,
                        targetedSections: eventScope === 'DEPARTMENT' ? formData.targetedSections : [],
                        userId: user?.id,
                        budget: formData.budget === '' ? 0 : Number(formData.budget),
                        registrationFee: formData.hasRegistrationFee ? Number(formData.registrationFee) : 0,
                        category: 'PLACEMENT',
                        eventType: 'Placement Activity',
                        cancelConflicting: true
                      };

                      const res = await fetch(API_BASE_URL + '/api/events/propose', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(payload),
                      });

                      if (res.ok) setSubmitted(true);
                      else {
                        const err = await res.json();
                        setError(err.message);
                      }
                      setIsSubmitting(false);
                    })();
                  }}
                  className="py-4 bg-brand-indigo text-white rounded-2xl font-black text-[10px] uppercase tracking-widest hover:scale-105 transition-all shadow-lg shadow-brand-indigo/20"
                >
                  Prioritize Placement
                </button>
              </div>
              <p className="mt-6 text-[9px] font-bold text-amber-600 italic">
                * Note: Prioritizing this event will automatically CANCEL the conflicting club and departmental events.
              </p>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
};
