import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import { 
  Upload, 
  FileSpreadsheet, 
  CheckCircle2, 
  AlertCircle, 
  ArrowRight, 
  Search,
  X,
  AlertTriangle,
  Loader2,
  UserPlus,
  UserCheck,
  ChevronDown,
  Zap,
  Clock,
  MapPin
} from 'lucide-react';
import { API_BASE_URL } from '../../lib/config';
import { cn } from '../../lib/utils';
import { Pagination } from './Pagination';

const DEPARTMENTS = [
  'AI&DS', 'AI&ML', 'CSE', 'CCE', 'CSBS', 'ECE', 'MECH', 'EE(VLSI)', 'BIOTECH', 'Placement Department', 'H&S Dept', 'PGDM'
];

interface ExcelRow {
  [key: string]: any;
  Timestamp: any;
  'Date of the event (start date)': any;
  'Date of the event (End date)': any;
  'starting Time': any;
  'ending Time': any;
  Venue: string;
  Department: string;
  'Requirements [Row 1]': string;
  'Name of the event': string;
  'Name of the faculty coordinator': string;
  'Name of the Guest': string;
  'Any Other Requirements, Please mention'?: string;
  Status?: string;
}

interface ParsedEvent {
  id: string;
  title: string;
  guestName?: string;
  startDate: string;
  endDate: string;
  venue: string;
  department: string;
  requirements: string[];
  status: 'APPROVED' | 'REQUESTED';
  conflict?: string;
  proposerName: string;
  proposerEmail?: string;
  proposerId?: number;
  proposerExists: boolean;
  originalData: any;
}

interface ConflictInfo {
  title: string;
  venue: string;
  startDate: string;
  endDate: string;
  source: 'database' | 'batch';
}

interface ProposedResolution {
  eventId: string;
  title: string;
  oldVenue: string;
  newVenue: string;
  oldStartDate: string;
  oldEndDate: string;
  newStartDate: string;
  newEndDate: string;
  conflictWith: string;
  reason: string;
  fixType: 'venue' | 'time' | 'manual';
}

export const ExcelImport: React.FC = () => {
  const [isParsing, setIsParsing] = useState(false);
  const [events, setEvents] = useState<ParsedEvent[]>([]);
  const [existingEvents, setExistingEvents] = useState<any[]>([]);
  const [users, setUsers] = useState<any[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [importStatus, setImportStatus] = useState<{ success: boolean; message: string } | null>(null);

  const [venues, setVenues] = useState<string[]>([
    'GB 4th floor auditorium',
    'Wozniak Auditorium',
    'C6-02 Indoor Theatre',
    'H Block Guest Lecture Theatre',
    'Steve Jobs Computer Centre 1',
    'Steve Jobs Computer Centre 2',
    'Others.'
  ]);

  // Resolution state
  const [proposedResolutions, setProposedResolutions] = useState<ProposedResolution[]>([]);
  const [isResolutionReviewOpen, setIsResolutionReviewOpen] = useState(false);
  const [appliedFixes, setAppliedFixes] = useState<ProposedResolution[]>([]);

  // Search and Pagination state
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPageAttention, setCurrentPageAttention] = useState(1);
  const [currentPageReady, setCurrentPageReady] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  useEffect(() => {
    fetchInitialData();
  }, []);

  useEffect(() => {
    setCurrentPageAttention(1);
    setCurrentPageReady(1);
  }, [searchQuery]);

  const fetchInitialData = async () => {
    try {
      const [eventsRes, usersRes, venuesRes] = await Promise.all([
        fetch(`${API_BASE_URL}/api/events`),
        fetch(`${API_BASE_URL}/api/admin/users`),
        fetch(`${API_BASE_URL}/api/venues`)
      ]);
      if (eventsRes.ok) setExistingEvents(await eventsRes.json());
      if (usersRes.ok) setUsers(await usersRes.json());
      if (venuesRes.ok) {
        const venueData = await venuesRes.json();
        setVenues([...venueData.map((v: any) => v.name), 'Others.']);
      }
    } catch (err) {
      console.error('Failed to fetch initial data:', err);
    }
  };

  const mapVenue = (v: string) => {
    const val = v?.toLowerCase() || '';
    const match = venues.find(vn => {
      if (vn === 'Others.') return false;
      return val.includes(vn.toLowerCase()) || vn.toLowerCase().includes(val);
    });
    if (match) return match;

    if (val.includes('wozniak')) return 'Wozniak Auditorium';
    if (val.includes('gb 4th') || val.includes('auditorium')) return 'GB 4th floor auditorium';
    if (val.includes('c6-02')) return 'C6-02 Indoor Theatre';
    if (val.includes('h block')) return 'H Block Guest Lecture Theatre';
    if (val.includes('steve jobs') && (val.includes('1') || val.includes('1st'))) return 'Steve Jobs Computer Centre 1';
    if (val.includes('steve jobs') && (val.includes('2') || val.includes('2nd'))) return 'Steve Jobs Computer Centre 2';
    return 'Others.';
  };

  const normalizeVenue = (venue?: string) => (venue || '').trim().toLowerCase();

  const overlaps = (aStart: Date, aEnd: Date, bStart: Date, bEnd: Date) => (
    aStart < bEnd && aEnd > bStart
  );

  const getDurationMs = (event: { startDate: string, endDate: string }) => {
    const duration = new Date(event.endDate).getTime() - new Date(event.startDate).getTime();
    return duration > 0 ? duration : 2 * 60 * 60 * 1000;
  };

  const toConflictInfo = (event: any, source: 'database' | 'batch'): ConflictInfo => ({
    title: event.title || 'Untitled Event',
    venue: event.location || event.venue || 'TBD',
    startDate: event.startDate,
    endDate: event.endDate,
    source
  });

  const getEventConflict = (
    event: { startDate: string, endDate: string, venue: string, id?: string },
    batch: ParsedEvent[] = events
  ): ConflictInfo | null => {
    const start = new Date(event.startDate);
    const end = new Date(event.endDate);
    const location = normalizeVenue(event.venue);
    
    const dbConflict = existingEvents.find(e => {
      const eStart = new Date(e.startDate);
      const eEnd = new Date(e.endDate);
      return normalizeVenue(e.location) === location && overlaps(start, end, eStart, eEnd) && e.status !== 'CANCELLED';
    });
    if (dbConflict) return toConflictInfo(dbConflict, 'database');

    const batchConflict = batch.find(e => {
      if (e.id === event.id) return false;
      const eStart = new Date(e.startDate);
      const eEnd = new Date(e.endDate);
      return normalizeVenue(e.venue) === location && overlaps(start, end, eStart, eEnd);
    });

    return batchConflict ? toConflictInfo(batchConflict, 'batch') : null;
  };

  const findAlternativeVenue = (event: ParsedEvent, currentBatch: ParsedEvent[]) => {
    const start = new Date(event.startDate);
    const end = new Date(event.endDate);
    
    return venues.find(v => {
      if (v === event.venue || v === 'Others.') return false;
      
      // Check DB
      const hasDbConflict = existingEvents.some(e => {
        const eStart = new Date(e.startDate);
        const eEnd = new Date(e.endDate);
        return normalizeVenue(e.location) === normalizeVenue(v) && overlaps(start, end, eStart, eEnd) && e.status !== 'CANCELLED';
      });
      if (hasDbConflict) return false;

      // Check Batch
      const hasBatchConflict = currentBatch.some(e => {
        if (e.id === event.id) return false;
        const eStart = new Date(e.startDate);
        const eEnd = new Date(e.endDate);
        return normalizeVenue(e.venue) === normalizeVenue(v) && overlaps(start, end, eStart, eEnd);
      });
      return !hasBatchConflict;
    });
  };

  const findNextAvailableTime = (event: ParsedEvent, currentBatch: ParsedEvent[]) => {
    const duration = getDurationMs(event);
    let nextStart = new Date(event.startDate);

    for (let attempt = 0; attempt < 48; attempt++) {
      const nextEnd = new Date(nextStart.getTime() + duration);
      const blockingEvents = [
        ...existingEvents
          .filter(e => e.status !== 'CANCELLED' && normalizeVenue(e.location) === normalizeVenue(event.venue))
          .map(e => toConflictInfo(e, 'database')),
        ...currentBatch
          .filter(e => e.id !== event.id && normalizeVenue(e.venue) === normalizeVenue(event.venue))
          .map(e => toConflictInfo(e, 'batch'))
      ].filter(e => overlaps(nextStart, nextEnd, new Date(e.startDate), new Date(e.endDate)));

      if (blockingEvents.length === 0) {
        return {
          startDate: nextStart.toISOString(),
          endDate: nextEnd.toISOString()
        };
      }

      const latestEnd = Math.max(...blockingEvents.map(e => new Date(e.endDate).getTime()));
      nextStart = new Date(latestEnd + 15 * 60 * 1000);
    }

    return null;
  };

  const buildResolutionPlan = (sourceEvents: ParsedEvent[]) => {
    const sortedEvents = [...sourceEvents].sort((a, b) => {
      const venueCompare = a.venue.localeCompare(b.venue);
      if (venueCompare !== 0) return venueCompare;
      return new Date(a.startDate).getTime() - new Date(b.startDate).getTime();
    });
    let acceptedBatch: ParsedEvent[] = [];
    const fixes: ProposedResolution[] = [];

    for (const event of sortedEvents) {
      const conflict = getEventConflict(event, acceptedBatch);
      if (!conflict) {
        acceptedBatch = [...acceptedBatch, event];
        continue;
      }

      const oldVenue = event.venue;
      const oldStartDate = event.startDate;
      const oldEndDate = event.endDate;
      const alternativeVenue = findAlternativeVenue(event, acceptedBatch);

      let updated: ParsedEvent | null = null;
      let fixType: ProposedResolution['fixType'] = 'manual';
      let reason = `${conflict.source === 'database' ? 'Database' : 'Imported batch'} conflict with "${conflict.title}"`;

      if (alternativeVenue) {
        updated = { ...event, venue: alternativeVenue };
        fixType = 'venue';
        reason = `${reason}; moved to an available venue.`;
      } else {
        const nextSlot = findNextAvailableTime(event, acceptedBatch);
        if (nextSlot) {
          updated = { ...event, startDate: nextSlot.startDate, endDate: nextSlot.endDate };
          fixType = 'time';
          reason = `${reason}; shifted to the next available slot at the same venue.`;
        }
      }

      if (updated) {
        acceptedBatch = [...acceptedBatch, updated];
      } else {
        acceptedBatch = [...acceptedBatch, event];
      }

      fixes.push({
        eventId: event.id,
        title: event.title,
        oldVenue,
        newVenue: updated?.venue || oldVenue,
        oldStartDate,
        oldEndDate,
        newStartDate: updated?.startDate || oldStartDate,
        newEndDate: updated?.endDate || oldEndDate,
        conflictWith: conflict.title,
        reason: updated ? reason : `${reason}; no automatic venue or time slot was available.`,
        fixType
      });
    }

    return fixes.sort((a, b) => {
      const venueCompare = a.oldVenue.localeCompare(b.oldVenue);
      if (venueCompare !== 0) return venueCompare;
      return new Date(a.oldStartDate).getTime() - new Date(b.oldStartDate).getTime();
    });
  };

  const mapDepartment = (d: string) => {
    const val = d?.toLowerCase() || '';
    if (val.includes('placement')) return 'Placement Department';
    if (val.includes('mech')) return 'MECH';
    if (val.includes('cse')) return 'CSE';
    if (val.includes('ai&ds') || val.includes('ai & ds') || val.includes('data science')) return 'AI&DS';
    if (val.includes('ai&ml') || val.includes('ai & ml') || val.includes('machine learning')) return 'AI&ML';
    if (val.includes('ece') || val.includes('electronics')) return 'ECE';
    if (val.includes('cce')) return 'CCE';
    if (val.includes('csbs')) return 'CSBS';
    if (val.includes('biotech')) return 'BIOTECH';
    if (val.includes('vlsi')) return 'EE(VLSI)';
    if (val.includes('h&s') || val.includes('humanities')) return 'H&S Dept';
    if (val.includes('rsb') || val.includes('pgdm')) return 'PGDM';
    return 'H&S Dept'; // Default
  };

  const parseRequirements = (reqStr: string, otherReqStr?: string) => {
    const combined = `${reqStr || ''}, ${otherReqStr || ''}`;
    const items = combined.split(/[,\n]/).map(s => s.trim()).filter(s => s.length > 1);
    const mapped = items.map(item => {
      const l = item.toLowerCase();
      if (l.includes('memento')) return 'Mementos';
      if (l.includes('projector')) return 'Projector';
      if (l.includes('mike') || l.includes('pa system') || l.includes('audio')) return 'Mike/PA System';
      if (l.includes('refreshment')) return 'Refreshments';
      if (l.includes('lunch')) return 'Lunch';
      if (l.includes('breakfast')) return 'Breakfast';
      if (l.includes('white board')) return 'White Board';
      if (l.includes('wifi') || l.includes('internet')) return 'Wi-Fi';
      if (l.includes('photo')) return 'Photography';
      if (l.includes('decor')) return 'Stage Decor';
      if (l.includes('certificate')) return 'Certificates';
      if (l.includes('transport')) return 'Guest Transport';
      if (l.includes('remuneration')) return 'Remuneration';
      if (l.includes('bouquet') || l.includes('boquet')) return 'Bouquet';
      if (l.includes('led')) return 'LED Screen';
      if (l.includes('lab')) return 'Computer lab';
      if (l.includes('board room')) return 'Board Room';
      return item;
    });
    return Array.from(new Set(mapped));
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsParsing(true);
    const reader = new FileReader();
    reader.onload = (evt) => {
      try {
        const bstr = evt.target?.result;
        const wb = XLSX.read(bstr, { type: 'binary', cellDates: true });
        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];
        const data = XLSX.utils.sheet_to_json(ws) as ExcelRow[];

        const parsedEvents: ParsedEvent[] = data
          .map((row, index): ParsedEvent | null => {
            try {
              const title = row['Name of the event'] || 'Untitled Event';
              const guestName = row['Name of the Guest'];
              const startDateValue = row['Date of the event (start date)'];
              
              if (!startDateValue) return null;

              let start = new Date(startDateValue);
              if (start.getFullYear() < 100) start.setFullYear(start.getFullYear() + 2000);
              if (isNaN(start.getTime())) return null;

              const endDateValue = row['Date of the event (End date)'];
              let end = endDateValue ? new Date(endDateValue) : new Date(start);
              if (isNaN(end.getTime())) end = new Date(start);
              if (end.getFullYear() < 100) end.setFullYear(end.getFullYear() + 2000);

              const startTimeStr = row['starting Time'];
              const endTimeStr = row['ending Time'];
              
              if (startTimeStr) {
                if (startTimeStr instanceof Date) start.setHours(startTimeStr.getHours(), startTimeStr.getMinutes());
                else if (typeof startTimeStr === 'string' && startTimeStr.includes(':')) {
                  const [h, m] = startTimeStr.split(':').map(n => parseInt(n));
                  if (!isNaN(h)) start.setHours(h, isNaN(m) ? 0 : m);
                }
              }

              if (endTimeStr) {
                if (endTimeStr instanceof Date) end.setHours(endTimeStr.getHours(), endTimeStr.getMinutes());
                else if (typeof endTimeStr === 'string' && endTimeStr.includes(':')) {
                  const [h, m] = endTimeStr.split(':').map(n => parseInt(n));
                  if (!isNaN(h)) end.setHours(h, isNaN(m) ? 0 : m);
                } else if (!endDateValue) end.setHours(start.getHours() + 2);
              } else if (!endDateValue) end.setHours(start.getHours() + 2);

              if (end <= start) end = new Date(start.getTime() + 2 * 60 * 60 * 1000);

              const venue = mapVenue(row.Venue);
              const dept = mapDepartment(row.Department);
              const reqs = parseRequirements(row['Requirements [Row 1]'], row['Any Other Requirements, Please mention']);

              // Fuzzy matching for Proposer Name & Email
              const rowKeys = Object.keys(row);
              const proposerKey = rowKeys.find(k => {
                const l = k.toLowerCase();
                return (l.includes('faculty') && l.includes('coordinator')) || 
                       l.includes('proposed by') || 
                       l.includes('proposer name') ||
                       (l.includes('name') && l.includes('coordinator'));
              }) || 'Name of the faculty coordinator';

              const emailKey = rowKeys.find(k => {
                const l = k.toLowerCase();
                return l.includes('email') || l.includes('mail id');
              });

              const proposerName = row[proposerKey] || 'Unknown Faculty';
              const proposerEmailFromExcel = emailKey ? row[emailKey] : null;

              // Priority: Identification by Email
              const foundUser = users.find(u => {
                if (proposerEmailFromExcel && u.email?.toLowerCase() === proposerEmailFromExcel.toLowerCase()) return true;
                if (u.fullName?.toLowerCase() === proposerName.toLowerCase()) return true;
                return false;
              });

              return {
                id: `row-${index}`,
                title: title,
                guestName: guestName || undefined,
                startDate: start.toISOString(),
                endDate: end.toISOString(),
                venue: venue,
                department: dept,
                requirements: reqs,
                status: 'APPROVED' as const,
                proposerName: proposerName || 'Unknown Faculty',
                proposerExists: !!foundUser,
                proposerId: foundUser?.id,
                proposerEmail: proposerEmailFromExcel || foundUser?.email,
                originalData: row
              };
            } catch (e) {
              console.error(`Error processing row ${index + 1}:`, e);
              return null;
            }
          })
          .filter((e): e is ParsedEvent => e !== null)
          .sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());

        setEvents(parsedEvents);
        setCurrentPageAttention(1);
        setCurrentPageReady(1);
        
        const resolutions = buildResolutionPlan(parsedEvents);
        setProposedResolutions(resolutions);
        setAppliedFixes([]);
        setIsResolutionReviewOpen(resolutions.length > 0);
      } catch (err) {
        console.error('Error parsing excel:', err);
        alert('Failed to parse Excel file. Please ensure it follows the expected format.');
      } finally {
        setIsParsing(false);
      }
    };
    reader.readAsBinaryString(file);
  };

  const handleImport = async (currentEvents = events) => {
    setIsSubmitting(true);
    try {
      const unresolvedConflict = currentEvents.find(e => getEventConflict(e, currentEvents));
      if (unresolvedConflict) {
        const plan = buildResolutionPlan(currentEvents);
        setProposedResolutions(plan);
        setIsResolutionReviewOpen(plan.length > 0);
        throw new Error('Resolve all venue and timing conflicts before importing.');
      }

      // 0. Refresh users list to ensure we have the latest
      let latestUsers = users;
      const usersRes = await fetch(`${API_BASE_URL}/api/admin/users`);
      if (usersRes.ok) {
        latestUsers = await usersRes.json();
        setUsers(latestUsers);
      }

      // 1. Identify missing proposers and register them
      const eventsToFix = currentEvents.filter(e => !e.proposerExists);
      const uniqueProposers = Array.from(new Set(eventsToFix.map(e => e.proposerName.trim()).filter(Boolean)));
      
      const createdUsersMap = new Map<string, number>();
      
      for (const name of uniqueProposers) {
        const event = currentEvents.find(e => e.proposerName.trim() === name);
        const email = (event?.proposerEmail || `${name.toLowerCase().replace(/[^a-z0-9]+/g, '.').replace(/^\.+|\.+$/g, '')}@ritindia.edu`).trim().toLowerCase();
        if (!email || !email.includes('@')) {
          throw new Error(`Missing a valid email for proposer "${name}". Map the proposer manually and retry.`);
        }
        
        const existing = latestUsers.find((u: any) => 
          u.email?.toLowerCase() === email || u.fullName?.trim().toLowerCase() === name.toLowerCase()
        );
        if (existing) {
          createdUsersMap.set(name, existing.id);
          continue;
        }

        const payload = {
          fullName: name,
          email: email,
          password: 'Password@123',
          role: 'FACULTY',
          department: event?.department || 'H&S Dept',
          isClubCoordinator: false,
          isPlacementStaff: false,
          isClassIncharge: false,
          assignedClubs: []
        };


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

        if (res.ok) {
          const newUser = await res.json();
          createdUsersMap.set(name, newUser.id);
          latestUsers = [...latestUsers, newUser];
          setUsers(latestUsers);
        } else if (res.status === 400) {
          // If already exists, fetch again to get the ID
          const syncRes = await fetch(`${API_BASE_URL}/api/admin/users`);
          if (syncRes.ok) {
            const allUsers = await syncRes.json();
            const found = allUsers.find((u: any) => 
              u.email?.toLowerCase() === email || u.fullName?.trim().toLowerCase() === name.toLowerCase()
            );
            if (found) createdUsersMap.set(name, found.id);
            else {
              const err = await res.json().catch(() => ({ message: 'User could not be created' }));
              throw new Error(`Could not create proposer "${name}": ${err.message || 'Bad request'}`);
            }
          } else {
            throw new Error(`Could not confirm proposer "${name}" after the user API returned 400.`);
          }
        } else {
          const err = await res.json().catch(() => ({ message: 'User could not be created' }));
          throw new Error(`Could not create proposer "${name}": ${err.message || res.statusText}`);
        }
      }

      // 2. Prepare and send events
      const payloads = currentEvents.map(e => {
        const proposerId = e.proposerId || createdUsersMap.get(e.proposerName.trim());
        return {
          title: e.title,
          guestName: e.guestName,
          startDate: e.startDate,
          endDate: e.endDate,
          venue: e.venue,
          institution: 'RIT',
          department: e.department,
          category: 'ACADEMIC',
          status: 'APPROVED',
          academicYears: [],
          requirements: e.requirements,
          proposer: proposerId ? { id: proposerId } : null
        };
      });

      const res = await fetch(`${API_BASE_URL}/api/events/batch-create`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payloads)
      });

      if (res.ok) {
        setImportStatus({ 
          success: true, 
          message: appliedFixes.length > 0 
            ? `Successfully imported ${currentEvents.length} events with ${appliedFixes.length} reviewed conflict fixes.`
            : `Successfully imported ${currentEvents.length} events.` 
        });
        setEvents([]);
        setAppliedFixes([]);
        setProposedResolutions([]);
        setIsResolutionReviewOpen(false);
      } else {
        const err = await res.json();
        throw new Error(err.message || 'Import failed');
      }
    } catch (err: any) {
      setImportStatus({ success: false, message: err.message });
    } finally {
      setIsSubmitting(false);
    }
  };

  const formatDateTimeLocal = (dateStr: string) => {
    const d = new Date(dateStr);
    const tzOffset = d.getTimezoneOffset() * 60000;
    return new Date(d.getTime() - tzOffset).toISOString().slice(0, 16);
  };

  const updateEvent = (id: string, updates: Partial<ParsedEvent>) => {
    setEvents(prev => {
      const targetEvent = prev.find(e => e.id === id);
      if (!targetEvent) return prev;

      const newEvents = prev.map(e => e.id === id ? { ...e, ...updates } : e);

      // Automatic propagation of faculty mappings
      if (updates.proposerId || updates.proposerExists === true) {
        const nameToMatch = targetEvent.proposerName;
        return newEvents.map(e => {
	          if (e.proposerName === nameToMatch && !e.proposerExists) {
	            return { 
	              ...e, 
	              proposerId: updates.proposerId, 
	              proposerName: updates.proposerName || e.proposerName, 
	              proposerEmail: updates.proposerEmail || e.proposerEmail,
	              proposerExists: true 
	            };
	          }
          return e;
        });
      }

      return newEvents;
    });
  };

  const renderTableRow = (event: ParsedEvent) => (
    <>
      <td className="px-4 py-3">
        <div className="flex flex-col gap-1 min-w-[180px]">
          <input 
            type="text"
            value={event.title}
            onChange={(e) => updateEvent(event.id, { title: e.target.value })}
            className="bg-transparent text-xs font-black text-brand-navy border-none p-0 focus:ring-0 w-full truncate"
          />
          {event.guestName && (
            <span className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-slate-100 text-[9px] font-bold text-slate-500 rounded w-fit">
              {event.guestName}
            </span>
          )}
          {event.conflict && (
            <span className="flex items-center gap-1 text-[9px] font-bold text-red-500 leading-tight">
              <AlertTriangle className="w-2.5 h-2.5 shrink-0" />
              {event.conflict}
            </span>
          )}
        </div>
      </td>
      <td className="px-4 py-3">
        <div className="flex flex-col gap-1 min-w-[140px]">
          <input 
            type="datetime-local"
            value={formatDateTimeLocal(event.startDate)}
            onChange={(e) => updateEvent(event.id, { startDate: new Date(e.target.value).toISOString() })}
            className={cn(
              "w-full bg-white border rounded-lg p-1.5 text-[9px] font-black focus:ring-2 transition-all outline-none",
              event.conflict ? "border-red-200 focus:ring-red-100 text-red-700" : "border-slate-100 focus:ring-brand-indigo/10"
            )}
          />
          <input 
            type="datetime-local"
            value={formatDateTimeLocal(event.endDate)}
            onChange={(e) => updateEvent(event.id, { endDate: new Date(e.target.value).toISOString() })}
            className={cn(
              "w-full bg-white border rounded-lg p-1.5 text-[9px] font-black focus:ring-2 transition-all outline-none",
              event.conflict ? "border-red-200 focus:ring-red-100 text-red-700" : "border-slate-100 focus:ring-brand-indigo/10"
            )}
          />
        </div>
      </td>
      <td className="px-4 py-3">
        <div className="min-w-[160px]">
          {!event.proposerExists ? (
            <div className="p-2 bg-brand-glow border border-brand-indigo/10 rounded-xl space-y-1.5">
              <div className="flex items-center gap-1.5 text-brand-indigo">
                <UserPlus className="w-3 h-3" />
                <span className="text-[8px] font-black uppercase tracking-widest">Will Auto-Create</span>
              </div>
              <p className="text-[9px] font-bold text-brand-navy leading-tight truncate">"{event.proposerName}"</p>
              <div className="relative group/map">
                <select 
                  className="w-full bg-white border border-brand-indigo/20 rounded-lg px-2 py-1 text-[9px] font-black text-brand-indigo outline-none focus:ring-2 focus:ring-brand-indigo/10 cursor-pointer appearance-none"
                  onChange={(e) => {
                    const u = users.find(u => u.id === Number(e.target.value));
                    if (u) updateEvent(event.id, { proposerId: u.id, proposerName: u.fullName, proposerEmail: u.email, proposerExists: true });
                  }}
                  value=""
                >
                  <option value="" disabled>Manual Map...</option>
                  {users
                    .filter(u => ['FACULTY', 'HOD', 'ADMIN', 'PRINCIPAL'].includes(u.role))
                    .sort((a, b) => a.fullName.localeCompare(b.fullName))
                    .map(u => (
                      <option key={u.id} value={u.id}>
                        {u.fullName} ({u.email})
                      </option>
                    ))
                  }
                </select>
                <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-brand-indigo pointer-events-none" />
              </div>
            </div>
          ) : (
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 rounded-full bg-emerald-50 flex items-center justify-center text-emerald-600 border border-emerald-100 shrink-0">
                <UserCheck className="w-3.5 h-3.5" />
              </div>
              <div className="min-w-0">
                <p className="text-[10px] font-black text-brand-navy truncate">{event.proposerName}</p>
                <p className="text-[8px] font-bold text-slate-400 truncate">{event.proposerEmail}</p>
              </div>
              <button 
                onClick={() => updateEvent(event.id, { proposerExists: false })}
                className="p-1 text-slate-300 hover:text-red-500 transition-colors ml-auto"
              >
                <X className="w-3 h-3" />
              </button>
            </div>
          )}
        </div>
      </td>
      <td className="px-4 py-3">
        <div className="flex flex-col gap-1 min-w-[120px]">
          <select 
            value={event.venue}
            onChange={(e) => updateEvent(event.id, { venue: e.target.value })}
            className={cn(
              "w-full bg-white border rounded-lg p-1.5 text-[9px] font-black focus:ring-2 transition-all outline-none cursor-pointer",
              event.conflict ? "border-red-200 focus:ring-red-100 text-red-700" : "border-slate-100 focus:ring-brand-indigo/10 text-brand-indigo"
            )}
          >
            {venues.map(v => <option key={v} value={v}>{v}</option>)}
          </select>
          <select 
            value={event.department}
            onChange={(e) => updateEvent(event.id, { department: e.target.value })}
            className="w-full bg-transparent text-[9px] font-bold text-text-secondary border-none p-0 focus:ring-0 cursor-pointer"
          >
            {DEPARTMENTS.map(d => <option key={d} value={d}>{d}</option>)}
          </select>
        </div>
      </td>
    </>
  );

  const filteredEvents = events.map(e => {
    const conflict = getEventConflict(e);
    return { ...e, conflict: conflict ? `Conflict with "${conflict.title}"` : undefined };
  }).filter(e => {
    const s = searchQuery.toLowerCase();
    return e.title.toLowerCase().includes(s) ||
           e.proposerName.toLowerCase().includes(s) ||
           (e.guestName && e.guestName.toLowerCase().includes(s)) ||
           e.venue.toLowerCase().includes(s) ||
           e.department.toLowerCase().includes(s);
  });

  const attentionRequired = filteredEvents.filter(e => e.conflict);
  const readyForImport = filteredEvents.filter(e => !e.conflict);

  const paginatedAttention = attentionRequired.slice(
    (currentPageAttention - 1) * itemsPerPage,
    currentPageAttention * itemsPerPage
  );
  
  const paginatedReady = readyForImport.slice(
    (currentPageReady - 1) * itemsPerPage,
    currentPageReady * itemsPerPage
  );

  return (
    <div className="space-y-8 pb-20">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-black text-text-dark tracking-tight">Excel Import Tool</h2>
          <p className="text-text-muted font-medium">Bulk upload events from institutional response sheets.</p>
        </div>
        <div className="flex items-center gap-4">
          {events.length > 0 && (
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
              <input 
                type="text"
                placeholder="Search events, proposers..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-11 pr-6 py-2.5 bg-white border border-slate-100 rounded-xl text-sm font-bold focus:ring-4 focus:ring-brand-indigo/5 outline-none w-64 transition-all"
              />
            </div>
          )}
          {proposedResolutions.length > 0 && (
            <button 
              onClick={() => {
                const nextPlan = buildResolutionPlan(events);
                setProposedResolutions(nextPlan);
                setIsResolutionReviewOpen(nextPlan.length > 0);
              }}
              className="px-6 py-2.5 bg-brand-glow text-brand-indigo rounded-xl text-xs font-black uppercase tracking-widest hover:shadow-lg transition-all flex items-center gap-2"
            >
              <Zap className="w-4 h-4" />
              Review Resolutions ({proposedResolutions.length})
            </button>
          )}
          {events.length > 0 && (
            <button 
              onClick={() => {
                setEvents([]);
                setSearchQuery('');
                setProposedResolutions([]);
                setAppliedFixes([]);
                setIsResolutionReviewOpen(false);
              }}
              className="px-6 py-2.5 bg-slate-100 text-text-muted rounded-xl text-xs font-black uppercase tracking-widest hover:bg-slate-200 transition-all"
            >
              Clear List
            </button>
          )}
        </div>
      </div>

      {importStatus && (
        <div className={cn(
          "flex items-center gap-3 rounded-2xl border px-5 py-4 text-sm font-bold",
          importStatus.success ? "bg-emerald-50 border-emerald-100 text-emerald-700" : "bg-red-50 border-red-100 text-red-700"
        )}>
          {importStatus.success ? <CheckCircle2 className="w-5 h-5" /> : <AlertCircle className="w-5 h-5" />}
          <span>{importStatus.message}</span>
          <button onClick={() => setImportStatus(null)} className="ml-auto p-1 rounded-lg hover:bg-white/60 transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>
      )}

      {events.length === 0 ? (
        <div className="bg-white rounded-[3rem] border-4 border-dashed border-slate-100 p-20 text-center relative group overflow-hidden">
          <div className="relative z-10">
            <div className="w-24 h-24 bg-brand-glow rounded-[2rem] flex items-center justify-center mx-auto mb-8 group-hover:scale-110 transition-transform duration-500">
              <Upload className="w-10 h-10 text-brand-indigo" />
            </div>
            <h3 className="text-2xl font-black text-brand-navy mb-4">Upload your Excel file</h3>
            <p className="text-text-muted max-w-sm mx-auto mb-10 font-medium">
              Drag and drop your "Hall Booking & Event Requirements" spreadsheet here or click to browse.
            </p>
            <label className="inline-flex items-center gap-3 px-8 py-4 bg-brand-navy text-white rounded-2xl font-black text-xs uppercase tracking-[0.2em] cursor-pointer hover:shadow-2xl hover:shadow-brand-navy/30 transition-all active:scale-95">
              <FileSpreadsheet className="w-5 h-5" />
              Choose File
              <input type="file" className="hidden" accept=".xlsx, .xls" onChange={handleFileUpload} />
            </label>
          </div>
          <div className="absolute inset-0 bg-brand-glow/30 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none" />
        </div>
      ) : (
        <div className="space-y-12">
          <div className="grid grid-cols-1 2xl:grid-cols-2 gap-8 items-start">
            {/* Attention Required Section */}
            <div className={cn("space-y-4", attentionRequired.length === 0 && "opacity-40 grayscale pointer-events-none")}>
              <div className="flex items-center gap-3 px-4">
                <div className="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center text-amber-600">
                  <AlertTriangle className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="text-xl font-black text-brand-navy tracking-tight">Conflicts Detected</h3>
                  <p className="text-text-muted text-[10px] font-bold uppercase tracking-widest">Overlapping venue schedules</p>
                </div>
                <div className="ml-auto px-4 py-1.5 bg-amber-50 text-amber-600 rounded-full text-[10px] font-black uppercase tracking-widest border border-amber-100">
                  {attentionRequired.length} Conflicts
                </div>
              </div>

              <div className="bg-white rounded-[2.5rem] border-2 border-amber-100 premium-shadow overflow-hidden flex flex-col h-[850px]">
                <div className="overflow-x-auto flex-1">
                  <table className="w-full text-left">
                    <thead>
                      <tr className="bg-amber-50/30 border-b border-amber-100 sticky top-0 z-10 backdrop-blur-md">
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-amber-700/60">Details</th>
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-amber-700/60">Timing</th>
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-amber-700/60">Proposer</th>
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-amber-700/60">Venue</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-amber-50">
                      {paginatedAttention.length > 0 ? paginatedAttention.map((event) => (
                        <tr key={event.id} className="bg-amber-50/10 hover:bg-amber-50/20 transition-colors">
                          {renderTableRow(event)}
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={4} className="px-8 py-20 text-center">
                            <div className="w-16 h-16 bg-emerald-50 text-emerald-500 rounded-2xl flex items-center justify-center mx-auto mb-4">
                              <CheckCircle2 className="w-8 h-8" />
                            </div>
                            <p className="text-sm font-black text-brand-navy">No Issues Found!</p>
                            <p className="text-xs font-medium text-text-muted mt-1">All filtered events are ready for import.</p>
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
                <div className="mt-auto border-t border-amber-50 bg-amber-50/10">
                  <Pagination 
                    currentPage={currentPageAttention}
                    totalItems={attentionRequired.length}
                    itemsPerPage={itemsPerPage}
                    onPageChange={setCurrentPageAttention}
                    onItemsPerPageChange={setItemsPerPage}
                    itemsPerPageOptions={[10, 20, 50, 100]}
                  />
                </div>
              </div>
            </div>

            {/* Ready for Import Section */}
            <div className={cn("space-y-4", readyForImport.length === 0 && "opacity-40 grayscale pointer-events-none")}>
              <div className="flex items-center gap-3 px-4">
                <div className="w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center text-emerald-600">
                  <CheckCircle2 className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="text-xl font-black text-brand-navy tracking-tight">Ready for Import</h3>
                  <p className="text-text-muted text-[10px] font-bold uppercase tracking-widest">Verified and conflict-free entries</p>
                </div>
                <div className="ml-auto px-4 py-1.5 bg-emerald-50 text-emerald-600 rounded-full text-[10px] font-black uppercase tracking-widest border border-emerald-100">
                  {readyForImport.length} Ready
                </div>
              </div>

              <div className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden flex flex-col h-[850px]">
                <div className="overflow-x-auto flex-1">
                  <table className="w-full text-left">
                    <thead>
                      <tr className="bg-slate-50/50 border-b border-slate-100 sticky top-0 z-10 backdrop-blur-md">
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-text-muted">Details</th>
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-text-muted">Timing</th>
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-text-muted">Proposer</th>
                        <th className="px-6 py-4 text-[10px] font-black uppercase tracking-widest text-text-muted">Venue</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-50">
                      {paginatedReady.length > 0 ? paginatedReady.map((event) => (
                        <tr key={event.id} className="hover:bg-slate-50/50 transition-colors">
                          {renderTableRow(event)}
                        </tr>
                      )) : (
                        <tr>
                          <td colSpan={4} className="px-8 py-20 text-center">
                            <div className="w-16 h-16 bg-slate-50 text-slate-300 rounded-2xl flex items-center justify-center mx-auto mb-4">
                              <Search className="w-8 h-8" />
                            </div>
                            <p className="text-sm font-black text-brand-navy">No Ready Events</p>
                            <p className="text-xs font-medium text-text-muted mt-1">Try clearing your search or fixing issues.</p>
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
                <div className="mt-auto border-t border-slate-50 bg-slate-50/30">
                  <Pagination 
                    currentPage={currentPageReady}
                    totalItems={readyForImport.length}
                    itemsPerPage={itemsPerPage}
                    onPageChange={setCurrentPageReady}
                    onItemsPerPageChange={setItemsPerPage}
                    itemsPerPageOptions={[10, 20, 50, 100]}
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="flex flex-col items-end gap-4 bg-white/50 backdrop-blur-xl p-8 rounded-[3rem] border border-white sticky bottom-4 z-50 premium-shadow">
            <div className="flex items-center gap-6">
              <div className="text-right">
                <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-1">Current Batch Status</p>
                <div className="flex items-center gap-3">
                  <span className="flex items-center gap-1.5 text-xs font-bold text-amber-600">
                    <AlertTriangle className="w-3.5 h-3.5" /> {attentionRequired.length} Issues
                  </span>
                  <div className="w-1 h-1 rounded-full bg-slate-200" />
                  <span className="flex items-center gap-1.5 text-xs font-bold text-emerald-600">
                    <CheckCircle2 className="w-3.5 h-3.5" /> {readyForImport.length} Ready
                  </span>
                </div>
              </div>
              <div className="h-10 w-px bg-slate-100" />
              <div className="flex gap-4">
                <button 
                  disabled={isSubmitting}
                  onClick={() => {
                    setEvents([]);
                    setSearchQuery('');
                    setProposedResolutions([]);
                    setAppliedFixes([]);
                    setIsResolutionReviewOpen(false);
                  }}
                  className="px-8 py-4 bg-slate-50 text-text-muted rounded-2xl font-black text-xs uppercase tracking-widest hover:bg-slate-100 transition-all"
                >
                  Discard All
                </button>
                <button 
                  disabled={isSubmitting || attentionRequired.length > 0 || readyForImport.length === 0}
                  onClick={() => handleImport()}
                  className="px-12 py-4 bg-brand-navy text-white rounded-2xl font-black text-xs uppercase tracking-[0.2em] hover:shadow-2xl hover:shadow-brand-navy/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-3 group"
                >
                  {isSubmitting ? <Loader2 className="w-5 h-5 animate-spin" /> : <CheckCircle2 className="w-5 h-5 group-hover:scale-110 transition-transform" />}
                  Import {readyForImport.length} Events
                </button>
              </div>
            </div>
            {attentionRequired.length > 0 && (
              <p className="text-[10px] font-bold text-red-500 flex items-center gap-2">
                <AlertCircle className="w-3 h-3" />
                Resolve all {attentionRequired.length} issues in the left panel to enable import.
              </p>
            )}
          </div>
        </div>
      )}

      {isParsing && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-md z-[100] flex items-center justify-center">
          <div className="bg-white p-12 rounded-[3rem] text-center max-w-sm">
            <div className="w-20 h-20 bg-brand-glow rounded-3xl flex items-center justify-center mx-auto mb-6">
              <Loader2 className="w-10 h-10 text-brand-indigo animate-spin" />
            </div>
            <h3 className="text-2xl font-black text-brand-navy mb-2">Parsing Spreadsheet</h3>
            <p className="text-text-muted font-medium italic">Analyzing rows and mapping departments...</p>
          </div>
        </div>
      )}

      {isResolutionReviewOpen && proposedResolutions.length > 0 && (
        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-md z-[120] flex items-center justify-center p-4">
          <div className="bg-white p-10 rounded-[2.5rem] max-w-5xl w-full premium-shadow border border-slate-100 animate-in zoom-in duration-300 flex flex-col max-h-[90vh]">
            <div className="flex items-center justify-between mb-8 shrink-0">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-brand-indigo text-white rounded-2xl flex items-center justify-center">
                  <Zap className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="text-2xl font-black text-brand-navy tracking-tight">Review Conflict Fixes</h3>
                  <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{proposedResolutions.length} venue/timing fixes sorted by venue and start time.</p>
                </div>
              </div>
              <button 
                onClick={() => setIsResolutionReviewOpen(false)}
                className="w-10 h-10 rounded-full hover:bg-slate-100 flex items-center justify-center text-slate-400 transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto pr-4 custom-scrollbar space-y-4 mb-8">
              {proposedResolutions.map((res) => (
                <div key={res.eventId} className={cn(
                  "p-5 rounded-2xl border grid grid-cols-1 xl:grid-cols-[1.2fr_1.1fr_1fr] gap-5",
                  res.fixType === 'manual' ? "bg-red-50/50 border-red-100" : "bg-emerald-50/50 border-emerald-100"
                )}>
                  <div className="min-w-0">
                    <div className="flex items-center gap-2 mb-2">
                      {res.fixType === 'time' ? <Clock className="w-4 h-4 text-amber-600" /> : <MapPin className="w-4 h-4 text-emerald-600" />}
                      <h4 className="text-sm font-black text-brand-navy truncate">{res.title}</h4>
                    </div>
                    <p className="text-[10px] font-bold text-slate-500 leading-relaxed">{res.reason}</p>
                    <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest mt-2">Conflict: {res.conflictWith}</p>
                  </div>

                  <div className="grid grid-cols-[1fr_auto_1fr] gap-3 items-center text-[10px] font-bold">
                    <div className="min-w-0">
                      <p className="uppercase tracking-widest text-slate-400 mb-1">Original</p>
                      <p className="line-through text-slate-400 truncate">{res.oldVenue}</p>
                      <p className="text-slate-400 mt-1">{formatDateTimeLocal(res.oldStartDate).replace('T', ' ')}</p>
                    </div>
                    <ArrowRight className="w-4 h-4 text-brand-indigo" />
                    <div className="min-w-0">
                      <p className="uppercase tracking-widest text-slate-400 mb-1">Applied Fix</p>
                      <p className="text-emerald-700 truncate">{res.newVenue}</p>
                      <p className="text-emerald-700 mt-1">{formatDateTimeLocal(res.newStartDate).replace('T', ' ')}</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                    <select
                      value={res.newVenue}
                      onChange={(e) => {
                        setProposedResolutions(prev => prev.map(item => item.eventId === res.eventId ? { ...item, newVenue: e.target.value, fixType: 'venue' } : item));
                      }}
                      className="bg-white border border-slate-100 rounded-xl px-3 py-2 text-[10px] font-black text-brand-indigo outline-none focus:ring-2 focus:ring-brand-indigo/10"
                    >
                      {venues.map(v => <option key={v} value={v}>{v}</option>)}
                    </select>
                    <input
                      type="datetime-local"
                      value={formatDateTimeLocal(res.newStartDate)}
                      onChange={(e) => {
                        const newStartDate = new Date(e.target.value).toISOString();
                        const newEndDate = new Date(new Date(newStartDate).getTime() + (new Date(res.newEndDate).getTime() - new Date(res.newStartDate).getTime())).toISOString();
                        setProposedResolutions(prev => prev.map(item => item.eventId === res.eventId ? { ...item, newStartDate, newEndDate, fixType: 'time' } : item));
                      }}
                      className="bg-white border border-slate-100 rounded-xl px-3 py-2 text-[10px] font-black text-brand-navy outline-none focus:ring-2 focus:ring-brand-indigo/10"
                    />
                    <input
                      type="datetime-local"
                      value={formatDateTimeLocal(res.newEndDate)}
                      onChange={(e) => {
                        const newEndDate = new Date(e.target.value).toISOString();
                        setProposedResolutions(prev => prev.map(item => item.eventId === res.eventId ? { ...item, newEndDate, fixType: 'time' } : item));
                      }}
                      className="bg-white border border-slate-100 rounded-xl px-3 py-2 text-[10px] font-black text-brand-navy outline-none focus:ring-2 focus:ring-brand-indigo/10"
                    />
                  </div>
                </div>
              ))}
            </div>

            <div className="shrink-0 flex gap-4">
              <button 
                onClick={() => setIsResolutionReviewOpen(false)}
                className="flex-1 py-4 bg-slate-100 text-slate-500 rounded-2xl font-black text-xs uppercase tracking-widest hover:bg-slate-200 transition-all"
              >
                Keep Reviewing Manually
              </button>
              <button 
                onClick={() => {
                  const nextEvents = events.map(event => {
                    const fix = proposedResolutions.find(res => res.eventId === event.id);
                    return fix ? { ...event, venue: fix.newVenue, startDate: fix.newStartDate, endDate: fix.newEndDate } : event;
                  });
                  const remainingPlan = buildResolutionPlan(nextEvents);
                  setEvents(nextEvents);
                  setAppliedFixes(proposedResolutions);
                  setProposedResolutions(remainingPlan);
                  setIsResolutionReviewOpen(remainingPlan.length > 0);
                  if (remainingPlan.length === 0) {
                    setImportStatus({ success: true, message: `Applied ${proposedResolutions.length} reviewed conflict fixes. The batch is ready to import.` });
                  } else {
                    setImportStatus({ success: false, message: `${remainingPlan.length} conflicts still need review after applying the current edits.` });
                  }
                }}
                className="flex-[2] py-4 bg-brand-navy text-white rounded-2xl font-black text-xs uppercase tracking-[0.2em] hover:shadow-2xl hover:shadow-brand-navy/30 transition-all flex items-center justify-center gap-2 group"
              >
                <CheckCircle2 className="w-5 h-5 group-hover:scale-110 transition-transform" />
                Apply Reviewed Changes
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
