import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { createPortal } from 'react-dom';
import type { UserRole, DashboardView, Event, Announcement, SpecialEvent } from '../../types';
import { useAuth } from '../../context/AuthContext';
import { useDialog } from '../../context/DialogContext';
import { API_BASE_URL } from '../../lib/config';

// Import Site 2 components
import Navbar from '../student/Navbar';
import Hero from '../student/Hero';
import UpcomingEventsSlider from '../student/UpcomingEventsSlider';
import AboutHubSection from '../student/AboutHubSection';
import StatsSection from '../student/StatsSection';
import HomeDashboard from '../student/HomeDashboard';
import AboutSection from '../student/AboutSection';
import ContactSection from '../student/ContactSection';
import EventList from '../student/EventList';
import RegistrationsView from '../student/RegistrationsView';
import ProfileView from '../student/ProfileView';
import StatusTrackerView from '../student/StatusTrackerView';
import Footer from '../student/Footer';

const Portal: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  return createPortal(children, document.body);
};

export const StudentDashboard: React.FC = () => {
  const { user, logout, login } = useAuth();
  const { showAlert } = useDialog();
  
  // Tab Routing
  const [activeView, setActiveView] = useState<DashboardView>('HOME');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [trackedEvent, setTrackedEvent] = useState<Event | null>(null);

  // States
  const [rawEvents, setRawEvents] = useState<any[]>([]);
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [allRegistrations, setAllRegistrations] = useState<any[]>([]);
  const [specialEvents, setSpecialEvents] = useState<SpecialEvent[]>([]);
  const [settings, setSettings] = useState<Record<string, any>>({});
  const [isLoading, setIsLoading] = useState(true);

  // Team Modals
  const [showCreateModal, setShowCreateModal] = useState<{eventId: string, title: string} | null>(null);
  const [showJoinModal, setShowJoinModal] = useState<{eventId: string, title: string} | null>(null);
  const [teamName, setTeamName] = useState('');
  const [teamCode, setTeamCode] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);

  // Map raw Firebase event object to Site 2 Event structure
  const mapDbToEvent = useCallback((dbEvent: any, registrations: any[] = []): Event => {
    const eventRegs = registrations.filter(r => String(r.eventId || r.event_id) === String(dbEvent.id));
    const deptCounts: Record<string, number> = {};
    const deptSectionCounts: Record<string, Record<string, number>> = {};

    eventRegs.forEach(reg => {
      const dept = reg.dept || reg.department;
      if (dept) {
        deptCounts[dept] = (deptCounts[dept] || 0) + 1;
        if (reg.section) {
          if (!deptSectionCounts[dept]) {
            deptSectionCounts[dept] = {};
          }
          deptSectionCounts[dept][reg.section] = (deptSectionCounts[dept][reg.section] || 0) + 1;
        }
      }
    });

    const mapDepartmentToDomain = (dept: string): string => {
      if (!dept) return '';
      const d = dept.trim().toUpperCase();
      if (d === 'AI&DS' || d === 'AIDS' || d === 'AI & DS') return 'AIDS';
      if (d === 'AI&ML' || d === 'AIML' || d === 'AI & ML') return 'AIML';
      if (d === 'MECH' || d === 'MECHANICAL') return 'Mechanical';
      if (d === 'BIOTECH' || d === 'BIO-TECH') return 'Bio-tech';
      if (d === 'EE(VLSI)' || d === 'VLSI') return 'VLSI';
      return dept.trim();
    };

    const mapCategoryToStudentCategory = (dbCat: string, dbType: string): 'TECHNICAL' | 'NON-TECHNICAL' | 'WORKSHOP' | 'CENTRE-ACTIVITY' => {
      const cat = (dbCat || '').toUpperCase();
      if (cat === 'WORKSHOP') {
        return 'TECHNICAL';
      }
      if (cat === 'TECHNICAL' || cat === 'NON-TECHNICAL' || cat === 'CENTRE-ACTIVITY') {
        return cat as any;
      }
      if (cat === 'CENTRE') {
        return 'CENTRE-ACTIVITY';
      }
      if (cat === 'ACADEMIC') {
        return 'TECHNICAL';
      }
      const type = (dbType || '').toLowerCase();
      if (type === 'workshop') {
        return 'TECHNICAL';
      }
      if (type === 'cultural event' || type === 'cultural') {
        return 'NON-TECHNICAL';
      }
      return 'TECHNICAL';
    };

    return {
      id: String(dbEvent.id),
      title: dbEvent.title || 'Untitled Event',
      location: dbEvent.location || dbEvent.venue || 'TBD',
      date: dbEvent.startDate || dbEvent.date || new Date().toISOString(),
      category: mapCategoryToStudentCategory(dbEvent.category, dbEvent.eventType || dbEvent.type || ''),
      domain: mapDepartmentToDomain(dbEvent.domain || dbEvent.department || ''),
      pricingType: dbEvent.hasRegistrationFee ? 'PAID' : 'FREE',
      coordinator: dbEvent.proposer?.fullName || dbEvent.coordinator || 'Faculty Coordinator',
      image: dbEvent.image || 'https://images.unsplash.com/photo-1517694712202-14dd9538aa97?auto=format&fit=crop&q=80&w=800',
      status: dbEvent.status || 'APPROVED',
      maxParticipants: dbEvent.maxParticipants || dbEvent.max_participants,
      registrationDeadline: dbEvent.registrationDeadline || dbEvent.endDate,
      durationDays: dbEvent.durationDays || 1,
      club: dbEvent.club || '',
      deptLimits: dbEvent.deptLimits || {},
      deptSectionLimits: dbEvent.deptSectionLimits || {},
      event_summary: dbEvent.description || dbEvent.event_summary || '',
      isTeamEvent: !!dbEvent.isTeamEvent,
      teamSizeLimit: dbEvent.teamSizeLimit || dbEvent.team_size_limit,
      teamComposition: dbEvent.teamComposition || dbEvent.team_composition,
      currentParticipants: eventRegs.length,
      currentDeptCounts: deptCounts,
      currentDeptSectionCounts: deptSectionCounts,
      created_by: dbEvent.proposer?.email || dbEvent.created_by || '',
      participantType: dbEvent.participantType || 'BOTH',
      verificationStatus: dbEvent.status === 'COMPLETED' ? 'APPROVED' : 'APPROVED',
      openToAll: !!dbEvent.openToAll,
      academicYears: dbEvent.academicYears || [],
      targetedSections: dbEvent.targetedSections || [],
      department: dbEvent.department || ''
    };
  }, []);

  // Sync data from Firestore
  const fetchData = async () => {
    if (!user) return;
    setIsLoading(true);
    try {
      const [eventsRes, regsRes, annRes] = await Promise.all([
        fetch(`${API_BASE_URL}/api/events`),
        fetch(`${API_BASE_URL}/api/registrations`),
        fetch(`${API_BASE_URL}/api/announcements`)
      ]);

      let eventsData = [];
      let regsData = [];
      let annData = [];

      if (eventsRes.ok) eventsData = await eventsRes.json();
      if (regsRes.ok) regsData = await regsRes.json();
      if (annRes.ok) annData = await annRes.json();

      setRawEvents(eventsData);
      setAllRegistrations(regsData);
      setAnnouncements(annData);

      // Fetch special events safely (defaulting to empty array if not supported)
      try {
        const [seRes, setRes] = await Promise.all([
          fetch(`${API_BASE_URL}/api/special-events`),
          fetch(`${API_BASE_URL}/api/settings`)
        ]);

        if (seRes.ok) {
          const seData = await seRes.json();
          setSpecialEvents(seData);
        }
        if (setRes.ok) {
          const setData = await setRes.json();
          setSettings(setData);
        }
      } catch (err) {
        console.error("Failed to fetch special events/settings:", err);
        setSpecialEvents([]);
        setSettings({});
      }
    } catch (err) {
      console.error("Failed to fetch student dashboard data from Firestore:", err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [user?.id]);

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [activeView, selectedCategory]);

  // Compute computed lists
  const events = useMemo(() => {
    const list = rawEvents.map(e => mapDbToEvent(e, allRegistrations));
    // Students only see live (approved / ongoing / completed) events
    return list.filter(e => {
      const isLive = e.status === 'APPROVED' || e.status === 'COMPLETED' || e.status === 'Event Ongoing' || e.status === 'ONGOING';
      if (!isLive) return false;

      // If it is open to all, it is visible to everyone
      if (e.openToAll) return true;

      // Otherwise, filter by student's department, year, and section
      const userDept = user?.department || '';
      const userYear = user?.year || '';
      const userSec = user?.section || '';

      const normalize = (s: string) => (s || '').trim().replace(/[^a-zA-Z0-9]/g, '').toLowerCase();

      const deptMatches = normalize(userDept) === normalize(e.domain || e.department || '');
      
      const yearMatches = e.academicYears && e.academicYears.length > 0
        ? e.academicYears.map((y: string) => normalize(y)).includes(normalize(userYear))
        : true;
        
      const sectionMatches = e.targetedSections && e.targetedSections.length > 0
        ? e.targetedSections.map((s: string) => normalize(s)).includes(normalize(userSec))
        : true;

      return deptMatches && yearMatches && sectionMatches;
    });
  }, [rawEvents, allRegistrations, mapDbToEvent, user]);

  const userRegistrations = useMemo(() => {
    return allRegistrations.filter(r => String(r.userId || r.user_id) === String(user?.id));
  }, [allRegistrations, user?.id]);

  const bookedEventIds = useMemo(() => {
    return userRegistrations.map(r => String(r.eventId || r.event_id));
  }, [userRegistrations]);

  // Actions
  const handleToggleBooking = async (eventId: string, customDetails?: any) => {
    if (!user) return;
    const isBooked = bookedEventIds.includes(eventId);
    setIsProcessing(true);

    try {
      if (isBooked) {
        // Cancel registration
        const regId = `${user.id}_${eventId}`;
        const res = await fetch(`${API_BASE_URL}/api/registrations/${regId}`, {
          method: 'DELETE'
        });
        if (res.ok) {
          await fetchData();
        } else {
          showAlert("Error", "Failed to cancel registration.", "error");
        }
      } else {
        // Block booking if there's an unfinalized completed event (missing proof or missing OD approval)
        const unfinalized = userRegistrations.find(reg => {
          const ev = events.find(e => String(e.id) === String(reg.eventId || reg.event_id));
          if (ev && ev.status === 'COMPLETED') {
            const hasUploadedCert = !!(reg.certificationUrl || reg.certification_url);
            const hasOd = !!(reg.odUrl || reg.od_url);
            return !hasUploadedCert || !hasOd;
          }
          return false;
        });

        if (unfinalized) {
          const ev = events.find(e => String(e.id) === String(unfinalized.eventId || unfinalized.event_id));
          showAlert("Registration Blocked", `You must upload your certificate and obtain OD approval for your completed event "${ev?.title || 'Past Event'}" before registering for another event.`, "error");
          setIsProcessing(false);
          return;
        }

        const targetEvent = events.find(e => String(e.id) === String(eventId));
        if (!targetEvent) return;

        // Register booking
        const payload = {
          userId: user.id,
          user_id: user.id,
          eventId: Number(eventId),
          event_id: Number(eventId),
          userEmail: customDetails?.email || user.email,
          userName: customDetails?.userName || user.fullName,
          regNo: customDetails?.regNo || user.regNo,
          phone: customDetails?.phone || user.phone,
          gender: user.gender,
          dept: customDetails?.dept || user.department,
          section: customDetails?.section || user.section,
          year: customDetails?.year || user.year,
          college: customDetails?.collegeName || user.collegeName || 'Rajalakshmi Institute of Technology',
          class: customDetails?.class,
          collegeLocation: customDetails?.collegeLocation,
          isExternal: customDetails?.isExternal
        };

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

        if (res.ok) {
          // Sync profile details back to the student's user record in Firestore
          try {
            const userUpdatePayload = {
              fullName: customDetails?.userName || user.fullName,
              phone: customDetails?.phone || user.phone,
              collegeName: customDetails?.collegeName || user.collegeName,
              department: customDetails?.isExternal ? 'Others' : (customDetails?.dept || user.department),
              year: customDetails?.year || user.year,
              section: customDetails?.isExternal ? 'N/A' : (customDetails?.section || user.section),
              regNo: customDetails?.regNo || user.regNo,
              // Keep external-specific properties in the user profile too
              class: customDetails?.class,
              collegeLocation: customDetails?.collegeLocation
            };
            
            const userUpdateRes = await fetch(`${API_BASE_URL}/api/admin/users/${user.id}`, {
              method: 'PUT',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(userUpdatePayload)
            });
            
            if (userUpdateRes.ok) {
              const updatedUserData = await userUpdateRes.json();
              login(updatedUserData);
            }
          } catch (profileErr) {
            console.error("Failed to automatically update user profile details on registration:", profileErr);
          }

          await fetchData();
          setActiveView('REGISTRATIONS');
        } else {
          const err = await res.json();
          showAlert("Error", err.message || "Registration failed.", "error");
        }
      }
    } catch (err) {
      console.error("Booking handler error:", err);
    } finally {
      setIsProcessing(false);
    }
  };

  const generateCode = () => Math.random().toString(36).substring(2, 8).toUpperCase();

  const handleCreateTeam = async (eventId: string) => {
    if (!teamName.trim()) {
      showAlert("Required", "Enter team name", "error");
      return;
    }
    setIsProcessing(true);
    try {
      const code = generateCode();
      const registrationId = `${user?.id}_${eventId}`;
      const res = await fetch(`${API_BASE_URL}/api/registrations/${registrationId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          teamCode: code,
          teamName: teamName.trim(),
          isTeamLeader: true
        })
      });

      if (!res.ok) throw new Error("Failed to create team");
      
      setShowCreateModal(null);
      setTeamName('');
      await fetchData();
    } catch (err) {
      console.error(err);
      showAlert("Error", "Failed to form team", "error");
    } finally {
      setIsProcessing(false);
    }
  };

  const handleJoinTeam = async (eventId: string) => {
    if (!teamCode.trim()) {
      showAlert("Required", "Enter team code", "error");
      return;
    }
    setIsProcessing(true);
    try {
      // Fetch team registrations to validate
      const res = await fetch(`${API_BASE_URL}/api/registrations?eventId=${eventId}&teamCode=${teamCode.trim().toUpperCase()}`);
      if (!res.ok) throw new Error("Failed to fetch team details");
      const teamRegs = await res.json();

      if (!teamRegs || teamRegs.length === 0) {
        showAlert("Invalid Team", "Invalid team code for this event.", "error");
        setIsProcessing(false);
        return;
      }

      const leader = teamRegs.find((r: any) => r.isTeamLeader || r.is_team_leader);
      const eventVal = events.find(e => String(e.id) === String(eventId));

      if (eventVal?.teamSizeLimit && teamRegs.length >= eventVal.teamSizeLimit) {
        showAlert("Team Full", "Team is already full.", "error");
        setIsProcessing(false);
        return;
      }

      if (eventVal?.teamComposition === 'INTER_DEPT' && leader && user?.department !== (leader.dept || leader.department)) {
        showAlert("Inter-Department Only", `This event requires INTER-DEPARTMENT teams. You must join a team from department ${(leader.dept || leader.department)}`, "error");
        setIsProcessing(false);
        return;
      }

      const registrationId = `${user?.id}_${eventId}`;
      const joinRes = await fetch(`${API_BASE_URL}/api/registrations/${registrationId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          teamCode: teamCode.trim().toUpperCase(),
          teamName: leader?.teamName || leader?.team_name || 'Team',
          isTeamLeader: false
        })
      });

      if (!joinRes.ok) throw new Error("Join failed");

      setShowJoinModal(null);
      setTeamCode('');
      await fetchData();
    } catch (err) {
      console.error(err);
      showAlert("Error", "Failed to join team", "error");
    } finally {
      setIsProcessing(false);
    }
  };

  const handleUploadCertificate = async (eventId: string, base64: string): Promise<string> => {
    const regId = `${user?.id}_${eventId}`;
    const res = await fetch(`${API_BASE_URL}/api/registrations/${regId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        certificationUrl: base64,
        certificationStatus: 'PENDING_APPROVAL'
      })
    });
    if (!res.ok) throw new Error("Failed to upload screenshot proof");
    await fetchData();
    return base64;
  };

  const handleTrackStatus = (event: Event) => {
    setTrackedEvent(event);
    setActiveView('STATUS_TRACKER');
  };

  // Render Sub View
  const renderContent = () => {
    switch (activeView) {
      case 'HOME':
        return (
          <>
            <Hero events={events} />
            <UpcomingEventsSlider 
              events={events} 
              bookedEventIds={bookedEventIds}
              onToggleBooking={handleToggleBooking}
              userRole={user?.role}
            />
            <AboutHubSection />
            <StatsSection events={events} />
            <HomeDashboard 
              events={events} 
              announcements={announcements} 
              onNavigateToEvents={() => setActiveView('EVENTS')} 
              specialEvents={specialEvents}
              settings={settings}
            />
          </>
        );
      case 'ABOUT':
        return (
          <div className="pt-16 min-h-screen bg-white">
            <AboutSection />
          </div>
        );
      case 'CONTACT':
        return (
          <div className="pt-16 min-h-screen bg-white">
            <ContactSection />
          </div>
        );
      case 'EVENTS':
        return (
          <EventList
            events={events}
            selectedCategory={selectedCategory}
            bookedEventIds={bookedEventIds}
            onToggleBooking={handleToggleBooking}
            onSelectCategory={setSelectedCategory}
            onTrackStatus={handleTrackStatus}
            currentUserName={user?.fullName || ''}
            userRole={user?.role}
            userRegistrations={userRegistrations}
          />
        );
      case 'REGISTRATIONS':
        return (
          <RegistrationsView
            events={events}
            bookedEventIds={bookedEventIds}
            userRegistrations={userRegistrations}
            onToggleBooking={handleToggleBooking}
            onTrackStatus={handleTrackStatus}
            currentUserName={user?.fullName || ''}
            userRole={user?.role}
          />
        );
      case 'PROFILE':
        return <ProfileView onLogout={logout} />;
      case 'STATUS_TRACKER':
        const registration = userRegistrations.find(r => String(r.eventId || r.event_id) === String(trackedEvent?.id));
        return trackedEvent ? (
          <StatusTrackerView
            event={trackedEvent}
            registration={registration}
            onBack={() => setActiveView('REGISTRATIONS')}
            onUploadCertificate={(data) => handleUploadCertificate(trackedEvent.id, data)}
            onShowCreateTeam={() => setShowCreateModal({ eventId: trackedEvent.id, title: trackedEvent.title })}
            onShowJoinTeam={() => setShowJoinModal({ eventId: trackedEvent.id, title: trackedEvent.title })}
          />
        ) : null;
      default:
        return null;
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-slate-50 flex flex-col items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#f97316]"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white">
      <Navbar
        activeView={activeView}
        onViewChange={(view) => {
          setActiveView(view);
          setTrackedEvent(null);
        }}
        onLogout={logout}
      />
      <main className="pb-20">
        {renderContent()}
      </main>
      <Footer />

      {/* Team Management Modals */}
      {showCreateModal && (
        <Portal>
          <div className="fixed inset-0 z-[10000] flex items-center justify-center p-6 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
            <div className="bg-white rounded-[3rem] w-full max-w-md p-10 md:p-12 shadow-2xl animate-in zoom-in-95 duration-500 relative overflow-hidden">
              <div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-orange-400 to-amber-400"></div>
              <div className="w-16 h-16 flex items-center justify-center mx-auto mb-8">
                <img 
                  src="/Rit-logo.png" 
                  alt="RIT Logo"
                  className="w-full h-full object-contain"
                />
              </div>
              <h3 className="text-2xl font-black text-slate-900 text-center uppercase mb-2 tracking-tight">Form a Team</h3>
              <p className="text-[10px] text-gray-400 text-center font-bold uppercase tracking-widest mb-10 line-clamp-1 px-4">{showCreateModal.title}</p>
              
              <div className="space-y-8">
                <div>
                  <label className="block text-[9px] font-black text-slate-400 uppercase tracking-[0.2em] mb-3 px-2">Team Identity</label>
                  <input 
                    type="text" 
                    placeholder="Enter team name..."
                    className="w-full bg-slate-50 border border-slate-200 rounded-[2rem] px-8 py-5 text-sm font-bold outline-none focus:ring-4 focus:ring-orange-100 focus:border-[#f97316] transition-all placeholder:text-slate-300"
                    value={teamName}
                    onChange={e => setTeamName(e.target.value)}
                    autoFocus
                  />
                </div>
                
                <div className="flex flex-col gap-3">
                  <button 
                    onClick={() => handleCreateTeam(showCreateModal.eventId)}
                    disabled={isProcessing}
                    className="w-full py-5 bg-[#f97316] text-white rounded-[2rem] font-black uppercase text-[11px] tracking-[0.2em] shadow-xl shadow-orange-200 hover:bg-[#ea580c] transition-all active:scale-95 disabled:opacity-50"
                  >
                    {isProcessing ? 'INITIALIZING...' : 'Establish Team & Code'}
                  </button>
                  <button onClick={() => setShowCreateModal(null)} className="w-full py-4 text-gray-400 font-black uppercase text-[9px] tracking-widest hover:text-slate-600 transition-colors">Dismiss</button>
                </div>
              </div>
            </div>
          </div>
        </Portal>
      )}

      {showJoinModal && (
        <Portal>
          <div className="fixed inset-0 z-[10000] flex items-center justify-center p-6 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
            <div className="bg-white rounded-[3rem] w-full max-w-md p-10 md:p-12 shadow-2xl animate-in zoom-in-95 duration-500 relative overflow-hidden">
              <div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-blue-400 to-indigo-400"></div>
              <div className="w-16 h-16 flex items-center justify-center mx-auto mb-8">
                <img 
                  src="/Rit-logo.png" 
                  alt="RIT Logo"
                  className="w-full h-full object-contain"
                />
              </div>
              <h3 className="text-2xl font-black text-slate-900 text-center uppercase mb-2 tracking-tight">Join Alliance</h3>
              <p className="text-[10px] text-gray-400 text-center font-bold uppercase tracking-widest mb-10 line-clamp-1 px-4">{showJoinModal.title}</p>
              
              <div className="space-y-8">
                <div>
                  <label className="block text-[9px] font-black text-slate-400 uppercase tracking-[0.2em] mb-3 px-2 text-center">Team Access Token</label>
                  <input 
                    type="text" 
                    placeholder="TOKEN"
                    className="w-full bg-slate-50 border border-slate-200 rounded-[2rem] px-5 py-6 text-center text-3xl font-black tracking-[0.4em] outline-none focus:ring-4 focus:ring-blue-100 focus:border-blue-500 uppercase transition-all placeholder:text-slate-200"
                    value={teamCode}
                    onChange={e => setTeamCode(e.target.value)}
                    maxLength={6}
                    autoFocus
                  />
                </div>
                
                <div className="flex flex-col gap-3">
                  <button 
                    onClick={() => handleJoinTeam(showJoinModal.eventId)}
                    disabled={isProcessing}
                    className="w-full py-5 bg-slate-900 text-white rounded-[2rem] font-black uppercase text-[11px] tracking-[0.2em] shadow-xl shadow-gray-200 hover:bg-black transition-all active:scale-95 disabled:opacity-50"
                  >
                    {isProcessing ? 'AUTHENTICATING...' : 'Validate & Join'}
                  </button>
                  <button onClick={() => setShowJoinModal(null)} className="w-full py-4 text-gray-400 font-black uppercase text-[9px] tracking-widest hover:text-slate-600 transition-colors">Dismiss</button>
                </div>
              </div>
            </div>
          </div>
        </Portal>
      )}
    </div>
  );
};
