import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom/client';
import {
    getAuth,
    onAuthStateChanged,
    signInWithEmailAndPassword,
    createUserWithEmailAndPassword,
    signOut,
    updatePassword,
    updateEmail,
    verifyBeforeUpdateEmail,
    updateProfile,
    sendEmailVerification,
    sendPasswordResetEmail,
    GoogleAuthProvider,
    signInWithPopup
} from 'firebase/auth';
import {
    getFirestore,
    collection,
    query,
    where,
    getDocs,
    getDoc,
    doc,
    setDoc,
    updateDoc,
    deleteDoc,
    addDoc,
    onSnapshot,
    serverTimestamp,
    orderBy,
    limit,
    increment
} from 'firebase/firestore';
import { initializeApp } from 'firebase/app';
import {
    User, Shield, Building2, LogOut, Plus, Trash2, CheckCircle, XCircle,
    Newspaper, MessageSquare, Menu, X, Heart, Briefcase, Send,
    MessageCircle, IndianRupee, Check, Settings, Lock, Search, AlertCircle, Clock, Edit2, AlertTriangle, FileText,
    BookOpen, Users, Mail, Star, ThumbsUp, Activity, Server, Megaphone, Award
} from 'lucide-react';

// --- MCP CONFIGURATION (Integrated) ---
const MCP_CONFIG = {
    "servers": {
        "SOH Docs": {
            "type": "sse",
            "url": "https://gitmcp.io/rajsimariaa/SOH"
        }
    }
};
console.log("MCP Config Loaded:", MCP_CONFIG);

// --- EMAILJS CONFIGURATION ---
const EMAILJS_SERVICE_ID = "service_w5shhzk";
const EMAILJS_TEMPLATE_ID = "template_i4u4qdo";
const EMAILJS_PUBLIC_KEY = "Hts5u45i6F4kAqm2W";

(function () {
    if (typeof emailjs !== 'undefined') {
        emailjs.init(EMAILJS_PUBLIC_KEY);
    } else {
        console.error("EmailJS SDK not loaded.");
    }
})();

// --- FIREBASE CONFIGURATION ---


import { auth, db, firebaseConfig } from './db.js';

const SUPER_ADMINS = ['rajsimariaa@gmail.com', 'krutika3011@gmail.com'];
const UPI_ID = "rajsimariaa-2@okaxis";

// --- EMAIL HELPER SYSTEM ---
const sendSystemEmail = async (to, subject, html) => {
    if (!to) return false;
    if (EMAILJS_SERVICE_ID === "YOUR_SERVICE_ID") return false;

    const recipients = Array.isArray(to) ? to : [to];
    let successCount = 0;

    for (const recipient of recipients) {
        const templateParams = { to_email: recipient, subject: subject, message: html };
        try {
            await window.emailjs.send(EMAILJS_SERVICE_ID, EMAILJS_TEMPLATE_ID, templateParams);
            successCount++;
        } catch (error) {
            console.error(`❌ Failed to send email to ${recipient}:`, error);
        }
    }
    return successCount > 0;
};

// --- UI COMPONENTS ---
const Button = ({ children, onClick, variant = 'primary', className = '', type = 'button', disabled = false }) => {
    const baseStyle = "px-6 py-2.5 rounded-full font-semibold transition-all duration-300 flex items-center justify-center gap-2 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transform hover:-translate-y-0.5 active:translate-y-0";
    const variants = {
        primary: "bg-gradient-to-r from-brand-600 to-brand-500 text-white hover:from-brand-500 hover:to-brand-400 focus:ring-brand-500 shadow-lg shadow-brand-500/30",
        secondary: "glass text-brand-700 border border-brand-200 hover:bg-brand-50 focus:ring-brand-400 shadow-sm",
        danger: "bg-gradient-to-r from-rose-600 to-rose-500 text-white hover:from-rose-500 hover:to-rose-400 focus:ring-rose-500 shadow-lg shadow-rose-500/30",
        ghost: "text-gray-600 hover:bg-brand-50 hover:text-brand-700",
        success: "bg-gradient-to-r from-emerald-600 to-emerald-500 text-white hover:from-emerald-500 hover:to-emerald-400 focus:ring-emerald-500 shadow-lg shadow-emerald-500/30"
    };
    return (
        <button type={type} onClick={onClick} disabled={disabled} className={`${baseStyle} ${variants[variant]} ${className}`}>
            {children}
        </button>
    );
};

const Card = ({ children, className = '' }) => (
    <div className={`glass rounded-2xl shadow-soft border border-white/50 overflow-hidden transition-all duration-300 hover:shadow-lg ${className}`}>
        {children}
    </div>
);

const Badge = ({ children, color = 'blue' }) => {
    const colors = {
        blue: 'bg-blue-100 text-blue-800',
        green: 'bg-green-100 text-green-800',
        red: 'bg-red-100 text-red-800',
        purple: 'bg-purple-100 text-purple-800',
        gray: 'bg-gray-100 text-gray-800',
        indigo: 'bg-indigo-100 text-indigo-800',
        orange: 'bg-orange-100 text-orange-800',
        yellow: 'bg-yellow-100 text-yellow-800'
    };
    return <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold ${colors[color] || colors.gray}`}>{children}</span>;
};

const StarRating = ({ rating }) => (
    <div className="flex text-yellow-400">
        {[...Array(5)].map((_, i) => (
            <Star key={i} size={14} fill={i < rating ? "currentColor" : "none"} className={i < rating ? "text-yellow-400" : "text-gray-300"} />
        ))}
    </div>
);

// --- TERMS MODAL ---
function TermsModal({ onClose }) {
    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
            <div className="bg-white rounded-xl shadow-2xl max-w-3xl w-full max-h-[85vh] flex flex-col">
                <div className="p-5 border-b border-gray-100 flex justify-between items-center bg-gray-50 rounded-t-xl">
                    <h3 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                        <FileText size={20} className="text-indigo-600" /> Platform Policies & Guidelines
                    </h3>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600 hover:bg-gray-200 rounded p-1 transition-colors"><X size={24} /></button>
                </div>
                <div className="p-6 overflow-y-auto text-sm text-gray-700 space-y-6 leading-relaxed">
                    <div className="bg-indigo-50 p-4 rounded-lg border border-indigo-100">
                        <h4 className="font-bold text-base text-indigo-900 mb-2">Contact Information</h4>
                        <div className="space-y-1 text-indigo-800">
                            <p><span className="font-semibold">Email:</span> help.shadesofhue@gmail.com</p>
                            <p><span className="font-semibold">Phone:</span> +91 9833201718 / +91 80970 86929</p>
                        </div>
                    </div>
                    <div>
                        <h4 className="font-bold text-lg text-gray-900 mb-2">Shades of Hue: Official Platform Policies and Guidelines</h4>
                        <p>These policies govern the conduct of all users, customers, and partnered organizations within the Shades of Hue platform.</p>
                    </div>
                    <div>
                        <h4 className="font-bold text-base text-gray-800 mb-2">I. Core Principles and Code of Conduct</h4>
                        <ul className="list-disc pl-5 mt-2 space-y-1">
                            <li><strong>Mission Alignment:</strong> All panel organizations must actively align with the mission of supporting and empowering the queer community.</li>
                            <li><strong>Respect and Professionalism:</strong> We enforce a Zero-Tolerance Policy for rude, aggressive, discriminatory, or harassing behavior.</li>
                            <li><strong>Prioritization of Stakeholders:</strong> The platform is dedicated to ensuring the highest quality service and privacy for our customers.</li>
                        </ul>
                    </div>
                    <div>
                        <h4 className="font-bold text-base text-gray-800 mb-2">II. Customer Privacy and Data Protection Policy</h4>
                        <ul className="list-disc pl-5 mt-2 space-y-1">
                            <li><strong>Anonymity & Confidentiality:</strong> User data is encrypted and handled in strict confidence.</li>
                            <li><strong>Limited Information Disclosure to Partners:</strong> Upon a confirmed match, partner organizations will only be provided with the minimal details required.</li>
                            <li><strong>Monitoring for Safety:</strong> All primary chat initiations are monitored by trained administrators.</li>
                        </ul>
                    </div>
                    <div>
                        <h4 className="font-bold text-base text-gray-800 mb-2">III. Service Request Management and Service Level Agreement (SLA)</h4>
                        <ul className="list-disc pl-5 mt-2 space-y-1">
                            <li><strong>Request Acceptance Window:</strong> Organizations must review requests within 10 business days.</li>
                            <li><strong>Mandatory Decline Rationale:</strong> A clear reason must be provided for declined requests.</li>
                            <li><strong>Optimal Matching Commitment:</strong> We commit to matching customers with the most suitable partner.</li>
                        </ul>
                    </div>
                    <div>
                        <h4 className="font-bold text-base text-gray-800 mb-2">IV. Accountability and Quality Assurance</h4>
                        <ul className="list-disc pl-5 mt-2 space-y-1">
                            <li><strong>Grounds for a Strike:</strong> Strikes issued for failure to satisfy needs or poor conduct.</li>
                            <li><strong>Suspension Protocol:</strong> One strike leads to a 30-day suspension of new leads.</li>
                            <li><strong>Account Deletion Protocol:</strong> 3 or more strikes result in permanent account deletion.</li>
                            <li><strong>Unresponsive Behaviour:</strong> Penalty of 200 per day for unresponsiveness over 1 week without genuine reason.</li>
                        </ul>
                    </div>
                    <div>
                        <h4 className="font-bold text-base text-gray-800 mb-2">V. Ethical Conduct and Termination</h4>
                        <ul className="list-disc pl-5 mt-2 space-y-1">
                            <li><strong>Zero-Tolerance for Customer Poaching:</strong> Poaching customers off-platform results in immediate termination.</li>
                            <li><strong>Mandatory Reporting:</strong> Partners must report disruptive customer behavior.</li>
                            <li><strong>Voluntary Termination Notice:</strong> 30-day notice required for partners leaving the platform.</li>
                        </ul>
                    </div>
                    <div>
                        <h4 className="font-bold text-base text-gray-800 mb-2">VI. Policy Changes</h4>
                        <ul className="list-disc pl-5 mt-2 space-y-1">
                            <li><strong>Advance Notice:</strong> 15 days' notice provided for major policy changes.</li>
                        </ul>
                    </div>
                </div>
                <div className="p-5 border-t border-gray-100 bg-gray-50 rounded-b-xl flex justify-end">
                    <Button onClick={onClose}>Close</Button>
                </div>
            </div>
        </div>
    );
}

// --- FEEDBACK MODAL ---
function FeedbackModal({ onClose, onSubmit }) {
    const [rating, setRating] = useState(0);
    const [comment, setComment] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        if (rating === 0) {
            alert("Please select a rating!");
            return;
        }
        onSubmit({ rating, comment });
    };

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
            <div className="bg-white rounded-xl shadow-2xl max-w-md w-full p-6">
                <div className="text-center mb-6">
                    <div className="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center text-yellow-600 mx-auto mb-3">
                        <Star size={24} fill="currentColor" />
                    </div>
                    <h3 className="text-xl font-bold text-gray-900">Rate Your Experience</h3>
                    <p className="text-gray-500 text-sm mt-1">How was the service provided?</p>
                </div>

                <form onSubmit={handleSubmit} className="space-y-6">
                    <div className="flex justify-center gap-2">
                        {[1, 2, 3, 4, 5].map((star) => (
                            <button
                                key={star}
                                type="button"
                                onClick={() => setRating(star)}
                                className="focus:outline-none transition-transform hover:scale-110"
                            >
                                <Star
                                    size={32}
                                    fill={star <= rating ? "#FACC15" : "none"}
                                    className={star <= rating ? "text-yellow-400" : "text-gray-300"}
                                />
                            </button>
                        ))}
                    </div>

                    <textarea
                        className="w-full p-3 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 outline-none resize-none"
                        rows={4}
                        placeholder="Share your feedback (optional)..."
                        value={comment}
                        onChange={(e) => setComment(e.target.value)}
                    />

                    <div className="flex gap-3">
                        <Button variant="secondary" onClick={onClose} className="flex-1">Cancel</Button>
                        <Button type="submit" className="flex-1">Submit Feedback</Button>
                    </div>
                </form>
            </div>
        </div>
    );
}

// --- DECLINE REASON MODAL ---
function DeclineModal({ onClose, onSubmit }) {
    const [reason, setReason] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        if (!reason.trim()) {
            alert("Please provide a reason for declining.");
            return;
        }
        onSubmit(reason);
    };

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
            <div className="bg-white rounded-xl shadow-2xl max-w-md w-full p-6">
                <div className="flex justify-between items-center mb-4">
                    <h3 className="text-xl font-bold text-red-600 flex items-center gap-2">
                        <XCircle size={24} /> Decline Request
                    </h3>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><X size={24} /></button>
                </div>

                <p className="text-sm text-gray-600 mb-4">
                    Per platform policy, you must provide a reason for declining this request.
                </p>

                <form onSubmit={handleSubmit} className="space-y-4">
                    <textarea
                        className="w-full p-3 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-red-500 outline-none resize-none"
                        rows={4}
                        placeholder="E.g., Capacity issues, specialization mismatch, conflict of interest..."
                        value={reason}
                        onChange={(e) => setReason(e.target.value)}
                        required
                    />

                    <div className="flex gap-3">
                        <Button variant="secondary" onClick={onClose} className="flex-1">Cancel</Button>
                        <Button type="submit" variant="danger" className="flex-1">Confirm Decline</Button>
                    </div>
                </form>
            </div>
        </div>
    );
}

// --- FOOTER COMPONENT ---
function Footer({ onShowTerms }) {
    return (
        <footer className="bg-white border-t border-gray-200 mt-12 py-8">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col md:flex-row justify-between items-center gap-4">
                <div className="flex items-center gap-2">
                    <img src="logo.png" alt="Logo" className="w-8 h-8 object-contain" />
                    <span className="font-bold text-gray-900">Shades of Hue</span>
                </div>
                <div className="flex flex-wrap justify-center gap-6 text-sm text-gray-500">
                    <span>&copy; {new Date().getFullYear()} Shades of Hue. All rights reserved.</span>
                    <button
                        onClick={onShowTerms}
                        className="hover:text-indigo-600 transition-colors underline"
                    >
                        Terms & Conditions
                    </button>
                    <span><a href="https://rajsimaria.vercel.app/">Made by Raj Simaria</a></span>
                </div>
            </div>
        </footer>
    );
}

// --- NAVBAR COMPONENT ---
function Navbar({ user, role, onNavigate, onSignOut, currentView }) {
    const [isOpen, setIsOpen] = useState(false);
    const NavLink = ({ target, label, icon: Icon }) => (
        <button onClick={() => { onNavigate(target); setIsOpen(false); }} className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-semibold transition-all duration-300 ${currentView === target ? 'bg-brand-100 text-brand-700 shadow-sm' : 'text-gray-600 hover:bg-brand-50 hover:text-brand-700'}`}>
            {Icon && <Icon size={18} />} {label}
        </button>
    );
    const roleLabel = role ? role.charAt(0).toUpperCase() + role.slice(1) : 'User';

    return (
        <nav className="glass sticky top-0 z-50 border-b border-brand-100 shadow-sm">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="flex justify-between h-20">
                    <div className="flex items-center">
                        <button onClick={() => onNavigate('home')} className="flex-shrink-0 flex items-center gap-3 cursor-pointer group">
                            <img src="logo.png" alt="Logo" className="w-10 h-10 object-contain group-hover:scale-105 transition-transform duration-300" />
                            <span className="font-bold text-2xl tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-brand-700 to-purple-600">Shades of Hue</span>
                        </button>
                    </div>
                    <div className="hidden md:flex items-center space-x-4">
                        <NavLink target="home" label="Home" icon={Newspaper} />
                        {!user ? (
                            <>
                                <Button variant="ghost" onClick={() => onNavigate('login')}>Sign In</Button>
                                <Button variant="primary" onClick={() => onNavigate('signup')}>Join Us</Button>
                            </>
                        ) : (
                            <>
                                {role && <NavLink target="dashboard" label={`${roleLabel} Dashboard`} icon={Briefcase} />}
                                <div className="border-l border-gray-300 h-6 mx-2"></div>
                                <div className="flex items-center gap-3">
                                    <div className="text-right hidden lg:block">
                                        <p className="text-sm font-medium text-gray-900">{user.email}</p>
                                        <p className="text-xs text-gray-500 capitalize">{role || '...'}</p>
                                    </div>
                                    <Button variant="secondary" onClick={onSignOut} className="!px-3"><LogOut size={16} /></Button>
                                </div>
                            </>
                        )}
                    </div>
                    <div className="flex items-center md:hidden">
                        <button onClick={() => setIsOpen(!isOpen)} className="text-gray-600 hover:text-gray-900 p-2">{isOpen ? <X size={24} /> : <Menu size={24} />}</button>
                    </div>
                </div>
            </div>
            {isOpen && (
                <div className="md:hidden bg-white border-b border-gray-200 px-2 pt-2 pb-3 space-y-1">
                    <NavLink target="home" label="Home" icon={Newspaper} />
                    {user && role && <NavLink target="dashboard" label="Dashboard" icon={Briefcase} />}
                    {!user ? (
                        <div className="flex flex-col gap-2 p-2 mt-2 border-t border-gray-100">
                            <Button variant="secondary" onClick={() => { onNavigate('login'); setIsOpen(false); }}>Sign In</Button>
                            <Button variant="primary" onClick={() => { onNavigate('signup'); setIsOpen(false); }}>Join Us</Button>
                        </div>
                    ) : (
                        <div className="flex flex-col gap-2 p-2 mt-2 border-t border-gray-100"><Button variant="danger" onClick={() => { onSignOut(); setIsOpen(false); }}>Sign Out</Button></div>
                    )}
                </div>
            )}
        </nav>
    );
}

function ChatWindow({ chatId, onClose, currentUser }) {
    const [messages, setMessages] = useState([]);
    const [newMessage, setNewMessage] = useState('');
    const [chatInfo, setChatInfo] = useState(null);
    const bottomRef = useRef(null);

    useEffect(() => {
        const fetchChatInfo = async () => {
            try {
                const docSnap = await getDoc(doc(db, 'chats', chatId));
                if (docSnap.exists()) setChatInfo(docSnap.data());
            } catch (e) { console.error("Chat info error:", e); }
        };
        fetchChatInfo();
        const q = query(collection(db, 'chats', chatId, 'messages'), orderBy('timestamp', 'asc'));
        const unsubscribe = onSnapshot(q, (snapshot) => {
            setMessages(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
            setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
        }, (error) => console.error("Chat messages error:", error));
        return () => unsubscribe();
    }, [chatId]);

    const sendMessage = async (e) => {
        e.preventDefault();
        if (!newMessage.trim()) return;
        try {
            await addDoc(collection(db, 'chats', chatId, 'messages'), {
                text: newMessage, senderId: currentUser.uid, senderEmail: currentUser.email, timestamp: serverTimestamp()
            });
            await updateDoc(doc(db, 'chats', chatId), { lastMessage: newMessage, lastMessageTime: serverTimestamp() });
            setNewMessage('');
        } catch (error) { console.error("Error sending message:", error); }
    };

    const getOtherParticipantName = () => {
        if (!chatInfo || !chatInfo.participantData) return "Chat";
        const otherUid = chatInfo.participants.find(uid => uid !== currentUser.uid);
        const participant = chatInfo.participantData[otherUid];
        return participant?.name || "User";
    };

    return (
        <div className="fixed bottom-4 right-4 w-96 h-[500px] bg-white rounded-xl shadow-2xl border border-gray-200 flex flex-col z-50 overflow-hidden">
            <div className="bg-indigo-600 text-white p-4 flex justify-between items-center shrink-0">
                <div className="flex items-center gap-2"><MessageCircle size={20} /><span className="font-bold truncate">{getOtherParticipantName()}</span></div>
                <button onClick={onClose} className="hover:bg-indigo-700 p-1 rounded"><X size={18} /></button>
            </div>
            <div className="flex-grow p-4 overflow-y-auto bg-gray-50 flex flex-col gap-3">
                {messages.map((msg) => {
                    const isMe = msg.senderId === currentUser.uid;
                    return (
                        <div key={msg.id} className={`max-w-[80%] p-3 rounded-lg text-sm ${isMe ? 'bg-indigo-100 text-indigo-900 self-end rounded-br-none' : 'bg-white border border-gray-200 text-gray-800 self-start rounded-bl-none'}`}>
                            <p>{msg.text}</p>
                            <p className={`text-[10px] mt-1 ${isMe ? 'text-indigo-400' : 'text-gray-400'}`}>{msg.timestamp?.toDate ? msg.timestamp.toDate().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '...'}</p>
                        </div>
                    );
                })}
                <div ref={bottomRef} />
            </div>
            <form onSubmit={sendMessage} className="p-3 bg-white border-t border-gray-100 flex gap-2 shrink-0">
                <input type="text" value={newMessage} onChange={(e) => setNewMessage(e.target.value)} placeholder="Type a message..." className="flex-grow px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm" />
                <button type="submit" disabled={!newMessage.trim()} className="p-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"><Send size={18} /></button>
            </form>
        </div>
    );
}

function CommonGrievanceList({ user, role }) {
    const [grievances, setGrievances] = useState([]);
    const [subject, setSubject] = useState('');
    const [description, setDescription] = useState('');
    const [msg, setMsg] = useState('');

    useEffect(() => {
        const q = query(collection(db, 'grievances'), where('userId', '==', user.uid));
        const unsub = onSnapshot(q, (s) => setGrievances(s.docs.map(d => ({ id: d.id, ...d.data() }))), (error) => console.error("Grievance List Error:", error));
        return () => unsub();
    }, [user.uid]);

    const submitGrievance = async (e) => {
        e.preventDefault();
        await addDoc(collection(db, 'grievances'), {
            userId: user.uid,
            userEmail: user.email,
            userName: user.displayName || user.email,
            userRole: role,
            subject,
            description,
            status: 'pending',
            createdAt: serverTimestamp()
        });

        // EMAIL: Notify Super Admins of new Grievance
        sendSystemEmail(
            SUPER_ADMINS,
            `New Grievance: ${subject}`,
            `<p>A new grievance ticket has been submitted by <strong>${user.email}</strong>.</p>
                     <p><strong>Subject:</strong> ${subject}</p>
                     <p><strong>Description:</strong> ${description}</p>`
        );

        setSubject(''); setDescription('');
        setMsg("Grievance submitted successfully.");
        setTimeout(() => setMsg(''), 3000);
    };

    return (
        <div className="space-y-6">
            <Card className="p-6">
                <h3 className="font-bold mb-4">Submit Grievance</h3>
                {msg && <div className="mb-4 p-3 bg-green-50 text-green-700 rounded-lg text-sm">{msg}</div>}
                <form onSubmit={submitGrievance} className="space-y-4">
                    <input className="w-full p-2 border rounded" placeholder="Subject" value={subject} onChange={e => setSubject(e.target.value)} required />
                    <textarea className="w-full p-2 border rounded" rows={3} placeholder="Describe your issue..." value={description} onChange={e => setDescription(e.target.value)} required />
                    <Button type="submit">Submit</Button>
                </form>
            </Card>
            <Card className="p-6">
                <h3 className="font-bold mb-4">My Grievances</h3>
                <div className="space-y-2">
                    {grievances.map(g => (
                        <div key={g.id} className="p-3 border rounded bg-gray-50">
                            <div className="flex justify-between font-bold"><span>{g.subject}</span><Badge color={g.status === 'resolved' ? 'green' : 'red'}>{g.status}</Badge></div>
                            <p className="text-sm mt-1">{g.description}</p>
                        </div>
                    ))}
                    {grievances.length === 0 && <p className="text-gray-500">No records found.</p>}
                </div>
            </Card>
        </div>
    );
}

function Home({ user, onNavigate }) {
    const [news, setNews] = useState([]);
    useEffect(() => {
        const unsubscribe = onSnapshot(query(collection(db, 'news'), orderBy('createdAt', 'desc')),
            (snapshot) => setNews(snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))),
            (error) => console.error("News error:", error)
        );
        return () => unsubscribe();
    }, []);

    return (
        <div className="space-y-16 animate-fade-in">
            <section className="text-center space-y-8 py-20 relative overflow-hidden">
                <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[800px] h-[500px] bg-brand-300/30 rounded-full blur-[100px] -z-10 animate-pulse"></div>
                <h1 className="text-5xl md:text-7xl font-extrabold text-gray-900 tracking-tight animate-slide-up">Empowering the <span className="bg-clip-text text-transparent bg-gradient-to-r from-brand-600 to-purple-600">Queer Community</span></h1>
                <p className="max-w-2xl mx-auto text-lg md:text-xl text-gray-600 animate-slide-up" style={{ animationDelay: '0.1s' }}>Connecting you with inclusive services, supportive organizations, and a community that cares.</p>
                {!user && <div className="flex justify-center gap-4 animate-slide-up" style={{ animationDelay: '0.2s' }}><Button onClick={() => onNavigate('signup')} className="!text-lg !px-8 !py-3 shadow-xl">Get Started</Button><Button variant="secondary" onClick={() => onNavigate('login')} className="!text-lg !px-8 !py-3">Sign In</Button></div>}
            </section>

            {/* Mission & Vision */}
            <div className="grid md:grid-cols-2 gap-8">
                <Card className="p-8 bg-gradient-to-br from-indigo-50 to-white border-indigo-100">
                    <div className="flex items-center gap-3 mb-4"><div className="p-2 bg-indigo-100 rounded-lg text-indigo-600"><Heart size={24} /></div><h2 className="text-2xl font-bold text-gray-900">Our Mission</h2></div>
                    <p className="text-gray-600 leading-relaxed">To provide a safe, accessible, and affirmative platform for Queer individuals to access essential services.</p>
                </Card>
                <Card className="p-8 bg-gradient-to-br from-purple-50 to-white border-purple-100">
                    <div className="flex items-center gap-3 mb-4"><div className="p-2 bg-purple-100 rounded-lg text-purple-600"><Shield size={24} /></div><h2 className="text-2xl font-bold text-gray-900">Our Vision</h2></div>
                    <p className="text-gray-600 leading-relaxed">A world where every Queer individual has equal access to healthcare, legal aid, housing, and community support.</p>
                </Card>
            </div>

            {/* Services Section */}
            <section className="py-8">
                <div className="text-center mb-8">
                    <h2 className="text-3xl font-bold text-gray-900">Our Services</h2>
                    <p className="text-gray-600 mt-2">Holistic support for the community.</p>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    {[
                        { icon: BookOpen, title: "Skill Development", desc: "Training programs to enhance your professional skillset." },
                        { icon: Briefcase, title: "Employment", desc: "Connecting you with inclusive employers and job opportunities." },
                        { icon: Users, title: "Inclusivity Workshops", desc: "Sensitization and awareness sessions for organizations." },
                        { icon: Heart, title: "Mental Health", desc: "Counseling and support groups for emotional well-being." }
                    ].map((s, i) => (
                        <Card key={i} className="p-6 text-center hover:shadow-md transition-shadow">
                            <div className="w-12 h-12 mx-auto bg-indigo-50 rounded-full flex items-center justify-center text-indigo-600 mb-4">
                                <s.icon size={24} />
                            </div>
                            <h3 className="font-bold text-lg text-gray-900 mb-2">{s.title}</h3>
                            <p className="text-sm text-gray-600">{s.desc}</p>
                        </Card>
                    ))}
                </div>
            </section>

            <section>
                <div className="flex items-center gap-3 mb-6"><Newspaper className="text-indigo-600" /><h2 className="text-2xl font-bold text-gray-900">Latest Updates</h2></div>
                <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                    {news.length > 0 ? news.map(item => (
                        <Card key={item.id} className="p-6 flex flex-col h-full hover:shadow-md transition-shadow">
                            <div className="mb-4"><span className="text-xs font-medium text-gray-500">{item.createdAt?.toDate ? item.createdAt.toDate().toLocaleDateString() : 'Just now'}</span><h3 className="text-xl font-bold text-gray-900 mt-1">{item.title}</h3></div>
                            <p className="text-gray-600 text-sm flex-grow whitespace-pre-wrap">{item.content}</p>
                        </Card>
                    )) : <div className="col-span-full text-center py-12 bg-gray-50 rounded-xl border border-dashed border-gray-300 text-gray-500">No news updates yet. Stay tuned!</div>}
                </div>
            </section>
        </div>
    );
}

// --- LOGIN COMPONENT (UPDATED FOR RESET) ---
function Login({ onNavigate }) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');

    // Password Reset States
    const [resetMode, setResetMode] = useState(false);
    const [resetEmail, setResetEmail] = useState('');
    const [resetMsg, setResetMsg] = useState('');

    const handleLogin = async (e) => {
        e.preventDefault();
        setError('');
        try {
            await signInWithEmailAndPassword(auth, email, password);
            onNavigate('home');
        } catch (err) {
            setError("Failed to login. Please check your credentials.");
        }
    };

    const handleReset = async (e) => {
        e.preventDefault();
        setResetMsg('');
        setError('');

        if (!resetEmail) {
            setError("Please enter your email address.");
            return;
        }

        try {
            await sendPasswordResetEmail(auth, resetEmail);
            setResetMsg("Password reset link sent! Please check your email.");
        } catch (err) {
            // Firebase errors for reset
            if (err.code === 'auth/user-not-found') {
                setError("No account found with this email.");
            } else if (err.code === 'auth/invalid-email') {
                setError("Invalid email address.");
            } else {
                setError("Failed to send reset email: " + err.message);
            }
        }
    };

    const handleGoogleSignIn = async () => {
        setError('');
        try {
            const provider = new GoogleAuthProvider();
            const result = await signInWithPopup(auth, provider);
            const user = result.user;

            // Check if user exists in DB, if not create a basic profile
            const userDoc = await getDoc(doc(db, 'users', user.uid));
            if (!userDoc.exists()) {
                await setDoc(doc(db, 'users', user.uid), {
                    uid: user.uid,
                    email: user.email,
                    displayName: user.displayName || 'User',
                    identity: 'Prefer not to say',
                    pronouns: 'Prefer not to say',
                    role: 'user',
                    isActive: true,
                    termsAccepted: true,
                    termsAcceptedAt: serverTimestamp(),
                    createdAt: serverTimestamp(),
                    lastSeen: serverTimestamp()
                });
            }
            onNavigate('home');
        } catch (err) {
            setError("Google sign-in failed: " + err.message);
        }
    };

    // If in Reset Mode, show Reset Form
    if (resetMode) {
        return (
            <div className="max-w-md mx-auto mt-12">
                <Card className="p-8">
                    <div className="text-center mb-8">
                        <div className="mx-auto w-12 h-12 bg-indigo-100 rounded-full flex items-center justify-center text-indigo-600 mb-4">
                            <Lock size={24} />
                        </div>
                        <h2 className="text-2xl font-bold text-gray-900">Reset Password</h2>
                        <p className="text-gray-500 mt-2">Enter your email to receive a reset link</p>
                    </div>

                    {resetMsg && <div className="p-3 bg-green-50 text-green-700 text-sm rounded-lg mb-6 flex items-center gap-2"><CheckCircle size={16} /> {resetMsg}</div>}
                    {error && <div className="p-3 bg-red-50 text-red-700 text-sm rounded-lg mb-6 flex items-center gap-2"><AlertCircle size={16} /> {error}</div>}

                    <form onSubmit={handleReset} className="space-y-6">
                        <input
                            type="email"
                            placeholder="Enter your email address"
                            required
                            className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500"
                            value={resetEmail}
                            onChange={(e) => setResetEmail(e.target.value)}
                        />
                        <Button type="submit" className="w-full">Send Reset Link</Button>
                    </form>

                    <button
                        onClick={() => { setResetMode(false); setError(''); setResetMsg(''); }}
                        className="w-full text-center mt-6 text-sm text-gray-600 hover:text-indigo-600 font-medium transition-colors"
                    >
                        Back to Login
                    </button>
                </Card>
            </div>
        );
    }

    // Default Login Form
    return (
        <div className="max-w-md mx-auto mt-12">
            <Card className="p-8">
                <div className="text-center mb-8">
                    <h2 className="text-2xl font-bold text-gray-900">Welcome Back</h2>
                    <p className="text-gray-500 mt-2">Sign in to your account</p>
                </div>
                <form onSubmit={handleLogin} className="space-y-6">
                    {error && <div className="p-3 bg-red-50 text-red-700 text-sm rounded-lg">{error}</div>}
                    <input type="email" placeholder="Email Address" required className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500" value={email} onChange={(e) => setEmail(e.target.value)} />
                    <input type="password" placeholder="Password" required className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500" value={password} onChange={(e) => setPassword(e.target.value)} />

                    {/* Forgot Password Link */}
                    <div className="flex justify-end">
                        <button
                            type="button"
                            onClick={() => setResetMode(true)}
                            className="text-sm text-indigo-600 hover:text-indigo-800 font-medium hover:underline"
                        >
                            Forgot Password?
                        </button>
                    </div>

                    <Button type="submit" className="w-full">Sign In</Button>
                </form>

                <div className="mt-6">
                    <div className="relative">
                        <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-300"></div></div>
                        <div className="relative flex justify-center text-sm"><span className="px-2 bg-white text-gray-500">Or continue with</span></div>
                    </div>
                    <Button type="button" variant="secondary" className="w-full mt-4" onClick={handleGoogleSignIn}>
                        <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
                            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                            <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                        </svg>
                        Google
                    </Button>
                </div>

                <p className="text-center mt-6 text-sm text-gray-600">Don't have an account? <button onClick={() => onNavigate('signup')} className="text-indigo-600 font-medium hover:underline">Sign up</button></p>
            </Card>
        </div>
    );
}

function Signup({ onNavigate }) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [name, setName] = useState('');
    const [identity, setIdentity] = useState('');
    const [pronouns, setPronouns] = useState('');
    const [error, setError] = useState('');
    const [agreed, setAgreed] = useState(false);
    const [showTerms, setShowTerms] = useState(false);

    const handleSignup = async (e) => {
        e.preventDefault();
        if (!agreed) {
            setError("You must agree to the Terms and Conditions to create an account.");
            return;
        }

        try {
            const userCredential = await createUserWithEmailAndPassword(auth, email, password);

            // Create User DB Entry 
            await setDoc(doc(db, 'users', userCredential.user.uid), {
                uid: userCredential.user.uid,
                email,
                displayName: name,
                identity: identity || 'Prefer not to say',
                pronouns: pronouns || 'Prefer not to say',
                role: 'user',
                isActive: true,
                termsAccepted: true,
                termsAcceptedAt: serverTimestamp(),
                createdAt: serverTimestamp(),
                lastSeen: serverTimestamp()
            });

            // EMAIL: Send Welcome Email
            sendSystemEmail(
                email,
                "Welcome to Shades of Hue!",
                `<p>Hi ${name},</p>
                        <p>Welcome to <strong>Shades of Hue</strong>! We are thrilled to have you as part of our community.</p>
                        <p>Feel free to explore our services and connect with organizations.</p>
                        <p>Best Regards,<br>The Shades of Hue Team</p>`
            );

            // Send verification email immediately for new users
            await sendEmailVerification(userCredential.user);
            alert("Account created! We've sent a verification email to " + email + ". Please verify it to access your dashboard.");

            onNavigate('home');
        } catch (err) {
            setError(err.message);
        }
    };

    const handleGoogleSignUp = async () => {
        if (!agreed) {
            setError("You must agree to the Terms and Conditions to sign up with Google.");
            return;
        }
        setError('');
        try {
            const provider = new GoogleAuthProvider();
            const result = await signInWithPopup(auth, provider);
            const user = result.user;

            const userDoc = await getDoc(doc(db, 'users', user.uid));
            if (!userDoc.exists()) {
                await setDoc(doc(db, 'users', user.uid), {
                    uid: user.uid,
                    email: user.email,
                    displayName: name || user.displayName || 'User',
                    identity: identity || 'Prefer not to say',
                    pronouns: pronouns || 'Prefer not to say',
                    role: 'user',
                    isActive: true,
                    termsAccepted: true,
                    termsAcceptedAt: serverTimestamp(),
                    createdAt: serverTimestamp(),
                    lastSeen: serverTimestamp()
                });

                // Send Welcome Email
                sendSystemEmail(
                    user.email,
                    "Welcome to Shades of Hue!",
                    `<p>Hi ${name || user.displayName || 'there'},</p>
                            <p>Welcome to <strong>Shades of Hue</strong>! We are thrilled to have you as part of our community.</p>
                            <p>Feel free to explore our services and connect with organizations.</p>
                            <p>Best Regards,<br>The Shades of Hue Team</p>`
                );
            }
            onNavigate('home');
        } catch (err) {
            setError("Google sign-up failed: " + err.message);
        }
    };

    return (
        <div className="max-w-md mx-auto mt-12">
            <Card className="p-8">
                <div className="text-center mb-8"><h2 className="text-2xl font-bold text-gray-900">Join Shades of Hue</h2><p className="text-gray-500 mt-2">Create your account today</p></div>
                <form onSubmit={handleSignup} className="space-y-6">
                    {error && <div className="p-3 bg-red-50 text-red-700 text-sm rounded-lg">{error}</div>}
                    <input type="text" placeholder="Full Name" required className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500" value={name} onChange={(e) => setName(e.target.value)} />
                    <input type="email" placeholder="Email Address" required className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500" value={email} onChange={(e) => setEmail(e.target.value)} />

                    <div className="grid grid-cols-2 gap-4">
                        <select required className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500 text-gray-700 bg-white" value={identity} onChange={(e) => setIdentity(e.target.value)}>
                            <option value="" disabled>Gender/Sexuality</option>
                            <option value="Lesbian">Lesbian</option>
                            <option value="Gay">Gay</option>
                            <option value="Bisexual">Bisexual</option>
                            <option value="Transgender">Transgender</option>
                            <option value="Queer">Queer</option>
                            <option value="Intersex">Intersex</option>
                            <option value="Asexual">Asexual</option>
                            <option value="Pansexual">Pansexual</option>
                            <option value="Non-binary">Non-binary</option>
                            <option value="Genderfluid">Genderfluid</option>
                            <option value="Agender">Agender</option>
                            <option value="Heterosexual/Straight">Heterosexual/Straight</option>
                            <option value="Prefer not to say">Prefer not to say</option>
                            <option value="Other">Other</option>
                        </select>
                        <select required className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500 text-gray-700 bg-white" value={pronouns} onChange={(e) => setPronouns(e.target.value)}>
                            <option value="" disabled>Pronouns</option>
                            <option value="He/Him">He/Him</option>
                            <option value="She/Her">She/Her</option>
                            <option value="They/Them">They/Them</option>
                            <option value="He/They">He/They</option>
                            <option value="She/They">She/They</option>
                            <option value="Ze/Zir">Ze/Zir</option>
                            <option value="Prefer not to say">Prefer not to say</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>

                    <input type="password" placeholder="Password (min 6 chars)" required minLength={6} className="w-full px-4 py-2 rounded-lg border border-gray-300 outline-none focus:ring-2 focus:ring-indigo-500" value={password} onChange={(e) => setPassword(e.target.value)} />

                    <div className="flex items-start gap-2 text-sm text-gray-600 px-1">
                        <input
                            type="checkbox"
                            id="terms"
                            checked={agreed}
                            onChange={(e) => setAgreed(e.target.checked)}
                            className="mt-1"
                        />
                        <label htmlFor="terms">
                            I agree to the <button type="button" onClick={() => setShowTerms(true)} className="text-indigo-600 hover:underline font-medium">Terms and Conditions</button>
                        </label>
                    </div>

                    <Button type="submit" className="w-full">Sign Up</Button>
                </form>

                <div className="mt-6">
                    <div className="relative">
                        <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-300"></div></div>
                        <div className="relative flex justify-center text-sm"><span className="px-2 bg-white text-gray-500">Or continue with</span></div>
                    </div>
                    <Button type="button" variant="secondary" className="w-full mt-4" onClick={handleGoogleSignUp}>
                        <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
                            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                            <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                        </svg>
                        Google
                    </Button>
                </div>

                <p className="text-center mt-6 text-sm text-gray-600">Already have an account? <button onClick={() => onNavigate('login')} className="text-indigo-600 font-medium hover:underline">Sign in</button></p>
            </Card>
            {showTerms && <TermsModal onClose={() => setShowTerms(false)} />}
        </div>
    );
}

// --- SUB-COMPONENTS FOR ADMIN DASHBOARD ---
function AdminRequestMonitor() {
    const [requests, setRequests] = useState([]);

    useEffect(() => {
        const q = query(collection(db, 'requests'), orderBy('createdAt', 'desc'));
        const unsub = onSnapshot(q, (s) => {
            const data = s.docs.map(d => ({ id: d.id, ...d.data() }));
            setRequests(data);
        }, (error) => console.error("Request Monitor Error:", error));
        return () => unsub();
    }, []);

    return (
        <Card className="p-6">
            <h3 className="font-bold text-gray-900 mb-6 flex items-center gap-2">
                <Activity size={20} className="text-indigo-600" /> Request Monitor
            </h3>
            <div className="space-y-4">
                {requests.map(req => (
                    <div key={req.id} className="p-4 border border-gray-200 rounded-lg bg-white shadow-sm">
                        <div className="flex flex-col md:flex-row justify-between items-start gap-4">
                            <div className="flex-grow">
                                <div className="flex items-center gap-2 mb-1">
                                    <span className="font-bold text-gray-900 text-lg">{req.serviceName}</span>
                                    <Badge color={req.status === 'accepted' ? 'green' : req.status === 'declined' ? 'red' : req.status === 'in_progress' ? 'yellow' : req.status === 'completed' ? 'green' : req.status === 'cancelled' ? 'gray' : 'blue'}>
                                        {req.status === 'payment_review' ? 'Payment Review' : req.status}
                                    </Badge>
                                </div>
                                <div className="text-sm text-gray-600 grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-1 mt-2">
                                    <span><strong>User:</strong> {req.userName} ({req.userEmail})</span>
                                    <span><strong>Org:</strong> {req.orgName}</span>
                                    <span><strong>Price:</strong> {req.servicePrice ? `₹${req.servicePrice}` : 'Free'}</span>
                                    <span><strong>Date:</strong> {req.createdAt?.toDate ? req.createdAt.toDate().toLocaleDateString() : 'N/A'}</span>
                                </div>
                                {req.status === 'declined' && req.declineReason && (
                                    <div className="mt-3 p-3 bg-red-50 border border-red-100 rounded text-sm text-red-800">
                                        <strong>Reason for Decline:</strong> {req.declineReason}
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                ))}
                {requests.length === 0 && <div className="text-center text-gray-500 py-8">No requests found in the system.</div>}
            </div>
        </Card>
    );
}

// NEW: Admin Freelancer List
function AdminFreelancerList() {
    const [freelancers, setFreelancers] = useState([]);

    useEffect(() => {
        const q = query(collection(db, 'users'), where('role', '==', 'freelancer'));
        const unsub = onSnapshot(q, (s) => {
            setFreelancers(s.docs.map(d => ({ id: d.id, ...d.data() })));
        }, (error) => console.error("Freelancer Network Error:", error));
        return () => unsub();
    }, []);

    return (
        <Card className="p-6">
            <h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-2">
                <Megaphone className="text-indigo-600" /> Freelancer Network
            </h3>

            <div className="overflow-x-auto">
                <table className="w-full text-left text-sm">
                    <thead>
                        <tr className="border-b text-gray-500">
                            <th className="pb-2">Name / Email</th>
                            <th className="pb-2">Referral Code</th>
                            <th className="pb-2 text-center">Total Referrals</th>
                            <th className="pb-2 text-right">Total Earnings</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y">
                        {freelancers.map(f => (
                            <tr key={f.id} className="hover:bg-gray-50 transition-colors">
                                <td className="py-3">
                                    <div className="font-medium text-gray-900">{f.displayName}</div>
                                    <div className="text-xs text-gray-500">{f.email}</div>
                                </td>
                                <td>
                                    <span className="font-mono bg-indigo-50 text-indigo-700 px-2 py-1 rounded border border-indigo-100">{f.referralCode}</span>
                                </td>
                                <td className="text-center font-bold text-gray-700">
                                    {f.referralsCount || 0}
                                </td>
                                <td className="text-right font-bold text-green-600">
                                    ₹{f.earnings || 0}
                                </td>
                            </tr>
                        ))}
                        {freelancers.length === 0 && <tr><td colSpan="4" className="text-center py-6 text-gray-500">No freelancers found.</td></tr>}
                    </tbody>
                </table>
            </div>
        </Card>
    );
}

function AdminUserList() {
    const [users, setUsers] = useState([]);
    const [confirmingId, setConfirmingId] = useState(null);

    // Migration/Edit States
    const [migratingUser, setMigratingUser] = useState(null);
    const [newEmail, setNewEmail] = useState('');
    const [tempPassword, setTempPassword] = useState('');
    const [isMigrating, setIsMigrating] = useState(false);
    const [migrationLog, setMigrationLog] = useState('');

    useEffect(() => {
        const unsub = onSnapshot(collection(db, 'users'), (s) => {
            const data = s.docs.map(d => ({ id: d.id, ...d.data() }));
            data.sort((a, b) => {
                if (a.isActive !== b.isActive) return a.isActive ? -1 : 1;
                const timeA = a.lastSeen?.seconds || 0;
                const timeB = b.lastSeen?.seconds || 0;
                return timeB - timeA;
            });
            setUsers(data);
        }, (error) => console.error("User List Error:", error));
        return () => unsub();
    }, []);

    const toggleStatus = async (uid, status) => { await updateDoc(doc(db, 'users', uid), { isActive: !status }); };
    const deleteUser = async (uid) => { if (confirmingId === uid) { await deleteDoc(doc(db, 'users', uid)); setConfirmingId(null); } else { setConfirmingId(uid); setTimeout(() => setConfirmingId(null), 3000); } };

    const handleEditClick = (user) => {
        setMigratingUser(user);
        setNewEmail(user.email);
        setTempPassword('');
        setMigrationLog('');
    };

    const log = (msg) => setMigrationLog(prev => prev + "\n" + msg);

    // --- THE MIGRATION LOGIC ---
    const handleMigration = async (e) => {
        e.preventDefault();
        if (!migratingUser || !newEmail || !tempPassword) return;

        setIsMigrating(true);
        setMigrationLog("Starting account migration...");

        try {
            // 1. Create New Auth User (Secondary App)
            log("Creating new login credential...");
            const secondaryApp = initializeApp(firebaseConfig, "SecondaryMigration-" + Date.now());
            const secondaryAuth = getAuth(secondaryApp);
            const userCredential = await createUserWithEmailAndPassword(secondaryAuth, newEmail, tempPassword);
            const newUid = userCredential.user.uid;
            const oldUid = migratingUser.id;
            await signOut(secondaryAuth); // cleanup
            log(`New Account Created. UID: ${newUid}`);

            // 2. Copy User Profile
            log("Migrating user profile...");
            const userDoc = await getDoc(doc(db, 'users', oldUid));
            if (userDoc.exists()) {
                const userData = userDoc.data();
                await setDoc(doc(db, 'users', newUid), {
                    ...userData,
                    uid: newUid,
                    email: newEmail,
                    migratedFrom: oldUid,
                    migratedAt: serverTimestamp()
                });
            }

            // 3. Migrate Requests (Update userId/userEmail)
            log("Moving service requests...");
            const reqQuery = query(collection(db, 'requests'), where('userId', '==', oldUid));
            const reqDocs = await getDocs(reqQuery);
            let reqCount = 0;
            for (const d of reqDocs.docs) {
                await updateDoc(doc(db, 'requests', d.id), { userId: newUid, userEmail: newEmail });
                reqCount++;
            }
            log(`Moved ${reqCount} requests.`);

            // 4. Migrate Grievances
            log("Moving grievances...");
            const grievQuery = query(collection(db, 'grievances'), where('userId', '==', oldUid));
            const grievDocs = await getDocs(grievQuery);
            for (const d of grievDocs.docs) {
                await updateDoc(doc(db, 'grievances', d.id), { userId: newUid, userEmail: newEmail });
            }

            // 5. Migrate Chats (Complex: Update participants array and map keys)
            log("Migrating chat history...");
            const chatQuery = query(collection(db, 'chats'), where('participants', 'array-contains', oldUid));
            const chatDocs = await getDocs(chatQuery);
            for (const d of chatDocs.docs) {
                const chatData = d.data();
                const newParticipants = chatData.participants.map(p => p === oldUid ? newUid : p);
                const newParticipantData = { ...chatData.participantData };
                if (newParticipantData[oldUid]) {
                    newParticipantData[newUid] = { ...newParticipantData[oldUid], email: newEmail };
                    delete newParticipantData[oldUid];
                }

                await updateDoc(doc(db, 'chats', d.id), {
                    participants: newParticipants,
                    participantData: newParticipantData
                });

                // Update messages inside chat
                const msgQuery = query(collection(db, 'chats', d.id, 'messages'), where('senderId', '==', oldUid));
                const msgDocs = await getDocs(msgQuery);
                for (const m of msgDocs.docs) {
                    await updateDoc(doc(db, 'chats', d.id, 'messages', m.id), { senderId: newUid, senderEmail: newEmail });
                }
            }

            // 6. Delete Old Profile (Leave Auth orphan, but remove data access)
            log("Cleaning up old data...");
            await deleteDoc(doc(db, 'users', oldUid));

            // 7. Notify
            await sendSystemEmail(newEmail, "Your Login Has Changed - Shades of Hue",
                `<p>Hello ${migratingUser.displayName},</p>
                         <p>Your login credentials have been updated by an administrator.</p>
                         <p><strong>New Email:</strong> ${newEmail}</p>
                         <p><strong>Temporary Password:</strong> ${tempPassword}</p>
                         <p>Please login and change your password immediately.</p>`
            );

            log("Done! Success.");
            alert(`Migration Successful!\n\nNew Login: ${newEmail}\nPassword: ${tempPassword}\n\nPlease share this with the user.`);
            setMigratingUser(null);

        } catch (error) {
            console.error(error);
            log(`ERROR: ${error.message}`);
            alert(`Migration Failed: ${error.message}`);
        } finally {
            setIsMigrating(false);
        }
    };

    const runInactivityCheck = () => {
        let count = 0;
        users.forEach(u => {
            const diffDays = (new Date() - (u.lastSeen?.toDate() || 0)) / (864e5);
            if (diffDays > 14 && u.email) { sendSystemEmail(u.email, "We miss you", "Please login."); count++; }
        });
        alert(`Emails queued for ${count} users.`);
    };

    return (
        <Card className="p-6">
            <div className="flex flex-col sm:flex-row justify-between items-center mb-6 gap-4">
                <h3 className="text-xl font-bold text-gray-900">User Management</h3>
                <Button onClick={runInactivityCheck} variant="secondary" className="!text-xs gap-2">
                    <Clock size={14} /> Run Inactivity Check (14 Days)
                </Button>
            </div>

            <div className="overflow-x-auto"><table className="w-full text-left text-sm"><thead><tr className="border-b text-gray-500"><th>User</th><th>Role</th><th>Status</th><th>Last Seen</th><th>Account</th><th className="text-right">Actions</th></tr></thead><tbody className="divide-y">{users.map(u => {
                const isOnline = (new Date() - (u.lastSeen?.toDate() || 0)) / 60000 < 2;
                return (
                    <tr key={u.id} className={!u.isActive ? "bg-amber-50" : ""}>
                        <td className="py-3">
                            <div className="font-medium">
                                {u.displayName}
                                {u.pronouns && u.pronouns !== 'Prefer not to say' && <span className="text-xs text-gray-400 font-normal ml-1">({u.pronouns})</span>}
                            </div>
                            <div className="text-xs text-gray-500">{u.email}</div>
                            {u.identity && u.identity !== 'Prefer not to say' && <div className="text-[10px] text-indigo-500 mt-0.5 font-medium">{u.identity}</div>}
                        </td>
                        <td className="capitalize">
                            <Badge color={u.role === 'admin' ? 'purple' : u.role === 'organization' ? 'blue' : u.role === 'freelancer' ? 'yellow' : 'gray'}>{u.role}</Badge>
                            {u.role === 'organization' && <div className="text-[10px] text-gray-500 mt-1 font-medium flex items-center gap-1"><Award size={10} /> {u.completedRequests || 0} Completions</div>}
                        </td>
                        <td>{isOnline ? <span className="text-green-600 text-xs font-bold">Online</span> : <span className="text-gray-400 text-xs">Offline</span>}</td>
                        <td className="text-xs text-gray-500">{u.lastSeen?.toDate ? u.lastSeen.toDate().toLocaleString() : 'Never'}</td>
                        <td>{u.isActive ? <span className="text-green-600 flex items-center gap-1"><CheckCircle size={14} /> Active</span> : <span className="text-amber-600 flex items-center gap-1"><Clock size={14} /> Pending</span>}</td>
                        <td className="text-right space-x-2">
                            {!SUPER_ADMINS.includes(u.email) && <>
                                <button onClick={() => toggleStatus(u.id, u.isActive)} className="text-gray-400 hover:text-green-600 p-1">{u.isActive ? <XCircle size={16} /> : <CheckCircle size={16} />}</button>
                                <button onClick={() => handleEditClick(u)} className="text-gray-400 hover:text-indigo-600 p-1" title="Change Login"><Edit2 size={16} /></button>
                                <button onClick={() => deleteUser(u.id)} className={confirmingId === u.id ? "text-red-600 font-bold" : "text-gray-400 hover:text-red-600 p-1"}>{confirmingId === u.id ? "Sure?" : <Trash2 size={16} />}</button>
                            </>}
                        </td>
                    </tr>
                );
            })}</tbody></table></div>

            {/* MIGRATION MODAL */}
            {migratingUser && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[70] p-4">
                    <div className="bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
                        <h3 className="text-lg font-bold text-gray-900 mb-2">Change User Login</h3>
                        <p className="text-sm text-gray-500 mb-4">Migrate data for <strong>{migratingUser.displayName}</strong> to a new email.</p>
                        <div className="bg-amber-50 border border-amber-200 rounded p-3 mb-4 text-xs text-amber-800">
                            <strong>Warning:</strong> This creates a NEW account and moves all data (chats, requests) to it. The old login will stop working.
                        </div>
                        <form onSubmit={handleMigration} className="space-y-4">
                            <div><label className="block text-xs font-medium text-gray-700">New Email</label><input type="email" required className="w-full px-3 py-2 border rounded" value={newEmail} onChange={e => setNewEmail(e.target.value)} /></div>
                            <div><label className="block text-xs font-medium text-gray-700">Temporary Password</label><input type="text" required minLength={6} className="w-full px-3 py-2 border rounded" value={tempPassword} onChange={e => setTempPassword(e.target.value)} placeholder="Min 6 chars" /></div>

                            {migrationLog && <pre className="text-[10px] bg-gray-900 text-green-400 p-2 rounded h-24 overflow-y-auto">{migrationLog}</pre>}

                            <div className="flex gap-3">
                                <Button variant="secondary" onClick={() => setMigratingUser(null)} className="flex-1" disabled={isMigrating}>Cancel</Button>
                                <Button type="submit" className="flex-1" disabled={isMigrating}>{isMigrating ? 'Migrating...' : 'Change Login'}</Button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </Card>
    );
}

function AdminCreateUser() {
    const [form, setForm] = useState({ email: '', password: '', name: '', role: 'organization', identity: '', pronouns: '' });
    const [msg, setMsg] = useState({ type: '', text: '' });

    const handleCreate = async (e) => {
        e.preventDefault(); setMsg({ type: 'info', text: 'Creating...' });
        try {
            const secondaryApp = initializeApp(firebaseConfig, "Secondary-" + Date.now());
            const secAuth = getAuth(secondaryApp);
            const cred = await createUserWithEmailAndPassword(secAuth, form.email, form.password);

            // Specific fields based on role
            const extraData = {};
            if (form.role === 'organization') {
                extraData.description = 'New Org';
                extraData.services = [];
                extraData.isAvailable = true;
                extraData.completedRequests = 0; // Tracking
            } else if (form.role === 'freelancer') {
                // Generate a unique 6-character referral code (e.g. FL-X79K2P)
                extraData.referralCode = 'FL-' + Math.random().toString(36).substr(2, 6).toUpperCase();
                extraData.referralsCount = 0;
                extraData.earnings = 0;
            }

            await setDoc(doc(db, 'users', cred.user.uid), {
                uid: cred.user.uid,
                email: form.email,
                displayName: form.name,
                identity: form.identity || 'Prefer not to say',
                pronouns: form.pronouns || 'Prefer not to say',
                role: form.role,
                isActive: true,
                createdAt: serverTimestamp(),
                lastSeen: serverTimestamp(),
                ...extraData
            });

            // EMAIL: Notify user of Creation
            sendSystemEmail(
                form.email,
                "Account Created - Shades of Hue",
                `<p>Hello ${form.name},</p><p>An administrator has created a <strong>${form.role}</strong> account for you on Shades of Hue.</p><p>Your temporary password is: <strong>${form.password}</strong></p><p>Please login and change it immediately.</p>`
            );

            await signOut(secAuth); // Sign out secondary
            setMsg({ type: 'success', text: 'Created!' });
            setForm({ email: '', password: '', name: '', role: 'organization', identity: '', pronouns: '' });
        } catch (err) { setMsg({ type: 'error', text: err.message }); }
    };

    return (
        <Card className="p-8 max-w-xl mx-auto"><h3 className="text-xl font-bold mb-6">Create Account</h3><form onSubmit={handleCreate} className="space-y-4">{msg.text && <div className={`p-2 text-sm rounded ${msg.type === 'error' ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green-700'}`}>{msg.text}</div>}

            <div className="flex flex-wrap gap-4 mb-2">
                <label className="flex items-center gap-2"><input type="radio" checked={form.role === 'organization'} onChange={() => setForm({ ...form, role: 'organization' })} /> Org</label>
                <label className="flex items-center gap-2"><input type="radio" checked={form.role === 'freelancer'} onChange={() => setForm({ ...form, role: 'freelancer' })} /> Freelancer</label>
                <label className="flex items-center gap-2"><input type="radio" checked={form.role === 'admin'} onChange={() => setForm({ ...form, role: 'admin' })} /> Admin</label>
                <label className="flex items-center gap-2"><input type="radio" checked={form.role === 'user'} onChange={() => setForm({ ...form, role: 'user' })} /> User</label>
            </div>

            <input className="w-full p-2 border rounded" placeholder="Name" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required />

            <div className="grid grid-cols-2 gap-4">
                <select className="w-full p-2 border rounded text-gray-700 bg-white" value={form.identity} onChange={e => setForm({ ...form, identity: e.target.value })}>
                    <option value="" disabled>Gender/Sexuality</option>
                    <option value="Lesbian">Lesbian</option>
                    <option value="Gay">Gay</option>
                    <option value="Bisexual">Bisexual</option>
                    <option value="Transgender">Transgender</option>
                    <option value="Queer">Queer</option>
                    <option value="Intersex">Intersex</option>
                    <option value="Asexual">Asexual</option>
                    <option value="Pansexual">Pansexual</option>
                    <option value="Non-binary">Non-binary</option>
                    <option value="Genderfluid">Genderfluid</option>
                    <option value="Agender">Agender</option>
                    <option value="Heterosexual/Straight">Heterosexual/Straight</option>
                    <option value="Prefer not to say">Prefer not to say</option>
                    <option value="Other">Other</option>
                </select>
                <select className="w-full p-2 border rounded text-gray-700 bg-white" value={form.pronouns} onChange={e => setForm({ ...form, pronouns: e.target.value })}>
                    <option value="" disabled>Pronouns</option>
                    <option value="He/Him">He/Him</option>
                    <option value="She/Her">She/Her</option>
                    <option value="They/Them">They/Them</option>
                    <option value="He/They">He/They</option>
                    <option value="She/They">She/They</option>
                    <option value="Ze/Zir">Ze/Zir</option>
                    <option value="Prefer not to say">Prefer not to say</option>
                    <option value="Other">Other</option>
                </select>
            </div>

            <input className="w-full p-2 border rounded" placeholder="Email" type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} required /><input className="w-full p-2 border rounded" placeholder="Password" type="password" value={form.password} onChange={e => setForm({ ...form, password: e.target.value })} required /><Button type="submit" className="w-full">Create</Button></form></Card>
    );
}

function AdminSystemCheck({ user }) {
    const [stats, setStats] = useState({ users: 0, orgs: 0, freelancers: 0, requests: 0, pendingPayments: 0, openGrievances: 0, chats: 0, news: 0 });
    const [loading, setLoading] = useState(true);
    const [lastChecked, setLastChecked] = useState(null);
    const [firestoreStatus, setFirestoreStatus] = useState('checking');
    const [authStatus, setAuthStatus] = useState('ok');
    const [emailStatus, setEmailStatus] = useState('unknown');
    const [testEmailSending, setTestEmailSending] = useState(false);
    const [testEmailMsg, setTestEmailMsg] = useState('');

    const runCheck = async () => {
        setLoading(true);
        setFirestoreStatus('checking');
        try {
            const [usersSnap, requestsSnap, grievancesSnap, chatsSnap, newsSnap] = await Promise.all([
                getDocs(collection(db, 'users')),
                getDocs(collection(db, 'requests')),
                getDocs(collection(db, 'grievances')),
                getDocs(collection(db, 'chats')),
                getDocs(collection(db, 'news')),
            ]);

            const usersData = usersSnap.docs.map(d => d.data());
            const requestsData = requestsSnap.docs.map(d => d.data());
            const grievancesData = grievancesSnap.docs.map(d => d.data());

            setStats({
                users: usersData.filter(u => u.role === 'user').length,
                orgs: usersData.filter(u => u.role === 'organization').length,
                freelancers: usersData.filter(u => u.role === 'freelancer').length,
                admins: usersData.filter(u => u.role === 'admin').length,
                requests: requestsData.length,
                pendingPayments: requestsData.filter(r => r.status === 'payment_review').length,
                openGrievances: grievancesData.filter(g => g.status === 'pending').length,
                chats: chatsSnap.size,
                news: newsSnap.size,
                activeOrgs: usersData.filter(u => u.role === 'organization' && u.isActive).length,
                inactiveUsers: usersData.filter(u => !u.isActive).length,
                completedRequests: requestsData.filter(r => r.status === 'completed').length,
                pendingRequests: requestsData.filter(r => r.status === 'pending').length,
            });

            setFirestoreStatus('ok');
        } catch (e) {
            console.error("System check error:", e);
            setFirestoreStatus('error');
        } finally {
            setLoading(false);
            setLastChecked(new Date());
        }
    };

    useEffect(() => { runCheck(); }, []);

    const sendTestEmail = async () => {
        setTestEmailSending(true);
        setTestEmailMsg('');
        const success = await sendSystemEmail(user.email, "SOH System Test Email", `<p>This is a test email from the Shades of Hue admin system check.</p><p>If you received this, EmailJS is working correctly.</p><p><strong>Time:</strong> ${new Date().toLocaleString()}</p>`);
        setTestEmailSending(false);
        if (success) {
            setEmailStatus('ok');
            setTestEmailMsg('✅ Test email sent to ' + user.email);
        } else {
            setEmailStatus('error');
            setTestEmailMsg('❌ Email failed. Check EmailJS config.');
        }
    };

    const StatusPill = ({ status }) => {
        const map = { ok: 'bg-green-100 text-green-700', error: 'bg-red-100 text-red-700', checking: 'bg-yellow-100 text-yellow-700', unknown: 'bg-gray-100 text-gray-600' };
        const labels = { ok: '✓ Operational', error: '✗ Error', checking: '⟳ Checking...', unknown: '? Not Tested' };
        return <span className={`px-3 py-1 rounded-full text-xs font-bold ${map[status]}`}>{labels[status]}</span>;
    };

    const StatBox = ({ label, value, color = 'indigo', alert = false }) => {
        const colors = { indigo: 'bg-indigo-50 text-indigo-600 border-indigo-100', green: 'bg-green-50 text-green-600 border-green-100', amber: 'bg-amber-50 text-amber-600 border-amber-100', red: 'bg-red-50 text-red-600 border-red-100', purple: 'bg-purple-50 text-purple-600 border-purple-100', gray: 'bg-gray-50 text-gray-600 border-gray-100' };
        return (
            <div className={`rounded-xl border p-4 flex flex-col items-center justify-center text-center ${colors[color]} ${alert && value > 0 ? 'ring-2 ring-offset-1 ring-amber-400' : ''}`}>
                <p className="text-3xl font-extrabold">{value ?? '—'}</p>
                <p className="text-xs font-semibold mt-1 uppercase tracking-wide opacity-80">{label}</p>
                {alert && value > 0 && <p className="text-[10px] mt-1 font-bold animate-pulse">Needs Attention</p>}
            </div>
        );
    };

    return (
        <div className="space-y-6">
            <Card className="p-6">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
                    <div>
                        <h3 className="text-xl font-bold text-gray-900 flex items-center gap-2"><Server size={20} className="text-indigo-600" /> System Health Check</h3>
                        {lastChecked && <p className="text-xs text-gray-400 mt-1">Last checked: {lastChecked.toLocaleTimeString()}</p>}
                    </div>
                    <Button onClick={runCheck} variant="secondary" disabled={loading} className="!text-sm gap-2">
                        {loading ? <><div className="w-4 h-4 border-2 border-indigo-400 border-t-transparent rounded-full animate-spin" /> Checking...</> : '↻ Refresh'}
                    </Button>
                </div>

                {/* Service Status */}
                <div className="space-y-3">
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100">
                        <div className="flex items-center gap-3"><div className="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center"><Server size={16} className="text-orange-600" /></div><div><p className="text-sm font-semibold text-gray-900">Firebase Firestore</p><p className="text-xs text-gray-500">Database read/write access</p></div></div>
                        <StatusPill status={firestoreStatus} />
                    </div>
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100">
                        <div className="flex items-center gap-3"><div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center"><Shield size={16} className="text-blue-600" /></div><div><p className="text-sm font-semibold text-gray-900">Firebase Auth</p><p className="text-xs text-gray-500">Authentication service</p></div></div>
                        <StatusPill status={authStatus} />
                    </div>
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100">
                        <div className="flex items-center gap-3"><div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center"><Mail size={16} className="text-green-600" /></div>
                            <div>
                                <p className="text-sm font-semibold text-gray-900">EmailJS</p>
                                <p className="text-xs text-gray-500">Email delivery service</p>
                            </div>
                        </div>
                        <div className="flex items-center gap-3">
                            <StatusPill status={emailStatus} />
                            <button onClick={sendTestEmail} disabled={testEmailSending} className="text-xs text-indigo-600 hover:underline disabled:opacity-50">
                                {testEmailSending ? 'Sending...' : 'Send Test'}
                            </button>
                        </div>
                    </div>
                    {testEmailMsg && <p className="text-xs px-3 py-2 bg-gray-50 rounded border border-gray-100 text-gray-700">{testEmailMsg}</p>}
                </div>
            </Card>

            {/* Database Stats */}
            <Card className="p-6">
                <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2"><Activity size={18} className="text-indigo-600" /> Database Statistics</h3>
                {loading ? (
                    <div className="flex items-center justify-center py-12"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600" /></div>
                ) : (
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <StatBox label="Users" value={stats.users} color="indigo" />
                        <StatBox label="Organisations" value={stats.orgs} color="purple" />
                        <StatBox label="Freelancers" value={stats.freelancers} color="green" />
                        <StatBox label="Admins" value={stats.admins} color="gray" />
                        <StatBox label="Total Requests" value={stats.requests} color="indigo" />
                        <StatBox label="Pending Requests" value={stats.pendingRequests} color="amber" alert={true} />
                        <StatBox label="Payment Reviews" value={stats.pendingPayments} color="amber" alert={true} />
                        <StatBox label="Completed" value={stats.completedRequests} color="green" />
                        <StatBox label="Open Grievances" value={stats.openGrievances} color="red" alert={true} />
                        <StatBox label="Active Chats" value={stats.chats} color="indigo" />
                        <StatBox label="News Posts" value={stats.news} color="gray" />
                        <StatBox label="Inactive Users" value={stats.inactiveUsers} color="red" alert={true} />
                    </div>
                )}
            </Card>

            {/* Config Info */}
            <Card className="p-6">
                <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2"><Settings size={18} className="text-indigo-600" /> Configuration</h3>
                <div className="space-y-2 text-sm font-mono">
                    <div className="flex justify-between p-2 bg-gray-50 rounded border border-gray-100"><span className="text-gray-500">Project ID</span><span className="text-gray-900 font-bold">{firebaseConfig.projectId}</span></div>
                    <div className="flex justify-between p-2 bg-gray-50 rounded border border-gray-100"><span className="text-gray-500">Auth Domain</span><span className="text-gray-900">{firebaseConfig.authDomain}</span></div>
                    <div className="flex justify-between p-2 bg-gray-50 rounded border border-gray-100"><span className="text-gray-500">EmailJS Service</span><span className="text-gray-900">{EMAILJS_SERVICE_ID}</span></div>
                    <div className="flex justify-between p-2 bg-gray-50 rounded border border-gray-100"><span className="text-gray-500">UPI ID</span><span className="text-gray-900">{UPI_ID}</span></div>
                    <div className="flex justify-between p-2 bg-gray-50 rounded border border-gray-100"><span className="text-gray-500">Super Admins</span><span className="text-gray-900">{SUPER_ADMINS.join(', ')}</span></div>
                </div>
            </Card>
        </div>
    );
}

function AdminNewsManager() {
    const [news, setNews] = useState({ title: '', content: '' });
    const [newsList, setNewsList] = useState([]);
    const [confirmId, setConfirmId] = useState(null);
    useEffect(() => { const q = query(collection(db, 'news'), orderBy('createdAt', 'desc')); const unsub = onSnapshot(q, (s) => setNewsList(s.docs.map(d => ({ id: d.id, ...d.data() }))), (error) => console.error("News Error:", error)); return () => unsub(); }, []);
    const post = async (e) => { e.preventDefault(); try { await addDoc(collection(db, 'news'), { ...news, createdAt: serverTimestamp() }); setNews({ title: '', content: '' }); } catch (e) { console.error(e); } };
    const deleteNews = async (id) => { if (confirmId === id) { await deleteDoc(doc(db, 'news', id)); setConfirmId(null); } else { setConfirmId(id); setTimeout(() => setConfirmId(null), 3000); } };
    return (
        <div className="space-y-8"><Card className="p-6"><h3 className="font-bold mb-4">Post News</h3><form onSubmit={post} className="space-y-4"><input className="w-full p-2 border rounded" placeholder="Title" value={news.title} onChange={e => setNews({ ...news, title: e.target.value })} required /><textarea className="w-full p-2 border rounded" rows={3} placeholder="Content" value={news.content} onChange={e => setNews({ ...news, content: e.target.value })} required /><Button type="submit">Publish</Button></form></Card><Card className="p-6"><h3 className="font-bold mb-4">Manage Updates</h3><div className="space-y-4">{newsList.map(item => (<div key={item.id} className="p-4 border rounded bg-gray-50 flex justify-between items-start group"><div><h4 className="font-bold text-gray-900">{item.title}</h4><p className="text-sm text-gray-600 mt-1 whitespace-pre-wrap">{item.content}</p><div className="text-xs text-gray-400 mt-2">{item.createdAt?.toDate ? item.createdAt.toDate().toLocaleDateString() : 'Just now'}</div></div><button onClick={() => deleteNews(item.id)} className={`p-2 rounded transition-colors ${confirmId === item.id ? 'bg-red-50 text-red-600' : 'text-gray-400 hover:text-red-600 hover:bg-gray-100'}`} title="Delete">{confirmId === item.id ? <span className="text-xs font-bold">Sure?</span> : <Trash2 size={18} />}</button></div>))}{newsList.length === 0 && <p className="text-gray-500 text-sm">No updates posted.</p>}</div></Card></div>
    );
}

function AdminPaymentApprovals() {
    const [requests, setRequests] = useState([]);
    const [confirmingId, setConfirmingId] = useState(null);
    useEffect(() => { const q = query(collection(db, 'requests'), where('status', '==', 'payment_review')); const unsub = onSnapshot(q, (s) => { const data = s.docs.map(d => ({ id: d.id, ...d.data() })); data.sort((a, b) => b.createdAt?.seconds - a.createdAt?.seconds); setRequests(data); }, (error) => console.error("Payment Error:", error)); return () => unsub(); }, []);
    const handleClick = (id) => { if (confirmingId === id) { approvePayment(id); } else { setConfirmingId(id); setTimeout(() => setConfirmingId(null), 3000); } };
    const approvePayment = async (id) => { try { await updateDoc(doc(db, 'requests', id), { status: 'pending' }); setConfirmingId(null); } catch (e) { console.error(e); } };
    return (
        <Card className="p-6"><h3 className="font-bold text-gray-900 mb-6 flex items-center gap-2"><IndianRupee size={20} className="text-indigo-600" /> Payment Approvals</h3><div className="space-y-3">{requests.map(req => (<div key={req.id} className="p-4 border border-indigo-100 rounded-lg bg-indigo-50/50 flex flex-col md:flex-row justify-between items-center gap-4"><div><div className="font-bold text-gray-900">{req.serviceName} <span className="text-gray-500 font-normal">(₹{req.servicePrice || 'N/A'})</span></div><div className="text-sm text-gray-600">User: {req.userEmail}</div><div className="text-xs text-gray-400 mt-1">To: {req.orgName}</div></div><Button onClick={() => handleClick(req.id)} variant={confirmingId === req.id ? 'danger' : 'success'} className="!py-1.5 !px-4 !text-sm transition-all">{confirmingId === req.id ? 'Confirm Approval?' : <><Check size={16} /> Approve Payment</>}</Button></div>))}{requests.length === 0 && <p className="text-gray-500 text-center py-4">No pending payments.</p>}</div></Card>
    );
}

function AdminGrievances() {
    const [grievances, setGrievances] = useState([]);
    useEffect(() => {
        const q = query(collection(db, 'grievances'));
        const unsub = onSnapshot(q, (s) => {
            const data = s.docs.map(d => ({ id: d.id, ...d.data() }));
            data.sort((a, b) => b.createdAt?.seconds - a.createdAt?.seconds);
            setGrievances(data);
        }, (error) => console.error("Grievance Error:", error));
        return () => unsub();
    }, []);

    const resolveGrievance = async (id) => {
        await updateDoc(doc(db, 'grievances', id), { status: 'resolved' });
    };

    return (
        <Card className="p-6"><h3 className="font-bold text-gray-900 mb-6 flex items-center gap-2"><AlertTriangle size={20} className="text-amber-600" /> Grievance Portal</h3><div className="space-y-4">{grievances.map(g => (
            <div key={g.id} className="p-4 border border-gray-200 rounded-lg">
                <div className="flex justify-between items-start">
                    <div>
                        <div className="font-bold text-lg">{g.subject} <Badge color={g.status === 'resolved' ? 'green' : 'red'}>{g.status}</Badge></div>
                        <div className="text-sm text-gray-500 mt-1">From: {g.userEmail} ({g.userRole})</div>
                        <p className="mt-2 text-gray-700">{g.description}</p>
                    </div>
                    {g.status !== 'resolved' && <Button variant="secondary" onClick={() => resolveGrievance(g.id)} className="!py-1 !text-sm">Mark Resolved</Button>}
                </div>
            </div>
        ))}
            {grievances.length === 0 && <div className="text-center text-gray-500">No grievances found.</div>}</div></Card>
    );
}

function AdminMessageCenter() {
    const [chats, setChats] = useState([]);
    const [selectedChat, setSelectedChat] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        const q = query(collection(db, 'chats'));
        const unsub = onSnapshot(q, (s) => {
            const data = s.docs.map(d => ({ id: d.id, ...d.data() }));
            data.sort((a, b) => (b.lastMessageTime?.seconds || 0) - (a.lastMessageTime?.seconds || 0));
            setChats(data);
            setError(null);
        }, (error) => {
            console.error("Message Center Error:", error);
            setError("Permission Denied: Please update Firestore Rules to allow Admin access to chats.");
        });
        return () => unsub();
    }, []);

    if (error) return (
        <Card className="p-6 bg-red-50 border-red-200">
            <h3 className="text-red-700 font-bold mb-2">Access Error</h3>
            <p className="text-sm text-red-600">{error}</p>
        </Card>
    );

    return (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 h-[600px]"><Card className="col-span-1 flex flex-col h-full"><div className="p-4 border-b"><h3 className="font-bold text-gray-900">Conversations</h3></div><div className="overflow-y-auto flex-1 p-2 space-y-2">{chats.map(chat => (<div key={chat.id} onClick={() => setSelectedChat(chat)} className={`p-3 rounded-lg cursor-pointer border transition-all ${selectedChat?.id === chat.id ? 'bg-indigo-50 border-indigo-200' : 'hover:bg-gray-50 border-transparent'}`}><div className="text-xs font-bold text-gray-700 truncate">{Object.values(chat.participantData || {}).map(p => p.name).join(' & ')}</div><div className="text-xs text-gray-500 truncate mt-1">{chat.lastMessage || 'No messages'}</div><div className="text-[10px] text-gray-400 mt-1 text-right">{chat.lastMessageTime?.toDate ? chat.lastMessageTime.toDate().toLocaleDateString() : ''}</div></div>))}{chats.length === 0 && <div className="p-4 text-center text-gray-500 text-sm">No chats found</div>}</div></Card><Card className="col-span-1 lg:col-span-2 flex flex-col h-full overflow-hidden">{selectedChat ? (<AdminChatDetails chat={selectedChat} />) : (<div className="h-full flex items-center justify-center text-gray-400 bg-gray-50/50">Select a conversation to monitor</div>)}</Card></div>
    );
}

function AdminChatDetails({ chat }) {
    const [messages, setMessages] = useState([]);
    const bottomRef = useRef(null);
    useEffect(() => {
        const q = query(collection(db, 'chats', chat.id, 'messages'), orderBy('timestamp', 'asc'));
        const unsub = onSnapshot(q, (s) => {
            setMessages(s.docs.map(d => ({ id: d.id, ...d.data() })));
            setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
        }, (error) => console.error("Chat Details Error:", error));
        return () => unsub();
    }, [chat.id]);
    return (
        <div className="flex flex-col h-full"><div className="p-4 border-b bg-gray-50"><h4 className="font-bold text-gray-800 text-sm">{Object.values(chat.participantData || {}).map(p => `${p.name}`).join(' ↔ ')}</h4></div><div className="flex-1 overflow-y-auto p-4 space-y-3 bg-white">{messages.map(m => { const sender = chat.participantData?.[m.senderId]; const senderName = sender ? sender.name : m.senderEmail; return (<div key={m.id} className="flex flex-col"><div className="flex justify-between items-end mb-1"><span className="text-xs font-bold text-indigo-600">{senderName}</span><span className="text-[10px] text-gray-400">{m.timestamp?.toDate ? m.timestamp.toDate().toLocaleTimeString() : ''}</span></div><div className="bg-gray-100 p-3 rounded-lg rounded-tl-none text-sm text-gray-800">{m.text}</div></div>); })}<div ref={bottomRef} /></div></div>
    );
}

function AdminFeedbackMonitor() {
    const [feedbackList, setFeedbackList] = useState([]);

    useEffect(() => {
        const q = query(collection(db, 'requests'), where('status', '==', 'completed'));
        const unsub = onSnapshot(q, (s) => {
            const data = s.docs
                .map(d => ({ id: d.id, ...d.data() }))
                .filter(item => item.feedback)
                .sort((a, b) => (b.feedback?.createdAt?.seconds || 0) - (a.feedback?.createdAt?.seconds || 0));
            setFeedbackList(data);
        }, (error) => console.error("Feedback Error:", error));
        return () => unsub();
    }, []);

    return (
        <Card className="p-6">
            <h3 className="font-bold text-gray-900 mb-6 flex items-center gap-2">
                <Star size={20} className="text-yellow-500" /> Service Feedback Monitor
            </h3>
            <div className="space-y-4">
                {feedbackList.map(item => (
                    <div key={item.id} className="p-4 border border-gray-200 rounded-lg bg-gray-50">
                        <div className="flex flex-col md:flex-row justify-between md:items-start gap-4">
                            <div>
                                <div className="font-bold text-gray-900 flex items-center gap-2">
                                    {item.serviceName}
                                    <span className="text-gray-400 font-normal text-sm">by {item.orgName}</span>
                                </div>
                                <div className="text-xs text-gray-500 mt-1">User: {item.userName}</div>
                                <div className="mt-3">
                                    <StarRating rating={item.feedback.rating} />
                                    <p className="mt-2 text-sm text-gray-700 italic">"{item.feedback.comment}"</p>
                                </div>
                            </div>
                            <div className="text-xs text-gray-400 whitespace-nowrap">
                                {item.feedback.createdAt?.toDate ? item.feedback.createdAt.toDate().toLocaleDateString() : 'Recent'}
                            </div>
                        </div>
                    </div>
                ))}
                {feedbackList.length === 0 && <div className="text-center text-gray-500 py-8">No feedback submitted yet.</div>}
            </div>
        </Card>
    );
}

// --- ADMIN SETTINGS ---
function AdminSettings({ user }) {
    const [email, setEmail] = useState(user.email);
    const [msg, setMsg] = useState({ type: '', text: '' });

    const handleUpdateEmail = async (e) => {
        e.preventDefault();
        setMsg({ type: '', text: '' });
        if (email === user.email) return;

        try {
            await verifyBeforeUpdateEmail(user, email);
            setMsg({ type: 'success', text: `Verification email sent to ${email}. Please check your inbox to finalize the change.` });
        } catch (error) {
            if (error.code === 'auth/requires-recent-login') {
                setMsg({ type: 'error', text: 'Security Check: Please log out and log back in to change your email.' });
            } else {
                setMsg({ type: 'error', text: error.message });
            }
        }
    };

    return (
        <Card className="p-6">
            <h3 className="font-bold text-gray-900 mb-6 flex items-center gap-2">
                <Settings size={20} className="text-indigo-600" /> Admin Account Settings
            </h3>

            {msg.text && (
                <div className={`p-4 mb-6 rounded-lg text-sm font-medium ${msg.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
                    {msg.text}
                </div>
            )}

            <div className="space-y-8 max-w-lg">
                <form onSubmit={handleUpdateEmail} className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Change Admin Email Address</label>
                        <p className="text-xs text-gray-500 mb-3">Updating this will change your login credentials.</p>
                        <div className="flex gap-3">
                            <input
                                type="email"
                                className="flex-1 px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                required
                            />
                            <Button type="submit">Update Email</Button>
                        </div>
                    </div>
                </form>
            </div>
        </Card>
    );
}

// --- ADMIN DASHBOARD ---
function AdminDashboard({ user }) {
    const [activeTab, setActiveTab] = useState('users');
    const SidebarBtn = ({ icon: Icon, label, active, onClick }) => <button onClick={onClick} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${active ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}`}><Icon size={18} />{label}</button>;
    return (
        <div className="grid lg:grid-cols-4 gap-8">
            <div className="lg:col-span-1 space-y-4">
                <Card className="p-4"><h3 className="font-bold text-gray-900 mb-4 px-2">Admin Controls</h3><div className="space-y-1">
                    <SidebarBtn icon={User} label="Manage Users" active={activeTab === 'users'} onClick={() => setActiveTab('users')} />
                    <SidebarBtn icon={Plus} label="Create Account" active={activeTab === 'create'} onClick={() => setActiveTab('create')} />
                    <SidebarBtn icon={Megaphone} label="Freelancers" active={activeTab === 'freelancers'} onClick={() => setActiveTab('freelancers')} />
                    <SidebarBtn icon={Server} label="System Check" active={activeTab === 'system'} onClick={() => setActiveTab('system')} />
                    <SidebarBtn icon={Newspaper} label="Manage News" active={activeTab === 'news'} onClick={() => setActiveTab('news')} />
                    <SidebarBtn icon={IndianRupee} label="Payment Approvals" active={activeTab === 'approvals'} onClick={() => setActiveTab('approvals')} />
                    <SidebarBtn icon={Activity} label="Request Monitor" active={activeTab === 'monitor'} onClick={() => setActiveTab('monitor')} />
                    <SidebarBtn icon={AlertTriangle} label="Grievance Portal" active={activeTab === 'grievances'} onClick={() => setActiveTab('grievances')} />
                    <SidebarBtn icon={MessageSquare} label="Conversation Monitor" active={activeTab === 'messages'} onClick={() => setActiveTab('messages')} />
                    <SidebarBtn icon={Star} label="Service Feedback" active={activeTab === 'feedback'} onClick={() => setActiveTab('feedback')} />
                    <div className="my-2 border-t border-gray-100"></div>
                    <SidebarBtn icon={Settings} label="Admin Settings" active={activeTab === 'settings'} onClick={() => setActiveTab('settings')} />
                </div></Card>
            </div>
            <div className="lg:col-span-3">
                {activeTab === 'users' && <AdminUserList />}
                {activeTab === 'create' && <AdminCreateUser />}
                {activeTab === 'freelancers' && <AdminFreelancerList />}
                {activeTab === 'system' && <AdminSystemCheck user={user} />}
                {activeTab === 'news' && <AdminNewsManager />}
                {activeTab === 'approvals' && <AdminPaymentApprovals />}
                {activeTab === 'monitor' && <AdminRequestMonitor />}
                {activeTab === 'grievances' && <AdminGrievances />}
                {activeTab === 'messages' && <AdminMessageCenter />}
                {activeTab === 'feedback' && <AdminFeedbackMonitor />}
                {activeTab === 'settings' && <AdminSettings user={user} />}
            </div>
        </div>
    );
}

// --- SUB-COMPONENTS FOR ORG DASHBOARD ---
function OrgChatList({ user, onSelectChat }) {
    const [chats, setChats] = useState([]);
    useEffect(() => {
        const q = query(collection(db, 'chats'), where('participants', 'array-contains', user.uid));
        const unsub = onSnapshot(q, (s) => {
            const chatData = s.docs.map(d => ({ id: d.id, ...d.data() }));
            chatData.sort((a, b) => {
                const timeA = a.lastMessageTime?.toMillis ? a.lastMessageTime.toMillis() : 0;
                const timeB = b.lastMessageTime?.toMillis ? b.lastMessageTime.toMillis() : 0;
                return timeB - timeA;
            });
            setChats(chatData);
        }, (error) => console.error("Org Chat List Error:", error));
        return () => unsub();
    }, [user.uid]);

    const getPartnerName = (chat) => {
        const partnerId = chat.participants.find(p => p !== user.uid);
        const pData = chat.participantData?.[partnerId];
        return pData?.name || "User";
    };

    return (<Card className="p-6"><h3 className="font-bold mb-4">Conversations</h3><div className="space-y-2">{chats.length > 0 ? chats.map(chat => (<div key={chat.id} onClick={() => onSelectChat(chat.id)} className="p-4 border rounded hover:bg-gray-50 cursor-pointer transition-colors"><div className="flex justify-between items-start"><span className="font-bold text-gray-900">{getPartnerName(chat)}</span><span className="text-xs text-gray-400">{chat.lastMessageTime?.toDate ? chat.lastMessageTime.toDate().toLocaleDateString() : ''}</span></div><p className="text-sm text-gray-600 truncate mt-1">{chat.lastMessage || "No messages yet"}</p></div>)) : <p className="text-gray-500 text-center py-4">No active conversations.</p>}</div></Card>);
}

// --- ORG DASHBOARD ---
function OrgDashboard({ user, userData }) {
    const [tab, setTab] = useState('profile');
    const [isEditing, setIsEditing] = useState(false);
    const [data, setData] = useState({ desc: userData?.description || '', services: userData?.services || [], newServiceName: '', newServicePrice: '', newServiceDesc: '' });
    const [requests, setRequests] = useState([]);
    const [activeChatId, setActiveChatId] = useState(null);

    const [confirmingReqId, setConfirmingReqId] = useState(null);
    const [declineModalReqId, setDeclineModalReqId] = useState(null);

    const [profileName, setProfileName] = useState(userData?.displayName || '');
    const [profileEmail, setProfileEmail] = useState(user.email || '');
    const [profileMsg, setProfileMsg] = useState({ type: '', text: '' });
    const [isAvailable, setIsAvailable] = useState(userData?.isAvailable ?? true);

    const [pass, setPass] = useState('');
    const [confirm, setConfirm] = useState('');
    const [passMsg, setPassMsg] = useState({ type: '', text: '' });

    useEffect(() => {
        if (userData) {
            setData(d => ({ ...d, desc: userData.description || '', services: userData.services || [] }));
            setProfileName(userData.displayName || '');
            setIsAvailable(userData.isAvailable ?? true);
        }
        if (user) setProfileEmail(user.email);
    }, [userData, user]);

    useEffect(() => {
        const unsub = onSnapshot(query(collection(db, 'requests'), where('orgId', '==', user.uid), orderBy('createdAt', 'desc')), (snapshot) => {
            const allRequests = snapshot.docs.map(d => ({ id: d.id, ...d.data() }));
            setRequests(allRequests.filter(r => r.status !== 'payment_review'));
        }, (e) => console.error("Org Requests Error:", e));
        return () => unsub();
    }, [user.uid]);

    const saveProfile = async () => { await updateDoc(doc(db, 'users', user.uid), { description: data.desc, services: data.services }); setIsEditing(false); };

    const toggleAvailability = async () => {
        const newVal = !isAvailable;
        setIsAvailable(newVal);
        try {
            await updateDoc(doc(db, 'users', user.uid), { isAvailable: newVal });
        } catch (error) {
            console.error("Error updating availability:", error);
            setIsAvailable(!newVal);
        }
    };

    const handleAcceptToggle = async (id) => {
        const actionId = `${id}-accepted`;
        if (confirmingReqId === actionId) {
            const req = requests.find(r => r.id === id);
            if (req && req.userEmail) {
                await sendSystemEmail(
                    req.userEmail,
                    "Request Accepted - Shades of Hue",
                    `<p>Good news! Your service request for <strong>${req.serviceName}</strong> has been accepted by <strong>${userData.displayName}</strong>.</p><p>You can now start chatting with them from your dashboard.</p>`
                );
            }
            updateRequestStatus(id, 'accepted');
        } else {
            setConfirmingReqId(actionId);
            setTimeout(() => setConfirmingReqId(null), 3000);
        }
    };

    const updateRequestStatus = async (id, status, extraData = {}) => {
        try {
            await updateDoc(doc(db, 'requests', id), { status, ...extraData });
            setConfirmingReqId(null);
        } catch (e) {
            console.error("Error updating status:", e);
        }
    };

    const onDeclineSubmit = async (reason) => {
        if (declineModalReqId) {
            const req = requests.find(r => r.id === declineModalReqId);
            if (req && req.userEmail) {
                await sendSystemEmail(
                    req.userEmail,
                    "Request Declined - Shades of Hue",
                    `<p>We regret to inform you that your request for <strong>${req.serviceName}</strong> was declined.</p>
                             <p><strong>Reason:</strong> ${reason}</p>
                             <p>You can browse other organizations for support.</p>`
                );
            }
            await updateRequestStatus(declineModalReqId, 'declined', { declineReason: reason });
            setDeclineModalReqId(null);
        }
    };

    const handleStatusChange = async (id, newStatus) => {
        const req = requests.find(r => r.id === id);
        const oldStatus = req ? req.status : null;

        await updateRequestStatus(id, newStatus);

        // NEW: Update ranking score if transitioning to or from 'completed'
        if (oldStatus && oldStatus !== newStatus) {
            let scoreChange = 0;
            if (newStatus === 'completed') scoreChange = 1;
            else if (oldStatus === 'completed') scoreChange = -1;

            if (scoreChange !== 0) {
                try {
                    await updateDoc(doc(db, 'users', user.uid), {
                        completedRequests: increment(scoreChange)
                    });
                } catch (e) { console.error("Error updating ranking score", e); }
            }
        }
    };

    const handleAddService = () => { if (data.newServiceName) { const newServiceObj = { name: data.newServiceName, price: data.newServicePrice, description: data.newServiceDesc }; setData({ ...data, services: [...data.services, newServiceObj], newServiceName: '', newServicePrice: '', newServiceDesc: '' }); } };

    const handleUpdateOrgInfo = async (e) => {
        e.preventDefault();
        setProfileMsg({ type: '', text: '' });
        try {
            let changesMade = false;
            if (profileName !== userData.displayName) {
                await updateProfile(user, { displayName: profileName });
                await updateDoc(doc(db, 'users', user.uid), { displayName: profileName });
                changesMade = true;
            }
            if (profileEmail !== user.email) {
                await verifyBeforeUpdateEmail(user, profileEmail);
                setProfileMsg({ type: 'success', text: `Verification email sent to ${profileEmail}. Please verify to complete the change.` });
            } else if (changesMade) {
                setProfileMsg({ type: 'success', text: 'Profile info updated successfully!' });
            } else {
                setProfileMsg({ type: 'info', text: 'No changes detected.' });
            }
        } catch (error) {
            if (error.code === 'auth/requires-recent-login') {
                setProfileMsg({ type: 'error', text: 'Security: For your protection, please log out and log in again to change your email.' });
            } else {
                setProfileMsg({ type: 'error', text: error.message });
            }
        }
    };

    const handleUpdatePassword = async (e) => {
        e.preventDefault();
        if (pass !== confirm) { setPassMsg({ type: 'error', text: 'Passwords do not match' }); return; }
        try {
            await updatePassword(user, pass);
            setPassMsg({ type: 'success', text: 'Password updated successfully!' });
            setPass(''); setConfirm('');
        } catch (error) {
            setPassMsg({ type: 'error', text: error.code === 'auth/requires-recent-login' ? 'Security: Please log out and login again to update password.' : error.message });
        }
    };

    return (
        <div className="grid lg:grid-cols-4 gap-8">
            <div className="lg:col-span-1 space-y-4"><Card className="p-4"><h3 className="font-bold text-gray-900 mb-4 px-2">Menu</h3><div className="space-y-1"><button onClick={() => setTab('profile')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'profile' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><Building2 size={18} /> Profile</button><button onClick={() => setTab('requests')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'requests' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><CheckCircle size={18} /> Requests</button><button onClick={() => setTab('messages')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'messages' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><MessageCircle size={18} /> Messages</button><button onClick={() => setTab('grievances')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'grievances' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><AlertTriangle size={18} /> Grievances</button></div></Card></div>
            <div className="lg:col-span-3">
                {tab === 'profile' && (
                    <div className="space-y-6">
                        <Card className="p-6">
                            <div className="flex justify-between items-center">
                                <div>
                                    <h2 className="text-xl font-bold text-gray-900">Availability Status</h2>
                                    <p className="text-sm text-gray-500 mt-1">Determine if users can send you new messages or requests.</p>
                                </div>
                                <button
                                    onClick={toggleAvailability}
                                    className={`px-5 py-2 rounded-full font-bold text-sm transition-all border shadow-sm ${isAvailable ? 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100' : 'bg-red-50 text-red-700 border-red-200 hover:bg-red-100'}`}
                                >
                                    {isAvailable ? '🟢 Available' : '🔴 Unavailable'}
                                </button>
                            </div>
                        </Card>

                        <Card className="p-6">
                            <div className="flex justify-between mb-6"><h2 className="text-xl font-bold">Services & Description</h2><Button variant={isEditing ? 'success' : 'secondary'} onClick={isEditing ? saveProfile : () => setIsEditing(true)} className="!py-1 !text-sm">{isEditing ? 'Save' : 'Edit'}</Button></div>
                            <div className="space-y-4"><div><label className="block text-sm font-medium mb-1">About</label>{isEditing ? <textarea className="w-full p-2 border rounded" rows={3} value={data.desc} onChange={e => setData({ ...data, desc: e.target.value })} /> : <p className="bg-gray-50 p-3 rounded text-gray-700">{data.desc || "No description."}</p>}</div><div><label className="block text-sm font-medium mb-1">Services</label><div className="flex flex-wrap gap-2 mb-2">{data.services.map((s, i) => <span key={i} className="px-2 py-1 bg-indigo-100 text-indigo-800 rounded-full text-xs flex items-center gap-1">{typeof s === 'string' ? s : s.name} {s.price && `(₹${s.price})`}{isEditing && <button onClick={() => { const n = [...data.services]; n.splice(i, 1); setData({ ...data, services: n }) }}><X size={12} /></button>}</span>)}</div>{isEditing && <div className="flex flex-col gap-2 mt-2 p-3 bg-gray-50 rounded border"><input className="w-full p-2 border rounded text-sm" placeholder="Service Name" value={data.newServiceName} onChange={e => setData({ ...data, newServiceName: e.target.value })} /><div className="flex gap-2"><input className="w-24 p-2 border rounded text-sm" type="number" placeholder="Price (₹)" value={data.newServicePrice} onChange={e => setData({ ...data, newServicePrice: e.target.value })} /><input className="flex-grow p-2 border rounded text-sm" placeholder="Short Description" value={data.newServiceDesc} onChange={e => setData({ ...data, newServiceDesc: e.target.value })} /></div><Button variant="secondary" onClick={handleAddService} className="w-full text-xs">Add Service</Button></div>}</div></div>
                        </Card>
                        <Card className="p-6">
                            <h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-2"><Settings size={20} /> Account Settings</h3>
                            <form onSubmit={handleUpdateOrgInfo} className="space-y-4 max-w-md">
                                {profileMsg.text && <div className={`p-3 text-sm rounded ${profileMsg.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>{profileMsg.text}</div>}
                                <div><label className="block text-sm font-medium">Organization Name</label><input className="w-full p-2 border rounded" value={profileName} onChange={e => setProfileName(e.target.value)} /></div>
                                <div>
                                    <label className="block text-sm font-medium">Email Address</label>
                                    <div className="flex gap-2">
                                        <input
                                            type="email"
                                            className="w-full p-2 border rounded"
                                            value={profileEmail}
                                            onChange={e => setProfileEmail(e.target.value)}
                                        />
                                    </div>
                                    <p className="text-xs text-gray-500 mt-1">Note: Email update requires verification.</p>
                                </div>
                                <Button type="submit">Update Info</Button>
                            </form>
                        </Card>
                        <Card className="p-6">
                            <h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-2"><Lock size={20} className="text-indigo-600" /> Security</h3>
                            <form onSubmit={handleUpdatePassword} className="space-y-4 max-w-md">
                                {passMsg.text && <div className={`p-3 text-sm rounded-lg ${passMsg.type === 'success' ? 'bg-emerald-50 text-emerald-700' : 'bg-red-50 text-red-700'}`}>{passMsg.text}</div>}
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">New Password</label><input type="password" className="w-full px-4 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-indigo-500" value={pass} onChange={(e) => setPass(e.target.value)} placeholder="Enter new password" /></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">Confirm Password</label><input type="password" className="w-full px-4 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-indigo-500" value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="Confirm new password" /></div>
                                <Button type="submit">Update Password</Button>
                            </form>
                        </Card>
                    </div>
                )}
                {tab === 'requests' && (
                    <Card className="p-6">
                        <h3 className="font-bold mb-4">Requests</h3>
                        <div className="space-y-3">
                            {requests.map(r => (
                                <div key={r.id} className="p-4 border rounded bg-white flex flex-col gap-3">
                                    <div className="flex justify-between items-start">
                                        <div>
                                            <div className="font-bold">{r.serviceName} {r.servicePrice && <span className="text-gray-500 font-normal text-xs">(₹{r.servicePrice})</span>}</div>
                                            <div className="text-sm text-gray-500">{r.userName || "User"}</div>
                                            <Badge color={r.status === 'accepted' ? 'green' : r.status === 'declined' ? 'red' : r.status === 'in_progress' ? 'yellow' : r.status === 'completed' ? 'green' : r.status === 'cancelled' ? 'gray' : 'blue'}>{r.status}</Badge>
                                        </div>
                                        {r.status === 'pending' && (
                                            <div className="flex gap-2">
                                                <Button onClick={() => handleAcceptToggle(r.id)} variant={confirmingReqId === `${r.id}-accepted` ? 'primary' : 'success'} className="!py-1 transition-all">{confirmingReqId === `${r.id}-accepted` ? 'Confirm?' : 'Accept'}</Button>
                                                <Button onClick={() => setDeclineModalReqId(r.id)} variant="secondary" className="!py-1 transition-all">Decline</Button>
                                            </div>
                                        )}
                                        {['accepted', 'in_progress', 'completed'].includes(r.status) && (
                                            <div className="mt-2 md:mt-0">
                                                <select value={r.status} onChange={(e) => handleStatusChange(r.id, e.target.value)} className="text-sm border rounded px-2 py-1 outline-none focus:ring-2 focus:ring-indigo-500 bg-white">
                                                    <option value="accepted">Not Started</option>
                                                    <option value="in_progress">In Progress</option>
                                                    <option value="completed">Completed</option>
                                                </select>
                                            </div>
                                        )}
                                        {r.status === 'cancelled' && <span className="text-sm text-gray-500 italic">Cancelled by User</span>}
                                        {r.status === 'declined' && r.declineReason && (
                                            <div className="text-sm text-red-600 italic bg-red-50 p-2 rounded">
                                                <strong>Decline Reason:</strong> {r.declineReason}
                                            </div>
                                        )}
                                    </div>

                                    {r.feedback && (
                                        <div className="mt-2 p-3 bg-yellow-50 rounded-lg border border-yellow-100">
                                            <div className="flex items-center gap-2 mb-1">
                                                <span className="text-xs font-bold text-yellow-800 uppercase tracking-wide">Client Feedback</span>
                                                <StarRating rating={r.feedback.rating} />
                                            </div>
                                            <p className="text-sm text-gray-700 italic">"{r.feedback.comment}"</p>
                                        </div>
                                    )}
                                </div>
                            ))}
                            {requests.length === 0 && <p className="text-gray-500">No requests.</p>}
                        </div>
                    </Card>
                )}
                {tab === 'messages' && (<OrgChatList user={user} onSelectChat={setActiveChatId} />)}
                {tab === 'grievances' && <CommonGrievanceList user={user} role="organization" />}
            </div>
            {activeChatId && <ChatWindow chatId={activeChatId} onClose={() => setActiveChatId(null)} currentUser={user} />}
            {declineModalReqId && <DeclineModal onClose={() => setDeclineModalReqId(null)} onSubmit={onDeclineSubmit} />}
        </div>
    );
}

// --- SUB-COMPONENTS FOR USER DASHBOARD ---
function UserProfile({ user, userData }) {
    const [pass, setPass] = useState('');
    const [confirm, setConfirm] = useState('');
    const [msg, setMsg] = useState({ type: '', text: '' });
    const [profileName, setProfileName] = useState(userData?.displayName || '');
    const [profileEmail, setProfileEmail] = useState(user.email || '');
    const [profileIdentity, setProfileIdentity] = useState(userData?.identity || '');
    const [profilePronouns, setProfilePronouns] = useState(userData?.pronouns || '');
    const [infoMsg, setInfoMsg] = useState({ type: '', text: '' });

    useEffect(() => {
        if (userData) {
            setProfileName(userData.displayName || '');
            setProfileIdentity(userData.identity || '');
            setProfilePronouns(userData.pronouns || '');
        }
        if (user) setProfileEmail(user.email);
    }, [userData, user]);

    const handleUpdatePassword = async (e) => { e.preventDefault(); if (pass !== confirm) { setMsg({ type: 'error', text: 'Passwords do not match' }); return; } try { await updatePassword(user, pass); setMsg({ type: 'success', text: 'Password updated successfully!' }); setPass(''); setConfirm(''); } catch (error) { setMsg({ type: 'error', text: error.code === 'auth/requires-recent-login' ? 'Please log out and login again to update password.' : error.message }); } };

    const handleUpdateInfo = async (e) => {
        e.preventDefault();
        setInfoMsg({ type: '', text: '' });
        try {
            let changesMade = false;
            if (profileName !== userData.displayName || profileIdentity !== userData.identity || profilePronouns !== userData.pronouns) {
                await updateProfile(user, { displayName: profileName });
                await updateDoc(doc(db, 'users', user.uid), {
                    displayName: profileName,
                    identity: profileIdentity,
                    pronouns: profilePronouns
                });
                changesMade = true;
            }

            if (profileEmail !== user.email) {
                await verifyBeforeUpdateEmail(user, profileEmail);
                setInfoMsg({ type: 'success', text: `Verification email sent to ${profileEmail}. Please verify to complete the update.` });
            } else if (changesMade) {
                setInfoMsg({ type: 'success', text: 'Profile info updated successfully!' });
            } else {
                setInfoMsg({ type: 'info', text: 'No changes to save.' });
            }
        } catch (error) {
            if (error.code === 'auth/requires-recent-login') {
                setInfoMsg({ type: 'error', text: 'Security: Please log out and log in again to change your email.' });
            } else {
                setInfoMsg({ type: 'error', text: error.message });
            }
        }
    };

    return (
        <div className="space-y-6">
            <Card className="p-6">
                <h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-2"><User size={20} className="text-indigo-600" /> Account Details</h3>
                <form onSubmit={handleUpdateInfo} className="space-y-4 max-w-md">
                    {infoMsg.text && <div className={`p-3 text-sm rounded-lg ${infoMsg.type === 'success' ? 'bg-emerald-50 text-emerald-700' : 'bg-red-50 text-red-700'}`}>{infoMsg.text}</div>}
                    <div><label className="block text-sm font-medium text-gray-500">Full Name</label><input className="w-full p-2 border rounded" value={profileName} onChange={e => setProfileName(e.target.value)} /></div>

                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-500">Gender/Sexuality</label>
                            <select className="w-full p-2 border rounded bg-white text-gray-900" value={profileIdentity} onChange={(e) => setProfileIdentity(e.target.value)}>
                                <option value="" disabled>Select</option>
                                <option value="Lesbian">Lesbian</option>
                                <option value="Gay">Gay</option>
                                <option value="Bisexual">Bisexual</option>
                                <option value="Transgender">Transgender</option>
                                <option value="Queer">Queer</option>
                                <option value="Intersex">Intersex</option>
                                <option value="Asexual">Asexual</option>
                                <option value="Pansexual">Pansexual</option>
                                <option value="Non-binary">Non-binary</option>
                                <option value="Genderfluid">Genderfluid</option>
                                <option value="Agender">Agender</option>
                                <option value="Heterosexual/Straight">Heterosexual/Straight</option>
                                <option value="Prefer not to say">Prefer not to say</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-500">Pronouns</label>
                            <select className="w-full p-2 border rounded bg-white text-gray-900" value={profilePronouns} onChange={(e) => setProfilePronouns(e.target.value)}>
                                <option value="" disabled>Select</option>
                                <option value="He/Him">He/Him</option>
                                <option value="She/Her">She/Her</option>
                                <option value="They/Them">They/Them</option>
                                <option value="He/They">He/They</option>
                                <option value="She/They">She/They</option>
                                <option value="Ze/Zir">Ze/Zir</option>
                                <option value="Prefer not to say">Prefer not to say</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-500">Email Address</label>
                        <input type="email" className="w-full p-2 border rounded bg-white text-gray-900" value={profileEmail} onChange={e => setProfileEmail(e.target.value)} />
                        <p className="text-xs text-gray-500 mt-1">Note: Email update requires verification.</p>
                    </div>
                    <div><label className="block text-sm font-medium text-gray-500">Account Type</label><Badge color="blue">{userData?.role || 'User'}</Badge></div>
                    <Button type="submit">Update Info</Button>
                </form>
            </Card>
            <Card className="p-6"><h3 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-2"><Lock size={20} className="text-indigo-600" /> Security</h3><form onSubmit={handleUpdatePassword} className="space-y-4 max-w-md">{msg.text && <div className={`p-3 text-sm rounded-lg ${msg.type === 'success' ? 'bg-emerald-50 text-emerald-700' : 'bg-red-50 text-red-700'}`}>{msg.text}</div>}<div><label className="block text-sm font-medium text-gray-700 mb-1">New Password</label><input type="password" className="w-full px-4 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-indigo-500" value={pass} onChange={(e) => setPass(e.target.value)} placeholder="Enter new password" /></div><div><label className="block text-sm font-medium text-gray-700 mb-1">Confirm Password</label><input type="password" className="w-full px-4 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-indigo-500" value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="Confirm new password" /></div><Button type="submit">Update Password</Button></form></Card>
        </div>
    );
}

// --- USER DASHBOARD ---
function UserDashboard({ user, userData }) {
    const [activeChatId, setActiveChatId] = useState(null);
    const [paymentModalData, setPaymentModalData] = useState(null);
    const [feedbackModalId, setFeedbackModalId] = useState(null);
    const [orgs, setOrgs] = useState([]);
    const [myRequests, setMyRequests] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [tab, setTab] = useState('find_support');
    const [confirmingCancelId, setConfirmingCancelId] = useState(null);
    const [referralCodeInput, setReferralCodeInput] = useState('');

    useEffect(() => {
        const unsubOrgs = onSnapshot(query(collection(db, 'users'), where('role', '==', 'organization'), where('isActive', '==', true)),
            s => setOrgs(s.docs.map(d => ({ id: d.id, ...d.data() }))),
            (e) => console.error("UserDash Orgs Error:", e)
        );
        const unsubReq = onSnapshot(query(collection(db, 'requests'), where('userId', '==', user.uid), orderBy('createdAt', 'desc')),
            s => setMyRequests(s.docs.map(d => ({ id: d.id, ...d.data() }))),
            (e) => console.error("UserDash Requests Error:", e)
        );
        return () => { unsubOrgs(); unsubReq(); };
    }, [user.uid]);

    const initiateRequest = (org, serviceObj) => { setPaymentModalData({ org, serviceName: typeof serviceObj === 'string' ? serviceObj : serviceObj.name, servicePrice: typeof serviceObj === 'object' && serviceObj.price ? serviceObj.price : null }); };

    const confirmPayment = async () => {
        if (!paymentModalData) return;

        let freelancerDocId = null;

        if (referralCodeInput.trim()) {
            try {
                const q = query(collection(db, 'users'), where('role', '==', 'freelancer'), where('referralCode', '==', referralCodeInput.trim().toUpperCase()));
                const snap = await getDocs(q);
                if (snap.empty) {
                    alert("Invalid Referral Code. Please check the code or clear the field to proceed without it.");
                    return;
                }
                freelancerDocId = snap.docs[0].id;
            } catch (err) {
                console.error("Error validating referral code:", err);
                alert("Error validating referral code. Please try again.");
                return;
            }
        }

        try {
            await addDoc(collection(db, 'requests'), {
                userId: user.uid,
                userEmail: user.email,
                userName: (userData && userData.displayName) || 'User',
                orgId: paymentModalData.org.id,
                orgName: paymentModalData.org.displayName,
                serviceName: paymentModalData.serviceName,
                servicePrice: paymentModalData.servicePrice,
                status: 'payment_review',
                usedReferralCode: referralCodeInput.trim().toUpperCase() || null,
                createdAt: serverTimestamp()
            });

            if (freelancerDocId) {
                try {
                    await updateDoc(doc(db, 'users', freelancerDocId), {
                        referralsCount: increment(1),
                        earnings: increment(50)
                    });
                } catch (err) {
                    console.error("Failed to update freelancer stats", err);
                }
            }

            await sendSystemEmail(paymentModalData.org.email, "New Service Request Received", `<p>You have received a new request from <strong>${userData.displayName || 'A User'}</strong> for the service: <strong>${paymentModalData.serviceName}</strong>.</p><p>Please login to your dashboard to review and accept/decline.</p>`);
            await sendSystemEmail(SUPER_ADMINS, "Admin Alert: Payment Review Pending", `<p>A new request requires payment review.</p><p><strong>Service:</strong> ${paymentModalData.serviceName}</p><p><strong>User:</strong> ${user.email}</p><p><strong>Org:</strong> ${paymentModalData.org.displayName}</p>`);

            setPaymentModalData(null);
            setReferralCodeInput('');
        } catch (e) {
            console.error("Payment confirmation failed:", e);
            alert("Payment confirmation failed. Please try again.");
        }
    };

    const cancelRequest = async (id) => {
        if (confirmingCancelId === id) {
            try { await updateDoc(doc(db, 'requests', id), { status: 'cancelled' }); setConfirmingCancelId(null); } catch (e) { console.error("Error cancelling:", e); }
        } else {
            setConfirmingCancelId(id); setTimeout(() => setConfirmingCancelId(null), 3000);
        }
    };

    const submitFeedback = async ({ rating, comment }) => {
        if (!feedbackModalId) return;
        try {
            await updateDoc(doc(db, 'requests', feedbackModalId), { feedback: { rating, comment, createdAt: serverTimestamp() } });
            setFeedbackModalId(null);
        } catch (e) {
            console.error("Error submitting feedback:", e); alert("Failed to submit feedback. Please try again.");
        }
    };

    const startChat = async (org) => {
        const q = query(collection(db, 'chats'), where('participants', 'array-contains', user.uid));
        const snapshot = await getDocs(q);
        const existingChat = snapshot.docs.find(doc => doc.data().participants.includes(org.id));
        if (existingChat) { setActiveChatId(existingChat.id); }
        else {
            const newChatRef = await addDoc(collection(db, 'chats'), {
                participants: [user.uid, org.id],
                participantData: { [user.uid]: { name: user.displayName || 'User', email: user.email }, [org.id]: { name: org.displayName, email: org.email } },
                createdAt: serverTimestamp(), lastMessage: '', lastMessageTime: serverTimestamp()
            });
            setActiveChatId(newChatRef.id);
        }
    };

    const filteredOrgs = orgs.filter(o => o.displayName?.toLowerCase().includes(searchTerm.toLowerCase()) || o.services?.some(s => (typeof s === 'string' ? s : s.name).toLowerCase().includes(searchTerm.toLowerCase())));

    // NEW: Sort by completed requests
    const sortedOrgs = [...filteredOrgs].sort((a, b) => (b.completedRequests || 0) - (a.completedRequests || 0));
    const highestScore = sortedOrgs.length > 0 ? Math.max(...sortedOrgs.map(o => o.completedRequests || 0)) : 0;

    return (
        <div className="grid lg:grid-cols-4 gap-8">
            <div className="lg:col-span-1 space-y-4"><Card className="p-4"><h3 className="font-bold text-gray-900 mb-4 px-2">Menu</h3><div className="space-y-1"><button onClick={() => setTab('find_support')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'find_support' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><Search size={18} /> Find Support</button><button onClick={() => setTab('requests')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'requests' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><CheckCircle size={18} /> My Requests</button><button onClick={() => setTab('profile')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'profile' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><Settings size={18} /> Profile</button><button onClick={() => setTab('grievances')} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${tab === 'grievances' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-gray-50'}`}><AlertTriangle size={18} /> Grievances</button></div></Card></div>
            <div className="lg:col-span-3">
                {tab === 'find_support' && (
                    <div className="space-y-6">
                        <div className="flex flex-col md:flex-row justify-between items-center gap-4">
                            <h2 className="text-2xl font-bold text-gray-900">Find Support</h2>
                            <input className="w-full md:w-64 px-4 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-indigo-500" placeholder="Search..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} />
                        </div>
                        <div className="grid gap-6">
                            {sortedOrgs.map(org => {
                                const isOrgAvailable = org.isAvailable !== false;
                                const isGold = (org.completedRequests || 0) > 0 && (org.completedRequests || 0) === highestScore;

                                return (
                                    <Card key={org.id} className={`p-6 transition-all duration-300 ${!isOrgAvailable ? 'opacity-75 bg-gray-50' : ''}`}>
                                        <div className="flex items-start justify-between">
                                            <div>
                                                <div className="flex items-center gap-3 flex-wrap">
                                                    <h3 className="text-xl font-bold text-gray-900">{org.displayName}</h3>
                                                    {isGold && <span className="bg-yellow-100 text-yellow-800 text-xs font-bold px-2 py-0.5 rounded-full flex items-center gap-1 border border-yellow-200 shadow-sm"><Award size={12} /> Gold</span>}
                                                    <Badge color={isOrgAvailable ? 'green' : 'red'}>{isOrgAvailable ? 'Available' : 'Unavailable'}</Badge>
                                                </div>
                                                <p className="text-gray-500 text-sm mt-2">{org.description || "No description provided."}</p>
                                                <div className="mt-2 flex items-center gap-2 text-xs font-medium text-gray-500">
                                                    <CheckCircle size={14} className={org.completedRequests > 0 ? "text-green-500" : "text-gray-400"} />
                                                    {org.completedRequests || 0} Orders Completed
                                                </div>
                                            </div>
                                            <div className="flex flex-col gap-2">
                                                <div className={`p-2 rounded-lg self-end ${isOrgAvailable ? 'bg-indigo-50 text-indigo-600' : 'bg-gray-200 text-gray-400'}`}><Building2 size={24} /></div>
                                                <Button variant="secondary" onClick={() => startChat(org)} disabled={!isOrgAvailable} className="!py-1 !px-2 !text-xs gap-1"><MessageCircle size={14} /> Message</Button>
                                            </div>
                                        </div>
                                        <div className="mt-6">
                                            <h4 className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-3">Services</h4>
                                            <div className="flex flex-wrap gap-2">
                                                {org.services?.map((s, i) => (
                                                    <button key={i} onClick={() => initiateRequest(org, s)} disabled={!isOrgAvailable} className="px-3 py-2 bg-gray-100 hover:bg-indigo-600 hover:text-white disabled:hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 rounded-lg text-sm font-medium transition-colors text-left flex flex-col items-start gap-1">
                                                        <span className="font-bold">{typeof s === 'string' ? s : s.name} {s.price && `(₹${s.price})`}</span>
                                                        {s.description && <span className="text-xs opacity-75 font-normal">{s.description}</span>}
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                    </Card>
                                );
                            })}
                        </div>
                    </div>
                )}
                {tab === 'requests' && (<Card className="p-6"><h3 className="font-bold text-gray-900 mb-4">My Requests</h3><div className="space-y-3">{myRequests.map(r => (
                    <div key={r.id} className="p-4 bg-gray-50 rounded border text-sm flex flex-col gap-3">
                        <div className="flex justify-between items-center">
                            <div>
                                <div className="flex items-center gap-2 mb-1">
                                    <span className="font-bold text-indigo-900">{r.serviceName} {r.servicePrice && `(₹${r.servicePrice})`}</span>
                                    <Badge color={r.status === 'accepted' ? 'green' : r.status === 'declined' ? 'red' : r.status === 'in_progress' ? 'yellow' : r.status === 'completed' ? 'green' : r.status === 'cancelled' ? 'gray' : 'blue'}>{r.status === 'payment_review' ? 'Payment Review' : r.status}</Badge>
                                </div>
                                <div className="text-gray-600 text-xs">{r.orgName}</div>
                            </div>
                            {['pending', 'payment_review'].includes(r.status) && (
                                <button onClick={() => cancelRequest(r.id)} className={`text-xs underline ${confirmingCancelId === r.id ? 'text-red-700 font-bold' : 'text-red-500 hover:text-red-700'}`}>
                                    {confirmingCancelId === r.id ? "Confirm Cancel?" : "Cancel Request"}
                                </button>
                            )}
                        </div>
                        {r.status === 'completed' && (
                            <div className="border-t border-gray-200 pt-3 mt-1">
                                {r.feedback ? (
                                    <div className="flex justify-between items-center">
                                        <div className="flex items-center gap-2"><span className="text-xs font-bold text-gray-500">Your Feedback:</span><StarRating rating={r.feedback.rating} /></div>
                                        <span className="text-xs text-green-600 flex items-center gap-1"><CheckCircle size={12} /> Submitted</span>
                                    </div>
                                ) : (
                                    <Button variant="secondary" onClick={() => setFeedbackModalId(r.id)} className="w-full !py-1.5 !text-sm border-indigo-200 text-indigo-700 hover:bg-indigo-50"><Star size={14} /> Rate Service</Button>
                                )}
                            </div>
                        )}
                    </div>
                ))}</div></Card>)}
                {tab === 'profile' && <UserProfile user={user} userData={userData} />}
                {tab === 'grievances' && <CommonGrievanceList user={user} role="user" />}
            </div>
            {activeChatId && <ChatWindow chatId={activeChatId} onClose={() => setActiveChatId(null)} currentUser={user} />}
            {paymentModalData && (
                <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-[100] p-4 animate-in fade-in duration-300">
                    <div className="bg-white rounded-3xl shadow-2xl p-6 max-w-sm w-full animate-in slide-in-from-bottom-8 duration-500">
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="text-xl font-extrabold text-gray-900 tracking-tight">Complete Payment</h3>
                            <button onClick={() => { setPaymentModalData(null); setReferralCodeInput(''); }} className="text-gray-400 hover:text-gray-600 p-1 rounded-full hover:bg-gray-100 transition-colors"><X size={20} /></button>
                        </div>
                        
                        <div className="bg-brand-50 rounded-2xl p-4 mb-6 border border-brand-100">
                            <p className="text-[10px] text-brand-600 font-black uppercase tracking-widest mb-1">Service Selected</p>
                            <p className="text-gray-900 font-bold text-lg leading-tight">{paymentModalData.serviceName}</p>
                            {paymentModalData.servicePrice && (
                                <div className="mt-4 pt-4 border-t border-brand-200/50 flex justify-between items-end">
                                    <div className="flex flex-col">
                                        <span className="text-xs font-medium text-gray-500">Total Amount</span>
                                        <div className="flex items-center gap-1 text-brand-700">
                                            <IndianRupee size={16} />
                                            <span className="text-3xl font-black tracking-tighter">{paymentModalData.servicePrice}</span>
                                        </div>
                                    </div>
                                    <Badge color="purple">Secure UPI</Badge>
                                </div>
                            )}
                        </div>

                        {/* Dynamic QR Code */}
                        <div className="flex flex-col items-center mb-6">
                            <div className="bg-white p-4 rounded-2xl shadow-xl shadow-brand-500/10 border border-gray-100 mb-3 group transition-transform hover:scale-105 duration-300">
                                <img 
                                    src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(`upi://pay?pa=${UPI_ID}&pn=ShadesOfHue&am=${paymentModalData.servicePrice || 0}&cu=INR&tn=${encodeURIComponent(paymentModalData.serviceName)}`)}`}
                                    alt="Payment QR Code"
                                    className="w-40 h-40"
                                />
                            </div>
                            <div className="flex items-center gap-2 text-gray-400">
                                <Search size={12} />
                                <p className="text-[10px] uppercase font-black tracking-widest">Scan with any UPI App</p>
                            </div>
                        </div>

                        {/* Pay via App Option */}
                        <div className="space-y-4">
                            <a 
                                href={`upi://pay?pa=${UPI_ID}&pn=ShadesOfHue&am=${paymentModalData.servicePrice || 0}&cu=INR&tn=${encodeURIComponent(paymentModalData.serviceName)}`}
                                className="w-full flex items-center justify-center gap-2 py-3.5 bg-gradient-to-r from-brand-600 to-brand-500 text-white font-bold rounded-2xl hover:shadow-lg hover:shadow-brand-500/30 transition-all active:scale-95"
                            >
                                <Send size={18} /> Pay via UPI App
                            </a>

                            <div className="relative py-2">
                                <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-100"></div></div>
                                <div className="relative flex justify-center text-[10px] uppercase font-bold tracking-widest"><span className="px-2 bg-white text-gray-400">Or referral</span></div>
                            </div>

                            <input
                                type="text"
                                placeholder="Referral Code (Optional)"
                                className="w-full px-4 py-3 rounded-2xl border border-gray-200 outline-none focus:ring-2 focus:ring-brand-500 bg-gray-50 text-center font-mono uppercase tracking-widest text-sm"
                                value={referralCodeInput}
                                onChange={(e) => setReferralCodeInput(e.target.value.toUpperCase())}
                            />
                            
                            <div className="flex gap-3 pt-2">
                                <Button onClick={() => { setPaymentModalData(null); setReferralCodeInput(''); }} variant="secondary" className="flex-1 !rounded-2xl !py-3">Cancel</Button>
                                <Button onClick={confirmPayment} variant="primary" className="flex-1 !rounded-2xl !py-3">Confirm Payment</Button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
            {feedbackModalId && <FeedbackModal onClose={() => setFeedbackModalId(null)} onSubmit={submitFeedback} />}
        </div>
    );
}

// --- NEW: FREELANCER DASHBOARD ---
function FreelancerDashboard({ user, userData }) {
    if (!userData) return <div className="min-h-screen flex items-center justify-center"><div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div></div>;
    return (
        <div className="space-y-6">
            <Card className="p-6">
                <h2 className="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-2">
                    <Megaphone className="text-indigo-600" /> Freelancer Portal
                </h2>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div className="bg-indigo-50 p-6 rounded-xl border border-indigo-100 flex flex-col items-center justify-center text-center">
                        <p className="text-sm text-indigo-600 font-bold mb-2 uppercase tracking-wide">Your Referral Code</p>
                        <p className="text-3xl font-mono font-bold text-indigo-900 bg-white px-4 py-2 rounded-lg border border-indigo-200 shadow-sm w-full">
                            {userData.referralCode}
                        </p>
                        <p className="text-xs text-indigo-500 mt-3 text-center">Share this code with new users.</p>
                    </div>

                    <div className="bg-green-50 p-6 rounded-xl border border-green-100 flex flex-col items-center justify-center">
                        <p className="text-sm text-green-600 font-bold mb-1 uppercase tracking-wide">Total Referrals</p>
                        <p className="text-5xl font-bold text-green-900">{userData.referralsCount || 0}</p>
                        <p className="text-xs text-green-600 mt-2 font-medium">Users Joined</p>
                    </div>

                    <div className="bg-purple-50 p-6 rounded-xl border border-purple-100 flex flex-col items-center justify-center">
                        <p className="text-sm text-purple-600 font-bold mb-1 uppercase tracking-wide">Total Earnings</p>
                        <p className="text-5xl font-bold text-purple-900">₹{userData.earnings || 0}</p>
                        <p className="text-xs text-purple-600 mt-2 font-medium">Earned at ₹50/referral</p>
                    </div>
                </div>
            </Card>

            <UserProfile user={user} userData={userData} />
        </div>
    );
}

// --- MAIN APP COMPONENT ---
function App() {
    const [currentUser, setCurrentUser] = useState(null);
    const [userRole, setUserRole] = useState(null);
    const [userData, setUserData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [view, setView] = useState(() => {
        const path = window.location.pathname;
        if (path.includes('admin.html') || path.includes('user.html') || path.includes('org.html') || path.includes('freelancer.html')) {
            return 'dashboard';
        }
        if (path.includes('auth.html')) {
            return 'login';
        }
        return 'home';
    });

    const handleNavigate = (target) => {
        const path = window.location.pathname;
        const isDashboardPage = path.includes('admin.html') || path.includes('user.html') || path.includes('org.html') || path.includes('freelancer.html');

        if (target === 'home') {
            if (isDashboardPage || path.includes('auth.html')) {
                window.location.href = 'index.html';
                return;
            }
        }

        if (target === 'login' || target === 'signup') {
            if (!path.includes('auth.html')) {
                window.location.href = 'auth.html';
                return;
            }
        }

        if (target === 'dashboard' && userRole) {
            if (userRole === 'admin' && !path.includes('admin.html')) { window.location.href = 'admin.html'; return; }
            if (userRole === 'user' && !path.includes('user.html')) { window.location.href = 'user.html'; return; }
            if (userRole === 'organization' && !path.includes('org.html')) { window.location.href = 'org.html'; return; }
            if (userRole === 'freelancer' && !path.includes('freelancer.html')) { window.location.href = 'freelancer.html'; return; }
        }

        setView(target);
    };
    const [isDeactivated, setIsDeactivated] = useState(false);
    const [isUnverified, setIsUnverified] = useState(false);
    const [showGlobalTerms, setShowGlobalTerms] = useState(false);

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, async (user) => {
            setIsDeactivated(false);
            setIsUnverified(false);

            if (user) {
                setCurrentUser(user);
                try {
                    if (SUPER_ADMINS.includes(user.email)) {
                        await setDoc(doc(db, 'users', user.uid), {
                            email: user.email, role: 'admin', isActive: true, displayName: 'Super Admin', uid: user.uid
                        }, { merge: true });
                    }
                    const userDocSnap = await getDoc(doc(db, 'users', user.uid));
                    if (userDocSnap.exists()) {
                        const data = userDocSnap.data();

                        if (!data.isActive) {
                            setIsDeactivated(true);
                            await signOut(auth);
                            setCurrentUser(null);
                            setUserRole(null);
                            handleNavigate('home');
                            setLoading(false);
                            return;
                        }

                        if (data.role === 'user' && !user.emailVerified) {
                            setIsUnverified(true);
                            setUserData(data);
                            setUserRole(data.role);
                        } else {
                            setUserData(data);
                            setUserRole(data.role);
                        }
                    } else {
                        setUserData({});
                        setUserRole('user');
                        if (!user.emailVerified) setIsUnverified(true);
                    }
                } catch (error) {
                    console.error("Error fetching user data:", error);
                    setUserRole('user');
                }
            } else {
                setCurrentUser(null);
                setUserData(null);
                setUserRole(null);
                const path = window.location.pathname;
                const isDashboardPage = path.includes('admin.html') || path.includes('user.html') || path.includes('org.html') || path.includes('freelancer.html');
                if (isDashboardPage) {
                    handleNavigate('home');
                }
            }
            setLoading(false);
        });
        return () => unsubscribe();
    }, []);

    useEffect(() => {
        if (!currentUser) return;

        const updatePresence = async () => {
            try {
                await updateDoc(doc(db, 'users', currentUser.uid), {
                    lastSeen: serverTimestamp()
                });
            } catch (err) {
                console.error("Error updating presence:", err);
            }
        };
        updatePresence();
        const intervalId = setInterval(updatePresence, 60 * 1000);
        return () => clearInterval(intervalId);
    }, [currentUser]);

    useEffect(() => {
        if (loading) return;
        const path = window.location.pathname;
        const isDashboardPage = path.includes('admin.html') || path.includes('user.html') || path.includes('org.html') || path.includes('freelancer.html');

        // Redirect logged-in users away from auth.html
        if (currentUser && path.includes('auth.html')) {
            window.location.href = 'index.html';
            return;
        }

        // Redirect logged-out users away from dashboard pages
        if (!currentUser && isDashboardPage) {
            window.location.href = 'index.html';
            return;
        }

        if (!userRole) return;
        if (path.includes('admin.html') && userRole !== 'admin') window.location.href = 'index.html';
        else if (path.includes('user.html') && userRole !== 'user') window.location.href = 'index.html';
        else if (path.includes('org.html') && userRole !== 'organization') window.location.href = 'index.html';
        else if (path.includes('freelancer.html') && userRole !== 'freelancer') window.location.href = 'index.html';
    }, [userRole, loading, currentUser]);

    const handleSignOut = async () => { await signOut(auth); window.location.href = 'index.html'; };

    if (loading) return <div className="min-h-screen flex items-center justify-center bg-gray-50"><div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div></div>;

    if (isDeactivated) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gray-50 p-4">
                <div className="bg-white p-8 rounded-xl shadow-lg max-w-md text-center">
                    <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
                    <h2 className="text-2xl font-bold text-gray-900 mb-2">Account Deactivated</h2>
                    <p className="text-gray-600 mb-6">Your account has been deactivated by an administrator. Please contact support for assistance.</p>
                    <Button onClick={() => setIsDeactivated(false)}>Back to Home</Button>
                </div>
            </div>
        );
    }

    if (isUnverified) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gray-50 p-4">
                <div className="bg-white p-8 rounded-xl shadow-lg max-w-md text-center">
                    <Mail className="w-16 h-16 text-indigo-500 mx-auto mb-4" />
                    <h2 className="text-2xl font-bold text-gray-900 mb-2">Verify Your Email</h2>
                    <p className="text-gray-600 mb-6">
                        Thanks for joining Shades of Hue! We've sent a verification link to <strong>{currentUser?.email}</strong>.
                        Please verify your email to access your dashboard.
                    </p>
                    <div className="space-y-3">
                        <Button className="w-full" onClick={() => window.location.reload()}>I've Verified My Email</Button>
                        <Button variant="secondary" className="w-full" onClick={async () => {
                            try {
                                await sendEmailVerification(currentUser);
                                alert("Verification email resent!");
                            } catch (e) { alert("Error: " + e.message); }
                        }}>Resend Verification Email</Button>
                        <button onClick={handleSignOut} className="text-gray-400 hover:text-gray-600 text-sm underline">Sign Out</button>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50 text-gray-800 font-sans flex flex-col">
            <Navbar user={currentUser} role={userRole} onNavigate={handleNavigate} onSignOut={handleSignOut} currentView={view} />
            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 flex-grow w-full">
                {view === 'home' && <Home user={currentUser} onNavigate={handleNavigate} />}
                {view === 'login' && <Login onNavigate={handleNavigate} />}
                {view === 'signup' && <Signup onNavigate={handleNavigate} />}
                {view === 'dashboard' && userRole === 'admin' && <AdminDashboard user={currentUser} />}
                {view === 'dashboard' && userRole === 'organization' && <OrgDashboard user={currentUser} userData={userData} />}
                {view === 'dashboard' && userRole === 'user' && <UserDashboard user={currentUser} userData={userData} />}
                {view === 'dashboard' && userRole === 'freelancer' && <FreelancerDashboard user={currentUser} userData={userData} />}
            </main>

            <Footer onShowTerms={() => setShowGlobalTerms(true)} />

            {showGlobalTerms && <TermsModal onClose={() => setShowGlobalTerms(false)} />}
        </div>
    );
}

// --- RENDER APP ---
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);