import { initializeApp, getApp, getApps } from 'firebase/app';
import { 
  getFirestore, 
  collection, 
  getDocs, 
  doc, 
  getDoc, 
  setDoc, 
  updateDoc, 
  deleteDoc
} from 'firebase/firestore';
import { getAuth, GoogleAuthProvider } from 'firebase/auth';

const firebaseConfig = {
  apiKey: "AIzaSyBdRUyA7LDtDReUA3TXDys71dSHgD2tOEA",
  authDomain: "ems-ritchennai1.firebaseapp.com",
  projectId: "ems-ritchennai1",
  storageBucket: "ems-ritchennai1.firebasestorage.app",
  messagingSenderId: "825363154108",
  appId: "1:825363154108:web:7b6d3430aa3b696fef3cb9",
  measurementId: "G-3W7ECQ52G1"
};

// Initialize Firebase App
export const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();
export const db = getFirestore(app);
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();

// Helper: parse date strings into Date objects
function parseDate(val: any): Date {
  if (!val) return new Date();
  let str = String(val).trim().replace(" ", "T");
  if (str.length === 10) str += "T00:00:00";
  if (str.length === 16) str += ":00";
  if (str.includes("+")) str = str.substring(0, str.indexOf("+"));
  if (str.includes("Z")) str = str.replace("Z", "");
  if (str.includes(".")) str = str.substring(0, str.indexOf("."));
  return new Date(str);
}

// Helper: parse BodyInit body to JSON
function parseBody(body: any): any {
  if (!body) return {};
  try {
    return JSON.parse(String(body));
  } catch {
    return {};
  }
}

// Conflict checking logic
async function getConflictMessage(event: any, ignoreId: any = null): Promise<string | null> {
  const start = parseDate(event.startDate || event.finalDate);
  const end = parseDate(event.endDate || (event.startDate ? new Date(parseDate(event.startDate).getTime() + 2 * 60 * 60 * 1000) : null));
  const location = String(event.location || event.venue || "").trim();
  const institution = String(event.institution || "RIT").trim();

  if (!location || !start || !end) return null;

  try {
    const colRef = collection(db, 'ems_events');
    const snap = await getDocs(colRef);
    const existingEvents = snap.docs.map(d => d.data());

    for (const other of existingEvents) {
      if (other.status === 'CANCELLED') continue;
      if (ignoreId && String(other.id) === String(ignoreId)) continue;
      if (event.id && String(other.id) === String(event.id)) continue;
      if (event.groupRequestId && other.groupRequestId === event.groupRequestId) continue;

      const oStart = parseDate(other.startDate);
      const oEnd = parseDate(other.endDate);
      const oLoc = String(other.location || "").trim();
      const oInst = String(other.institution || "RIT").trim();

      // Check overlap
      if (
        oInst === institution &&
        oLoc.toLowerCase() === location.toLowerCase() &&
        start < oEnd &&
        end > oStart
      ) {
        const timeFormatter = new Intl.DateTimeFormat('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });
        return `Venue Conflict: '${location}' is already booked for '${other.title}' from ${timeFormatter.format(oStart)} to ${timeFormatter.format(oEnd)}`;
      }
    }
  } catch (err) {
    console.error("Conflict checking error:", err);
  }
  return null;
}

// Generate sequential IDs
function generateNumericId(): number {
  return Date.now() + Math.floor(Math.random() * 1000);
}

// Seeding logic
async function seedDatabaseIfEmpty() {
  try {
    const usersSnap = await getDocs(collection(db, 'ems_users'));
    if (usersSnap.empty) {
      console.log("[Firebase Backend] Seeding users...");
      const defaultUsers = [
        { id: 1, email: "admin@rit.edu", password: "admin123", fullName: "System Administrator", role: "ADMIN", department: "ADMIN", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: false, assignedClubs: [] },
        { id: 2, email: "faculty@rit.edu", password: "faculty123", fullName: "Dr. Faculty Member", role: "FACULTY", department: "CSE", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: true, inchargeClass: "CSE", inchargeBatch: "3rd Year", inchargeSection: "A", classStrength: 0, assignedClubs: [] },
        { id: 3, email: "hod@rit.edu", password: "hod123", fullName: "Prof. Head of Dept", role: "HOD", department: "AI&ML", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: false, assignedClubs: [] },
        { id: 4, email: "principal@rit.edu", password: "principal123", fullName: "Dr. College Principal", role: "PRINCIPAL", department: "ADMIN", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: false, assignedClubs: [] },
        { id: 5, email: "placement@rit.edu", password: "placement123", fullName: "Placement Coordinator", role: "PLACEMENT", department: "Placement Department", isClubCoordinator: false, isPlacementStaff: true, isClassIncharge: false, assignedClubs: [] },
        { id: 6, email: "admin2@rit.edu", password: "admin123", fullName: "Secondary Admin", role: "ADMIN", department: "ADMIN", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: false, assignedClubs: [] },
        { id: 7, email: "principal2@rit.edu", password: "principal123", fullName: "Vice Principal", role: "PRINCIPAL", department: "ADMIN", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: false, assignedClubs: [] },
        { id: 8, email: "hod_cse@rit.edu", password: "hod123", fullName: "CSE HOD", role: "HOD", department: "CSE", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: false, assignedClubs: [] },
        { id: 9, email: "faculty2@rit.edu", password: "faculty123", fullName: "Assistant Professor CSE", role: "FACULTY", department: "CSE", isClubCoordinator: false, isPlacementStaff: false, isClassIncharge: false, assignedClubs: [] }
      ];

      for (const u of defaultUsers) {
        await setDoc(doc(db, 'ems_users', String(u.id)), u);
      }
    }

    const classesSnap = await getDocs(collection(db, 'ems_classes'));
    if (classesSnap.empty) {
      console.log("[Firebase Backend] Seeding classes...");
      const defaultClasses = [
        { id: 1, institution: "RIT", department: "CSE", academicYear: "3rd Year", sections: ["A", "B"], status: "Ready" },
        { id: 2, institution: "RIT", department: "AI&ML", academicYear: "3rd Year", sections: ["A"], status: "Ready" },
        { id: 3, institution: "RIT", department: "ECE", academicYear: "2nd Year", sections: ["A", "B", "C"], status: "Ready" }
      ];
      for (const c of defaultClasses) {
        await setDoc(doc(db, 'ems_classes', String(c.id)), c);
      }
    }

    // Clean up existing dummy events with "Sample event for" description
    const eventsSnap = await getDocs(collection(db, 'ems_events'));
    for (const d of eventsSnap.docs) {
      const data = d.data();
      if (data.description && data.description.startsWith("Sample event for")) {
        console.log("[Firebase Backend] Deleting dummy event:", data.title);
        await deleteDoc(d.ref);
      }
    }
  } catch (err) {
    console.error("Cleanup failed:", err);
  }
}

// Perform initial seed
seedDatabaseIfEmpty();

// Set up the fetch interceptor
const originalFetch = window.fetch;
window.fetch = async function(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
  const urlStr = typeof input === 'string' ? input : (input instanceof URL ? input.href : input.url);
  
  // Only intercept endpoints containing '/api/'
  if (!urlStr.includes('/api/')) {
    return originalFetch(input, init);
  }

  const parsedUrl = new URL(urlStr, window.location.origin);
  const path = parsedUrl.pathname;
  const method = (init?.method || 'GET').toUpperCase();
  const queryParams = parsedUrl.searchParams;

  console.log(`[Firebase Interceptor] ${method} ${path}`);

  // Helper response builder
  const jsonResponse = (data: any, status = 200) => {
    return new Response(JSON.stringify(data), {
      status,
      headers: { 'Content-Type': 'application/json' }
    });
  };

  try {
    // ----------------------------------------------------
    // AUTH CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/auth/login' && method === 'POST') {
      const { email, password } = parseBody(init?.body);
      const emailLower = (email || '').trim().toLowerCase();
      const snap = await getDocs(collection(db, 'ems_users'));
      const userDoc = snap.docs.find(d => d.data().email?.toLowerCase() === emailLower);

      if (userDoc) {
        const u = userDoc.data();
        if (u.password === password) {
          // Exclude password from response
          const { password: _, ...userData } = u;
          return jsonResponse({
            ...userData,
            department: userData.department || "N/A",
            assignedClubs: userData.assignedClubs || []
          });
        } else {
          return jsonResponse({ message: "Invalid password for this registered email" }, 401);
        }
      }

      return jsonResponse({ message: "Invalid email or passcode. Please check your credentials or register a new account." }, 401);
    }

    if (path === '/api/auth/google-login' && method === 'POST') {
      const { email, fullName } = parseBody(init?.body);
      const emailLower = (email || '').trim().toLowerCase();
      const snap = await getDocs(collection(db, 'ems_users'));
      const userDoc = snap.docs.find(d => d.data().email?.toLowerCase() === emailLower);

      if (userDoc) {
        const u = userDoc.data();
        const { password: _, ...userData } = u;
        return jsonResponse({
          ...userData,
          department: userData.department || "N/A",
          assignedClubs: userData.assignedClubs || []
        });
      }

      // Check if matches student RIT format
      const isRitEmail = emailLower.includes('@ritchennai.edu.in') || emailLower.includes('.ritchennai.edu.in');
      if (isRitEmail) {
        const studentMatch = emailLower.match(/^student\.(\d{6})@([a-zA-Z0-9&-_]+)\.ritchennai\.edu\.in$/);
        let rollNo = studentMatch ? studentMatch[1] : '';
        let rawDept = studentMatch ? studentMatch[2] : 'CSE';

        // Extract department from the email subdomain if possible
        const deptMatch = emailLower.match(/@([a-zA-Z0-9&-_]+)\.ritchennai\.edu\.in$/);
        if (!studentMatch && deptMatch) {
          rawDept = deptMatch[1];
        }

        if (!rollNo) {
          const digitMatch = emailLower.match(/\d+/);
          rollNo = digitMatch ? digitMatch[0] : String(Math.floor(100000 + Math.random() * 900000));
        }

        // Calculate joining year and academic year (current local time is 2026-06-19)
        const joinYear = 2000 + parseInt(rollNo.substring(0, 2) || "23");
        const currentYear = new Date().getFullYear();
        const currentMonth = new Date().getMonth();
        const academicYearOffset = currentMonth >= 5 ? 1 : 0;
        const yearIndex = currentYear - joinYear + academicYearOffset;
        const years = ["1st Year", "2nd Year", "3rd Year", "4th Year"];
        const calculatedYear = years[yearIndex - 1] || "3rd Year";

        // Map department
        let dept = rawDept.toUpperCase();
        if (dept === 'AIDS') dept = 'AI&DS';
        else if (dept === 'AIML') dept = 'AI&ML';
        else if (dept === 'VLSI') dept = 'EE(VLSI)';
        else if (dept === 'BIOTECH' || dept === 'BIO-TECH') dept = 'BIOTECH';
        else if (dept === 'H&S') dept = 'H&S Dept';

        const newUser = {
          id: generateNumericId(),
          email: emailLower,
          password: 'google-oauth-placeholder',
          fullName: fullName || `Student ${rollNo}`,
          role: 'STUDENT',
          department: dept,
          year: calculatedYear,
          section: 'A',
          regNo: rollNo,
          phone: '',
          gender: 'Male',
          collegeName: 'Rajalakshmi Institute of Technology',
          isClubCoordinator: false,
          isPlacementStaff: false,
          isClassIncharge: false,
          assignedClubs: []
        };

        await setDoc(doc(db, 'ems_users', String(newUser.id)), newUser);

        const { password: _, ...userData } = newUser;
        return jsonResponse({
          ...userData,
          department: userData.department || "N/A",
          assignedClubs: userData.assignedClubs || []
        });
      }

      // Register external students automatically
      if (emailLower) {
        const newUser = {
          id: generateNumericId(),
          email: emailLower,
          password: 'google-oauth-placeholder',
          fullName: fullName || emailLower.split('@')[0],
          role: 'STUDENT',
          department: 'Others',
          year: 'N/A',
          section: 'N/A',
          regNo: 'EXT-' + Math.floor(Math.random() * 100000),
          phone: '',
          gender: 'Male',
          collegeName: 'External Institution',
          isClubCoordinator: false,
          isPlacementStaff: false,
          isClassIncharge: false,
          assignedClubs: []
        };

        await setDoc(doc(db, 'ems_users', String(newUser.id)), newUser);

        const { password: _, ...userData } = newUser;
        return jsonResponse({
          ...userData,
          department: userData.department || "N/A",
          assignedClubs: userData.assignedClubs || []
        });
      }

      return jsonResponse({ message: "Access denied. Only registered accounts can log in." }, 401);
    }

    // ----------------------------------------------------
    // ADMIN USER CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/admin/users' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_users'));
      return jsonResponse(snap.docs.map(d => d.data()));
    }

    if (path === '/api/admin/users' && method === 'POST') {
      const payload = parseBody(init?.body);
      const snap = await getDocs(collection(db, 'ems_users'));
      const existingDoc = snap.docs.find(d => d.data().email?.toLowerCase() === payload.email?.toLowerCase());

      const role = payload.role || 'FACULTY';
      const department = payload.department || ((role === 'HOD' || role === 'FACULTY') ? 'H&S Dept' : '');

      if (existingDoc) {
        const existingUser = existingDoc.data();
        if (existingUser.role === 'STUDENT') {
          // Promote existing student to faculty/staff
          const updatedUser = {
            ...existingUser,
            ...payload,
            role: role,
            department: department,
            id: existingUser.id // Lock original ID
          };
          await setDoc(doc(db, 'ems_users', String(existingUser.id)), updatedUser);
          return jsonResponse(updatedUser);
        } else {
          return jsonResponse({ message: "User with this email already exists" }, 400);
        }
      }

      const newUser = {
        ...payload,
        id: generateNumericId(),
        email: payload.email?.trim().toLowerCase(),
        fullName: payload.fullName?.trim(),
        role: role,
        department: department,
        assignedClubs: payload.assignedClubs || []
      };

      await setDoc(doc(db, 'ems_users', String(newUser.id)), newUser);
      return jsonResponse(newUser);
    }

    if (path.startsWith('/api/admin/users/') && method === 'PUT') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      const payload = parseBody(init?.body);
      const docRef = doc(db, 'ems_users', String(id));
      const snap = await getDoc(docRef);

      if (!snap.exists()) {
        return jsonResponse({ message: "User not found" }, 404);
      }

      const role = payload.role || snap.data().role || 'FACULTY';
      const department = payload.department !== undefined 
        ? payload.department 
        : (snap.data().department || '');

      const updated = {
        ...snap.data(),
        ...payload,
        department: department,
        id: snap.data().id // lock ID
      };

      await setDoc(docRef, updated);
      return jsonResponse(updated);
    }

    if (path.startsWith('/api/admin/users/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_users', String(id)));
      return jsonResponse({ message: "User deleted successfully" });
    }

    // ----------------------------------------------------
    // CLASSES CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/classes' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_classes'));
      return jsonResponse(snap.docs.map(d => d.data()));
    }

    if (path === '/api/classes' && method === 'POST') {
      const payload = parseBody(init?.body);
      const newClass = {
        ...payload,
        id: generateNumericId(),
        status: payload.status || "Ready"
      };
      await setDoc(doc(db, 'ems_classes', String(newClass.id)), newClass);
      return jsonResponse(newClass);
    }

    if (path.startsWith('/api/classes/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_classes', String(id)));
      return jsonResponse({ message: "Class mapping deleted successfully" });
    }

    if (path === '/api/classes/promote' && method === 'POST') {
      const inst = queryParams.get('institution') || '';
      const snap = await getDocs(collection(db, 'ems_classes'));
      const classes = snap.docs.map(d => d.data());

      for (const cm of classes) {
        if (cm.institution?.trim().toLowerCase() !== inst.trim().toLowerCase()) {
          continue;
        }
        const ref = doc(db, 'ems_classes', String(cm.id));
        switch (cm.academicYear) {
          case "1st Year":
            await updateDoc(ref, { academicYear: "2nd Year" });
            break;
          case "2nd Year":
            await updateDoc(ref, { academicYear: "3rd Year" });
            break;
          case "3rd Year":
            await updateDoc(ref, { academicYear: "4th Year" });
            break;
          case "4th Year":
            await deleteDoc(ref);
            break;
        }
      }
      return jsonResponse({ message: `Academic year promotion completed for ${inst}` });
    }

    // ----------------------------------------------------
    // BATCHES CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/batches' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_batches'));
      return jsonResponse(snap.docs.map(d => d.data()));
    }

    if (path === '/api/batches' && method === 'POST') {
      const payload = parseBody(init?.body);
      const id = payload.id || generateNumericId();
      const newBatch = {
        ...payload,
        id,
        classes: payload.classes || []
      };
      await setDoc(doc(db, 'ems_batches', String(id)), newBatch);
      return jsonResponse(newBatch);
    }

    if (path.startsWith('/api/batches/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_batches', String(id)));
      return jsonResponse({ message: "Batch deleted successfully" });
    }

    // ----------------------------------------------------
    // VENUES CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/venues' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_venues'));
      let list = snap.docs.map(d => d.data());
      
      if (list.length === 0) {
        const defaultVenues = [
          { id: 'v-1', name: 'GB 4th floor auditorium', capacity: 500 },
          { id: 'v-2', name: 'Wozniak Auditorium', capacity: 180 },
          { id: 'v-3', name: 'C6-02 Indoor Theatre', capacity: 180 },
          { id: 'v-4', name: 'H Block Guest Lecture Theatre', capacity: 60 },
          { id: 'v-5', name: 'Steve Jobs Computer Centre 1', capacity: 120 },
          { id: 'v-6', name: 'Steve Jobs Computer Centre 2', capacity: 120 }
        ];
        for (const v of defaultVenues) {
          await setDoc(doc(db, 'ems_venues', v.id), v);
        }
        list = defaultVenues;
      }
      return jsonResponse(list);
    }

    if (path === '/api/venues' && method === 'POST') {
      const payload = parseBody(init?.body);
      const id = payload.id || 'v-' + generateNumericId();
      const newVenue = {
        ...payload,
        id,
        capacity: payload.capacity !== null && payload.capacity !== undefined ? Number(payload.capacity) : null
      };
      await setDoc(doc(db, 'ems_venues', String(id)), newVenue);
      return jsonResponse(newVenue);
    }

    if (path.startsWith('/api/venues/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_venues', String(id)));
      return jsonResponse({ message: "Venue deleted successfully" });
    }

    // ----------------------------------------------------
    // INSTITUTIONAL CHECKLIST EVENTS CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/institutional-events' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_institutional_events'));
      let list = snap.docs.map(d => d.data());
      
      // If collection is empty, seed it with the default list
      if (list.length === 0) {
        const defaultEvents = [
          { id: 'ie-1', name: 'New Year & Christmas Celebration', month: 'January', semester: 'EVEN' },
          { id: 'ie-2', name: 'Republic Day Celebration', month: 'January', semester: 'EVEN' },
          { id: 'ie-3', name: 'Pongal Celebration', month: 'January', semester: 'EVEN' },
          { id: 'ie-4', name: 'Yatra Banner Release', month: 'January', semester: 'EVEN' },
          { id: 'ie-5', name: 'Yatra Ethnic Day', month: 'February', semester: 'EVEN' },
          { id: 'ie-6', name: 'Yatra', month: 'February', semester: 'EVEN' },
          { id: 'ie-7', name: 'International Womens Day', month: 'March', semester: 'EVEN' },
          { id: 'ie-8', name: 'Ugathi', month: 'March', semester: 'EVEN' },
          { id: 'ie-9', name: 'Tamil New Year', month: 'April', semester: 'EVEN' },
          { id: 'ie-10', name: 'Techritz', month: 'July', semester: 'ODD' },
          { id: 'ie-11', name: 'Independence Day', month: 'August', semester: 'ODD' },
          { id: 'ie-12', name: 'AI Horizon Week', month: 'August', semester: 'ODD' },
          { id: 'ie-13', name: 'Initiation Day', month: 'September', semester: 'ODD' },
          { id: 'ie-14', name: 'Onam Celebration', month: 'September', semester: 'ODD' },
          { id: 'ie-15', name: 'Teachers Day', month: 'September', semester: 'ODD' },
          { id: 'ie-16', name: 'Engineers Day', month: 'September', semester: 'ODD' },
          { id: 'ie-17', name: 'SDG Golu', month: 'September', semester: 'ODD' },
          { id: 'ie-18', name: 'Ayutha Puja', month: 'October', semester: 'ODD' },
          { id: 'ie-19', name: 'Tech Fest IIT Bombay', month: 'October', semester: 'ODD' },
          { id: 'ie-20', name: 'EDI Conclave - FICCI Flow', month: 'November', semester: 'ODD' }
        ];
        for (const e of defaultEvents) {
          await setDoc(doc(db, 'ems_institutional_events', e.id), e);
        }
        list = defaultEvents;
      }
      return jsonResponse(list);
    }

    if (path === '/api/institutional-events' && method === 'POST') {
      const payload = parseBody(init?.body);
      const id = payload.id || `ie-${Date.now()}`;
      const newEv = {
        id,
        name: payload.name || "Untitled Milestone",
        month: payload.month || "January",
        semester: payload.semester || "ODD"
      };
      await setDoc(doc(db, 'ems_institutional_events', id), newEv);
      return jsonResponse(newEv);
    }

    if (path.startsWith('/api/institutional-events/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_institutional_events', String(id)));
      return jsonResponse({ message: "Institutional event deleted successfully" });
    }

    // ----------------------------------------------------
    // NOTES CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/notes' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_notes'));
      const list = snap.docs.map(d => d.data());
      // Sort desc
      list.sort((a, b) => new Date(b.createdAt || 0).getTime() - new Date(a.createdAt || 0).getTime());
      return jsonResponse(list);
    }

    if (path === '/api/notes' && method === 'POST') {
      const payload = parseBody(init?.body);
      const newNote = {
        ...payload,
        id: generateNumericId(),
        createdAt: new Date().toISOString()
      };
      await setDoc(doc(db, 'ems_notes', String(newNote.id)), newNote);
      return jsonResponse(newNote);
    }

    // ----------------------------------------------------
    // EVENTS CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/events' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_events'));
      const events = snap.docs.map(d => d.data());

      // Fetch all registrations to compute current participant counts dynamically
      const regsSnap = await getDocs(collection(db, 'ems_registrations'));
      const registrations = regsSnap.docs.map(d => d.data());

      // Populate conflicts and currentParticipants
      for (const event of events) {
        const count = registrations.filter(r => String(r.eventId || r.event_id) === String(event.id)).length;
        event.currentParticipants = count;
        if (event["total capacity"] !== undefined) {
          event.maxParticipants = event["total capacity"];
        }

        if (!['APPROVED', 'COMPLETED', 'CANCELLED'].includes(event.status)) {
          const conflictMsg = await getConflictMessage(event);
          if (conflictMsg) {
            event.conflictMessage = conflictMsg;
          }
        }
      }
      return jsonResponse(events);
    }

    if (path === '/api/events/propose' && method === 'POST') {
      const payload = parseBody(init?.body);
      const userId = payload.userId;
      const userSnap = await getDoc(doc(db, 'ems_users', String(userId)));

      if (!userSnap.exists()) {
        return jsonResponse({ message: "Proposer user not found" }, 400);
      }

      const proposer = userSnap.data();
      const start = parseDate(payload.startDate);
      const end = parseDate(payload.endDate);

      if (start < new Date()) {
        return jsonResponse({ message: "Cannot schedule events in the past" }, 400);
      }

      if (end <= start) {
        return jsonResponse({ message: "End date must be after start date" }, 400);
      }

      const conflictMsg = await getConflictMessage(payload);
      if (conflictMsg) {
        // If placement with cancelConflicting, we cancel other events
        if (payload.category === 'PLACEMENT' && payload.cancelConflicting) {
          const colRef = collection(db, 'ems_events');
          const snap = await getDocs(colRef);
          const allEvs = snap.docs.map(d => d.data());

          for (const other of allEvs) {
            if (other.status === 'CANCELLED') continue;
            if (payload.groupRequestId && other.groupRequestId === payload.groupRequestId) continue;

            const oStart = parseDate(other.startDate);
            const oEnd = parseDate(other.endDate);
            const oLoc = String(other.location || "").trim();
            const oInst = String(other.institution || "RIT").trim();

            if (
              oInst === String(payload.institution || "RIT").trim() &&
              oLoc.toLowerCase() === String(payload.venue || "").trim().toLowerCase() &&
              start < oEnd &&
              end > oStart
            ) {
              await updateDoc(doc(db, 'ems_events', String(other.id)), {
                status: 'CANCELLED',
                rejectionReason: "This event is cancelled due to the placement activity happening at the venue at this timing."
              });
            }
          }
        } else {
          // Find overlapping
          const colRef = collection(db, 'ems_events');
          const snap = await getDocs(colRef);
          const list = snap.docs.map(d => d.data()).filter(other => {
            if (other.status === 'CANCELLED') return false;
            const oStart = parseDate(other.startDate);
            const oEnd = parseDate(other.endDate);
            const oLoc = String(other.location || "").trim();
            const oInst = String(other.institution || "RIT").trim();
            return (
              oInst === String(payload.institution || "RIT").trim() &&
              oLoc.toLowerCase() === String(payload.venue || "").trim().toLowerCase() &&
              start < oEnd &&
              end > oStart
            );
          });

          return jsonResponse({
            message: conflictMsg,
            conflicts: list,
            canOverride: payload.category === 'PLACEMENT'
          }, 409);
        }
      }

      // Propose logic status
      let status = "REQUESTED";
      if (proposer.role === 'PRINCIPAL') {
        status = "APPROVED";
      } else if (
        proposer.role === 'HOD' || 
        payload.category === 'CLUB' || 
        payload.category === 'PLACEMENT' || 
        payload.category === 'INSTITUTIONAL' ||
        proposer.role === 'PLACEMENT' ||
        proposer.isPlacementStaff ||
        proposer.department === 'Placement Department'
      ) {
        status = "PENDING_PR";
      }

      const budgetStr = payload.budget ? String(payload.budget) : "";
      const feeStr = payload.registrationFee ? String(payload.registrationFee) : "";

      const event = {
        id: generateNumericId(),
        title: payload.eventName || "Untitled Event",
        description: payload.description || "",
        startDate: start.toISOString(),
        endDate: end.toISOString(),
        location: String(payload.venue || "TBD").trim(),
        category: payload.category || "ACADEMIC",
        type: payload.eventType || "Institutional",
        institution: String(payload.institution || "RIT").trim(),
        department: payload.department || "General",
        academicYears: payload.academicYears || [],
        status: status,
        guestName: payload.guestName || null,
        guestSocialProfile: payload.socialProfile || null,
        requirements: payload.requirements || [],
        targetedSections: payload.targetedSections || [],
        targetDepartments: payload.targetDepartments || [],
        groupRequestId: payload.groupRequestId || null,
        sponsors: payload.sponsors || [],
        budget: budgetStr === "" ? 0.0 : parseFloat(budgetStr),
        hasRegistrationFee: !!payload.hasRegistrationFee,
        registrationFee: feeStr === "" ? 0.0 : parseFloat(feeStr),
        paymentLink: payload.paymentLink || null,
        centreName: payload.centreName || null,
        isPublicEvent: !!payload.isPublicEvent,
        image: payload.image || null,
        targetedBatch: payload.targetedBatch || null,
        openToAll: !!payload.openToAll,
        "total capacity": payload.maxParticipants === '' || payload.maxParticipants === undefined ? null : Number(payload.maxParticipants),
        maxParticipants: payload.maxParticipants === '' || payload.maxParticipants === undefined ? null : Number(payload.maxParticipants),
        proposer: {
          id: proposer.id,
          fullName: proposer.fullName,
          email: proposer.email,
          role: proposer.role,
          department: proposer.department || "N/A"
        },
        dayConfigs: payload.dayConfigs || [],
        deptLimits: payload.deptLimits || {},
        deptSectionLimits: payload.deptSectionLimits || {},
        refreshment_expense: payload.refreshment_expense ? parseFloat(String(payload.refreshment_expense)) : 0.0,
        transportation_expense: payload.transportation_expense ? parseFloat(String(payload.transportation_expense)) : 0.0,
        session_coverage_fee: payload.session_coverage_fee ? parseFloat(String(payload.session_coverage_fee)) : 0.0,
        total_expense: payload.total_expense ? parseFloat(String(payload.total_expense)) : 0.0,
        durationDays: payload.durationDays ? Number(payload.durationDays) : 1
      };

      await setDoc(doc(db, 'ems_events', String(event.id)), event);
      return jsonResponse({ message: "Event proposed successfully", id: event.id });
    }

    if (path === '/api/events/batch-create' && method === 'POST') {
      const batchList = parseBody(init?.body);
      const eventsToSave: any[] = [];

      for (const payload of batchList) {
        const title = payload.title || "Untitled Event";
        const dateObj = payload.startDate || payload.finalDate;
        if (!dateObj) {
          return jsonResponse({ message: `Missing date for event: ${title}` }, 400);
        }

        const start = parseDate(dateObj);
        let end;
        if (payload.startDate && payload.endDate) {
          try {
            const origStart = parseDate(payload.startDate);
            const origEnd = parseDate(payload.endDate);
            const durationMs = origEnd.getTime() - origStart.getTime();
            end = new Date(start.getTime() + durationMs);
          } catch {
            end = new Date(start.getTime() + 2 * 60 * 60 * 1000);
          }
        } else {
          end = new Date(start.getTime() + 2 * 60 * 60 * 1000);
        }

        if (end <= start) {
          return jsonResponse({ message: `End date must be after start date for event: ${title}` }, 400);
        }

        const dept = payload.targetDepartment || payload.department || "General";
        const ay = payload.targetBatch ? [payload.targetBatch] : (payload.academicYears || []);
        const venue = payload.venue || payload.location || "TBD";

        let proposer = { id: 1, fullName: "Admin", email: "admin@rit.edu", role: "ADMIN", department: "ADMIN" };
        if (payload.proposer && payload.proposer.id) {
          const userSnap = await getDoc(doc(db, 'ems_users', String(payload.proposer.id)));
          if (userSnap.exists()) {
            const u = userSnap.data();
            proposer = {
              id: u.id,
              fullName: u.fullName,
              email: u.email,
              role: u.role,
              department: u.department || "N/A"
            };
          }
        } else if (payload.proposer) {
          proposer = { ...proposer, ...payload.proposer };
        }

        const event = {
          id: generateNumericId(),
          title,
          description: payload.description || "",
          startDate: start.toISOString(),
          endDate: end.toISOString(),
          location: String(venue).trim(),
          category: payload.category || "ACADEMIC",
          type: payload.type || "Seminar",
          institution: String(payload.institution || "RIT").trim(),
          department: dept,
          academicYears: ay,
          status: payload.status || "APPROVED",
          requirements: payload.requirements || [],
          image: payload.image || null,
          proposer,
          openToAll: !!payload.openToAll
        };

        const conflictMsg = await getConflictMessage(event);
        if (conflictMsg) {
          return jsonResponse({ message: `Conflict in batch item '${title}': ${conflictMsg}` }, 400);
        }

        eventsToSave.push(event);
      }

      // Check intra-batch conflicts
      for (let i = 0; i < eventsToSave.length; i++) {
        const current = eventsToSave[i];
        const currentStart = parseDate(current.startDate);
        const currentEnd = parseDate(current.endDate);
        const currentLoc = current.location.toLowerCase();

        for (let j = i + 1; j < eventsToSave.length; j++) {
          const other = eventsToSave[j];
          const otherStart = parseDate(other.startDate);
          const otherEnd = parseDate(other.endDate);
          const otherLoc = other.location.toLowerCase();

          if (
            current.institution === other.institution &&
            currentLoc === otherLoc &&
            currentStart < otherEnd &&
            currentEnd > otherStart
          ) {
            return jsonResponse({ message: `Conflict between imported events '${current.title}' and '${other.title}' at ${current.location}` }, 400);
          }
        }
      }

      for (const ev of eventsToSave) {
        await setDoc(doc(db, 'ems_events', String(ev.id)), ev);
      }
      return jsonResponse({ message: "Batch events created successfully", count: eventsToSave.length });
    }

    if (path.endsWith('/approve') && method === 'POST') {
      const parts = path.split('/');
      const id = parts[parts.length - 2];
      const userId = queryParams.get('userId');
      const newVenue = queryParams.get('newVenue');

      const userSnap = await getDoc(doc(db, 'ems_users', String(userId)));
      const eventRef = doc(db, 'ems_events', String(id));
      const eventSnap = await getDoc(eventRef);

      if (!userSnap.exists() || !eventSnap.exists()) {
        return jsonResponse({ message: "User or Event not found" }, 400);
      }

      const user = userSnap.data();
      const event = { ...eventSnap.data() };

      if (newVenue) {
        await updateDoc(eventRef, { location: newVenue });
        event.location = newVenue;
      }

      const conflictMsg = await getConflictMessage(event, id);
      if (conflictMsg) {
        return jsonResponse({ message: conflictMsg }, 409);
      }

      let newStatus = event.status;
      if (user.role === 'HOD') {
        newStatus = 'PENDING_PR';
      } else if (user.role === 'PRINCIPAL') {
        newStatus = 'APPROVED';
      } else {
        return jsonResponse({ message: "Only HoD or Principal can approve events" }, 403);
      }

      await updateDoc(eventRef, { status: newStatus });
      return jsonResponse({ message: "Event action completed successfully", status: newStatus });
    }

    if (path.endsWith('/reject') && method === 'POST') {
      const parts = path.split('/');
      const id = parts[parts.length - 2];
      const userId = queryParams.get('userId');
      const { reason } = parseBody(init?.body);

      if (!reason || reason.trim() === '') {
        return jsonResponse({ message: "Rejection reason is mandatory" }, 400);
      }

      const userSnap = await getDoc(doc(db, 'ems_users', String(userId)));
      const eventRef = doc(db, 'ems_events', String(id));
      const eventSnap = await getDoc(eventRef);

      if (!userSnap.exists() || !eventSnap.exists()) {
        return jsonResponse({ message: "User or Event not found" }, 400);
      }

      const user = userSnap.data();
      let newStatus = eventSnap.data().status;

      if (user.role === 'HOD') {
        newStatus = 'HOD_REJECTED';
      } else if (user.role === 'PRINCIPAL') {
        newStatus = 'PRINCIPAL_REJECTED';
      } else {
        return jsonResponse({ message: "Only HoD or Principal can reject events" }, 403);
      }

      await updateDoc(eventRef, { status: newStatus, rejectionReason: reason });
      return jsonResponse({ message: "Event rejected successfully", status: newStatus });
    }

    if (path.startsWith('/api/events/') && method === 'PUT') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      const payload = parseBody(init?.body);

      const eventRef = doc(db, 'ems_events', String(id));
      const eventSnap = await getDoc(eventRef);

      if (!eventSnap.exists()) {
        return jsonResponse({ message: "Event not found" }, 404);
      }

      const event = eventSnap.data();
      const userId = payload.userId;
      const userSnap = await getDoc(doc(db, 'ems_users', String(userId)));

      if (!userSnap.exists()) {
        return jsonResponse({ message: "User not found" }, 400);
      }

      const user = userSnap.data();
      const isAdmin = user.role === 'ADMIN';

      if (!isAdmin) {
        if (String(event.proposer?.id) !== String(userId)) {
          return jsonResponse({ message: "Only the proposer can edit this event" }, 403);
        }
        if (event.status !== 'REQUESTED') {
          return jsonResponse({ message: "Event cannot be edited once it moves past the initial request stage" }, 403);
        }
      }

      const start = payload.startDate ? parseDate(payload.startDate) : parseDate(event.startDate);
      const end = payload.endDate ? parseDate(payload.endDate) : parseDate(event.endDate);

      if (end <= start) {
        return jsonResponse({ message: "End date must be after start date" }, 400);
      }

      const testEvent = {
        ...event,
        ...payload,
        startDate: start.toISOString(),
        endDate: end.toISOString()
      };

      const conflictMsg = await getConflictMessage(testEvent, id);
      if (conflictMsg) {
        return jsonResponse({ message: conflictMsg }, 409);
      }

      const updatedFields: any = {};
      if (payload.title !== undefined) updatedFields.title = payload.title;
      if (payload.startDate !== undefined) updatedFields.startDate = start.toISOString();
      if (payload.endDate !== undefined) updatedFields.endDate = end.toISOString();
      if (payload.eventType !== undefined) updatedFields.type = payload.eventType;
      if (payload.institution !== undefined) updatedFields.institution = payload.institution;
      if (payload.department !== undefined) updatedFields.department = payload.department;
      if (payload.venue !== undefined) updatedFields.location = payload.venue;
      if (payload.category !== undefined) updatedFields.category = payload.category;
      if (payload.maxParticipants !== undefined) {
        const val = payload.maxParticipants === '' ? null : Number(payload.maxParticipants);
        updatedFields["total capacity"] = val;
        updatedFields.maxParticipants = val;
      }
      if (payload.guestName !== undefined) updatedFields.guestName = payload.guestName;
      if (payload.socialProfile !== undefined) updatedFields.guestSocialProfile = payload.socialProfile;
      if (payload.academicYears !== undefined) updatedFields.academicYears = payload.academicYears;
      if (payload.targetedSections !== undefined) updatedFields.targetedSections = payload.targetedSections;
      if (payload.requirements !== undefined) updatedFields.requirements = payload.requirements;
      if (payload.sponsors !== undefined) updatedFields.sponsors = payload.sponsors;
      if (payload.description !== undefined) updatedFields.description = payload.description;
      if (payload.budget !== undefined) {
        const b = String(payload.budget);
        updatedFields.budget = b === "" ? 0.0 : parseFloat(b);
      }
      if (payload.hasRegistrationFee !== undefined) updatedFields.hasRegistrationFee = !!payload.hasRegistrationFee;
      if (payload.registrationFee !== undefined) {
        const f = String(payload.registrationFee);
        updatedFields.registrationFee = f === "" ? 0.0 : parseFloat(f);
      }
      if (payload.centreName !== undefined) updatedFields.centreName = payload.centreName;
      if (payload.isPublicEvent !== undefined) updatedFields.isPublicEvent = !!payload.isPublicEvent;
      if (payload.image !== undefined) updatedFields.image = payload.image;
      if (payload.openToAll !== undefined) updatedFields.openToAll = !!payload.openToAll;
      if (payload.targetedBatch !== undefined) updatedFields.targetedBatch = payload.targetedBatch;
      if (payload.dayConfigs !== undefined) updatedFields.dayConfigs = payload.dayConfigs;
      if (payload.deptLimits !== undefined) updatedFields.deptLimits = payload.deptLimits;
      if (payload.deptSectionLimits !== undefined) updatedFields.deptSectionLimits = payload.deptSectionLimits;
      if (payload.refreshment_expense !== undefined) updatedFields.refreshment_expense = parseFloat(String(payload.refreshment_expense)) || 0;
      if (payload.transportation_expense !== undefined) updatedFields.transportation_expense = parseFloat(String(payload.transportation_expense)) || 0;
      if (payload.session_coverage_fee !== undefined) updatedFields.session_coverage_fee = parseFloat(String(payload.session_coverage_fee)) || 0;
      if (payload.total_expense !== undefined) updatedFields.total_expense = parseFloat(String(payload.total_expense)) || 0;
      if (payload.durationDays !== undefined) updatedFields.durationDays = Number(payload.durationDays) || 1;
      if (payload.status !== undefined && isAdmin) {
        updatedFields.status = payload.status;
      }

      await updateDoc(eventRef, updatedFields);
      return jsonResponse({ message: "Event updated successfully" });
    }

    if (path.startsWith('/api/events/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_events', String(id)));
      return jsonResponse({ message: "Event deleted successfully" });
    }

    // ----------------------------------------------------
    // STUDENT SIGNUP
    // ----------------------------------------------------
    if (path === '/api/auth/signup' && method === 'POST') {
      const payload = parseBody(init?.body);
      const email = payload.email?.trim().toLowerCase();
      
      const snap = await getDocs(collection(db, 'ems_users'));
      if (snap.docs.some(d => d.data().email?.toLowerCase() === email)) {
        return jsonResponse({ message: "A user with this email already exists" }, 400);
      }

      const id = generateNumericId();
      const isRitEmail = email.includes('@ritchennai.edu.in') || email.includes('.ritchennai.edu.in');
      const newUser = {
        ...payload,
        id,
        email,
        role: 'STUDENT',
        department: payload.department || 'CSE',
        year: payload.year || '1st Year',
        section: payload.section || 'A',
        regNo: payload.regNo || '',
        phone: payload.phone || '',
        gender: payload.gender || 'Male',
        collegeName: isRitEmail ? 'Rajalakshmi Institute of Technology' : (payload.collegeName || 'External Institution')
      };

      await setDoc(doc(db, 'ems_users', String(id)), newUser);
      // Return user without password
      const { password: _, ...userData } = newUser;
      return jsonResponse(userData);
    }

    // ----------------------------------------------------
    // REGISTRATIONS CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/registrations' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_registrations'));
      let list = snap.docs.map(d => d.data());

      // Filter by query parameters if any
      const filterUserId = queryParams.get('userId') || queryParams.get('user_id');
      const filterEventId = queryParams.get('eventId') || queryParams.get('event_id');
      const filterTeamCode = queryParams.get('teamCode') || queryParams.get('team_code');

      if (filterUserId) {
        list = list.filter(r => String(r.userId || r.user_id) === String(filterUserId));
      }
      if (filterEventId) {
        list = list.filter(r => String(r.eventId || r.event_id) === String(filterEventId));
      }
      if (filterTeamCode) {
        list = list.filter(r => String(r.teamCode || r.team_code) === String(filterTeamCode));
      }

      return jsonResponse(list);
    }

    if (path === '/api/registrations' && method === 'POST') {
      const payload = parseBody(init?.body);
      const userId = payload.userId || payload.user_id;
      const eventId = payload.eventId || payload.event_id;

      if (!userId || !eventId) {
        return jsonResponse({ message: "userId and eventId are required" }, 400);
      }

      const regId = `${userId}_${eventId}`;
      const regDocRef = doc(db, 'ems_registrations', regId);
      const regSnap = await getDoc(regDocRef);

      if (regSnap.exists()) {
        return jsonResponse({ message: "You are already registered for this event." }, 400);
      }

      const eventSnap = await getDoc(doc(db, 'ems_events', String(eventId)));
      if (!eventSnap.exists()) {
        return jsonResponse({ message: "Event not found" }, 404);
      }
      const event = eventSnap.data();

      if (event.endDate) {
        const deadline = new Date(event.registrationFee ? (event.registrationDeadline || event.endDate) : event.endDate);
        if (new Date() > deadline) {
          return jsonResponse({ message: "Registration Blocked: The deadline for this event has passed." }, 400);
        }
      }

      const allRegsSnap = await getDocs(collection(db, 'ems_registrations'));
      const eventRegs = allRegsSnap.docs.map(d => d.data()).filter(r => String(r.eventId || r.event_id) === String(eventId));
      const currentParticipants = eventRegs.length;

      if (event.maxParticipants && currentParticipants >= event.maxParticipants) {
        return jsonResponse({ message: "Registration Blocked: The event has reached its capacity." }, 409);
      }

      const studentDept = payload.dept || payload.department || 'CSE';
      const studentSec = payload.section || 'A';

      if (event.deptLimits && Object.keys(event.deptLimits).length > 0) {
        if (event.deptLimits[studentDept] === undefined) {
          return jsonResponse({ message: `Registration Blocked: Department ${studentDept} is not permitted to register.` }, 409);
        }

        const deptLimit = Number(event.deptLimits[studentDept]);
        const deptRegs = eventRegs.filter(r => (r.dept || r.department) === studentDept);

        if (event.deptSectionLimits && event.deptSectionLimits[studentDept] && Object.keys(event.deptSectionLimits[studentDept]).length > 0) {
          const sectionLimits = event.deptSectionLimits[studentDept];
          if (sectionLimits[studentSec] === undefined) {
            return jsonResponse({ message: `Registration Blocked: Section ${studentSec} of ${studentDept} is not permitted to register.` }, 409);
          }
          const sectionLimit = Number(sectionLimits[studentSec] || 0);
          
          if (sectionLimit <= 0) {
            return jsonResponse({ message: `Registration Blocked: Section ${studentSec} of ${studentDept} is not permitted to register.` }, 409);
          }

          const secRegs = deptRegs.filter(r => r.section === studentSec);
          if (secRegs.length >= sectionLimit) {
            return jsonResponse({ message: `Registration Blocked: Quota for Section ${studentSec} of ${studentDept} is full.` }, 409);
          }
        } else {
          if (deptRegs.length >= deptLimit) {
            return jsonResponse({ message: `Registration Blocked: Quota for department ${studentDept} is full.` }, 409);
          }
        }
      }

      const { image, ...registrationData } = payload;
      const isFree = event.hasRegistrationFee === false || event.registrationFee === 0 || event.pricingType === 'FREE';
      const newReg = {
        ...registrationData,
        id: regId,
        userId,
        user_id: userId,
        eventId,
        event_id: eventId,
        paymentStatus: isFree ? 'COMPLETED' : 'PENDING',
        payment_status: isFree ? 'COMPLETED' : 'PENDING',
        certificationStatus: 'NOT_SUBMITTED',
        certification_status: 'NOT_SUBMITTED',
        registeredAt: new Date().toISOString(),
        registered_at: new Date().toISOString()
      };

      await setDoc(regDocRef, newReg);
      const eventDocRef = doc(db, 'ems_events', String(eventId));
      await updateDoc(eventDocRef, { currentParticipants: currentParticipants + 1 });

      return jsonResponse(newReg);
    }

    if (path.startsWith('/api/registrations/') && method === 'PUT') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      const payload = parseBody(init?.body);

      const regRef = doc(db, 'ems_registrations', String(id));
      const snap = await getDoc(regRef);

      if (!snap.exists()) {
        return jsonResponse({ message: "Registration not found" }, 404);
      }

      // Map incoming keys to support both camelCase and snake_case
      const updatedFields: any = { ...snap.data(), ...payload };
      if (payload.payment_status !== undefined) updatedFields.paymentStatus = payload.payment_status;
      if (payload.paymentStatus !== undefined) updatedFields.payment_status = payload.paymentStatus;
      
      if (payload.team_code !== undefined) updatedFields.teamCode = payload.team_code;
      if (payload.teamCode !== undefined) updatedFields.team_code = payload.teamCode;
      
      if (payload.team_name !== undefined) updatedFields.teamName = payload.team_name;
      if (payload.teamName !== undefined) updatedFields.team_name = payload.teamName;
      
      if (payload.is_team_leader !== undefined) updatedFields.isTeamLeader = payload.is_team_leader;
      if (payload.isTeamLeader !== undefined) updatedFields.is_team_leader = payload.isTeamLeader;

      if (payload.certification_url !== undefined) updatedFields.certificationUrl = payload.certification_url;
      if (payload.certificationUrl !== undefined) updatedFields.certification_url = payload.certificationUrl;

      if (payload.certification_status !== undefined) updatedFields.certificationStatus = payload.certification_status;
      if (payload.certificationStatus !== undefined) updatedFields.certification_status = payload.certificationStatus;

      if (payload.od_url !== undefined) updatedFields.odUrl = payload.od_url;
      if (payload.odUrl !== undefined) updatedFields.od_url = payload.odUrl;

      if (payload.ticket_id !== undefined) updatedFields.ticketId = payload.ticket_id;
      if (payload.ticketId !== undefined) updatedFields.ticket_id = payload.ticketId;

      if (payload.ticket_qrcode !== undefined) updatedFields.ticketQrcode = payload.ticket_qrcode;
      if (payload.ticketQrcode !== undefined) updatedFields.ticket_qrcode = payload.ticketQrcode;

      await setDoc(regRef, updatedFields);
      return jsonResponse({ message: "Registration updated successfully", data: updatedFields });
    }

    if (path.startsWith('/api/registrations/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      const regRef = doc(db, 'ems_registrations', String(id));
      const regSnap = await getDoc(regRef);

      if (regSnap.exists()) {
        const regData = regSnap.data();
        const eventId = regData.eventId || regData.event_id;

        await deleteDoc(regRef);

        if (eventId) {
          const allRegsSnap = await getDocs(collection(db, 'ems_registrations'));
          const eventRegs = allRegsSnap.docs.map(d => d.data()).filter(r => String(r.eventId || r.event_id) === String(eventId));
          const currentParticipants = eventRegs.length;

          await updateDoc(doc(db, 'ems_events', String(eventId)), { currentParticipants });
        }
      } else {
        await deleteDoc(regRef);
      }

      return jsonResponse({ message: "Registration deleted successfully" });
    }

    // ----------------------------------------------------
    // ATTENDANCE CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/attendance' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_attendance'));
      let list = snap.docs.map(d => d.data());

      const regId = queryParams.get('registrationId') || queryParams.get('registration_id');
      const eventId = queryParams.get('eventId') || queryParams.get('event_id');

      if (regId) {
        list = list.filter(a => String(a.registrationId || a.registration_id) === String(regId));
      }
      if (eventId) {
        list = list.filter(a => String(a.eventId || a.event_id) === String(eventId));
      }

      return jsonResponse(list);
    }

    if (path === '/api/attendance' && method === 'POST') {
      const payload = parseBody(init?.body);
      const records = Array.isArray(payload) ? payload : [payload];

      for (const rec of records) {
        const regId = rec.registrationId || rec.registration_id;
        const day = rec.dayLabel || rec.day_idx || "Day 1";
        const slot = rec.batchLabel || rec.batch_idx || "Batch 1";
        const id = `${regId}_${day}_${slot}`;

        const docRef = doc(db, 'ems_attendance', id);
        await setDoc(docRef, {
          id,
          registrationId: regId,
          registration_id: regId,
          eventId: rec.eventId || rec.event_id,
          event_id: rec.eventId || rec.event_id,
          dayLabel: day,
          day_idx: day,
          batchLabel: slot,
          batch_idx: slot,
          isPresent: !!rec.isPresent,
          is_present: !!rec.isPresent,
          date: rec.date || new Date().toLocaleDateString()
        });
      }
      return jsonResponse({ message: "Attendance updated successfully" });
    }

    // ----------------------------------------------------
    // SETTINGS CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/settings' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_settings'));
      const settings: Record<string, any> = {};
      snap.docs.forEach(d => {
        settings[d.id] = d.data();
      });
      return jsonResponse(settings);
    }

    if (path === '/api/settings' && method === 'POST') {
      const payload = parseBody(init?.body);
      const { key, value } = payload;
      if (key) {
        await setDoc(doc(db, 'ems_settings', key), value);
      }
      return jsonResponse({ message: "Settings saved successfully" });
    }

    // ----------------------------------------------------
    // SPECIAL EVENTS CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/special-events' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_special_events'));
      const list = snap.docs.map(d => d.data());
      list.sort((a, b) => new Date(b.created_at || 0).getTime() - new Date(a.created_at || 0).getTime());
      return jsonResponse(list);
    }

    if (path === '/api/special-events' && method === 'POST') {
      const payload = parseBody(init?.body);
      const id = payload.id || String(generateNumericId());
      const newSE = {
        ...payload,
        id,
        created_at: payload.created_at || new Date().toISOString(),
        is_active: payload.is_active !== undefined ? !!payload.is_active : true,
        verificationStatus: payload.verificationStatus || 'APPROVED'
      };
      await setDoc(doc(db, 'ems_special_events', id), newSE);
      return jsonResponse(newSE);
    }

    if (path.startsWith('/api/special-events/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_special_events', String(id)));
      return jsonResponse({ message: "Special event deleted successfully" });
    }

    // ----------------------------------------------------
    // ANNOUNCEMENTS CONTROLLER
    // ----------------------------------------------------
    if (path === '/api/announcements' && method === 'GET') {
      const snap = await getDocs(collection(db, 'ems_announcements'));
      const list = snap.docs.map(d => d.data());
      list.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
      return jsonResponse(list);
    }

    if (path === '/api/announcements' && method === 'POST') {
      const payload = parseBody(init?.body);
      const id = String(generateNumericId());
      const newAnn = {
        ...payload,
        id,
        timestamp: new Date().toISOString()
      };
      await setDoc(doc(db, 'ems_announcements', id), newAnn);
      return jsonResponse(newAnn);
    }

    if (path.startsWith('/api/announcements/') && method === 'DELETE') {
      const parts = path.split('/');
      const id = parts[parts.length - 1];
      await deleteDoc(doc(db, 'ems_announcements', String(id)));
      return jsonResponse({ message: "Announcement deleted successfully" });
    }
  } catch (err: any) {
    console.error(`Interceptor routing error:`, err);
    return jsonResponse({ message: "Internal server error: " + err.message }, 500);
  }

  // Fallback to original fetch
  return originalFetch(input, init);
};

console.log("[Firebase Backend] Fetch interceptor active.");
