const { useState, useEffect, createContext, useContext, useRef } = React;

const Icon = ({ name, className, style }) => <i className={`fa-solid fa-${name} ${className || ''}`} style={style}></i>;
const Package = (p) => <Icon name="box" {...p} />;
const Search = (p) => <Icon name="magnifying-glass" {...p} />;
const MapPin = (p) => <Icon name="location-dot" {...p} />;
const Truck = (p) => <Icon name="truck" {...p} />;
const CheckCircle2 = (p) => <Icon name="circle-check" {...p} />;
const Clock = (p) => <Icon name="clock" {...p} />;
const Globe = (p) => <Icon name="globe" {...p} />;
const User = (p) => <Icon name="user" {...p} />;
const LogOut = (p) => <Icon name="right-from-bracket" {...p} />;
const Plus = (p) => <Icon name="plus" {...p} />;
const Edit2 = (p) => <Icon name="pen" {...p} />;
const Trash2 = (p) => <Icon name="trash" {...p} />;
const Send = (p) => <Icon name="paper-plane" {...p} />;
const MessageSquare = (p) => <Icon name="comment-dots" {...p} />;
const Menu = (p) => <Icon name="bars" {...p} />;
const X = (p) => <Icon name="xmark" {...p} />;
const Info = (p) => <Icon name="circle-info" {...p} />;
const TrendingUp = (p) => <Icon name="arrow-trend-up" {...p} />;

// --- MULTI-LANGUAGE DICTIONARY ---
const translations = {
    en: {
        hero_title: "Global Logistics & Tracking",
        hero_subtitle: "Track your shipment instantly with real-time updates and seamless communication.",
        track_placeholder: "Enter Tracking Number...",
        track_btn: "Track Package",
        admin_login: "Admin Login",
        language: "Language",
        status: "Status",
        from: "From",
        to: "To",
        est_delivery: "Est. Delivery",
        chat_with_us: "Chat with us",
        send: "Send",
        type_msg: "Type a message...",
        not_found: "Tracking number not found.",
        pending: "Pending",
        in_transit: "In Transit",
        delivered: "Delivered",
        dashboard: "Dashboard",
        manage_trackings: "Manage Trackings",
        create_new: "Create New",
        logout: "Logout",
        save: "Save"
    },
    es: {
        hero_title: "Logística y Seguimiento Global",
        hero_subtitle: "Rastree su envío al instante con actualizaciones en tiempo real.",
        track_placeholder: "Ingrese el número de seguimiento...",
        track_btn: "Rastrear",
        admin_login: "Acceso Admin",
        language: "Idioma",
        status: "Estado",
        from: "De",
        to: "A",
        est_delivery: "Entrega Est.",
        chat_with_us: "Chatea con nosotros",
        send: "Enviar",
        type_msg: "Escribe un mensaje...",
        not_found: "Número no encontrado.",
        pending: "Pendiente",
        in_transit: "En Tránsito",
        delivered: "Entregado",
        dashboard: "Panel",
        manage_trackings: "Gestionar Envíos",
        create_new: "Crear Nuevo",
        logout: "Cerrar sesión",
        save: "Guardar"
    },
    fr: {
        hero_title: "Logistique et Suivi Mondial",
        hero_subtitle: "Suivez votre envoi instantanément avec des mises à jour en temps réel.",
        track_placeholder: "Entrez le numéro de suivi...",
        track_btn: "Suivre",
        admin_login: "Connexion Admin",
        language: "Langue",
        status: "Statut",
        from: "De",
        to: "À",
        est_delivery: "Livraison Est.",
        chat_with_us: "Discutez avec nous",
        send: "Envoyer",
        type_msg: "Tapez un message...",
        not_found: "Numéro de suivi introuvable.",
        pending: "En attente",
        in_transit: "En transit",
        delivered: "Livré",
        dashboard: "Tableau de bord",
        manage_trackings: "Gérer les suivis",
        create_new: "Créer un nouveau",
        logout: "Déconnexion",
        save: "Enregistrer"
    }
};

const I18nContext = createContext();
const useI18n = () => useContext(I18nContext);

// --- MAIN APP COMPONENT ---
function App() {
    const [lang, setLang] = useState('en');
    const [view, setView] = useState(() => {
        return window.location.hash.includes('#admin') ? 'admin' : 'home';
    }); // home, admin
    const t = translations[lang];
    
    useEffect(() => {
        const handleHashChange = () => {
            if (window.location.hash.includes('#admin')) {
                setView('admin');
            } else {
                setView('home');
            }
        };
        window.addEventListener('hashchange', handleHashChange);
        return () => window.removeEventListener('hashchange', handleHashChange);
    }, []);

    const changeLang = (l) => setLang(l);

    const handleViewChange = (v) => {
        if (v === 'admin') window.location.hash = '#admin';
        else window.location.hash = '';
        setView(v);
    };

    return (
        <I18nContext.Provider value={{ t, lang, changeLang }}>
            <div className="min-h-screen flex flex-col font-sans">
                <Navbar view={view} setView={handleViewChange} />
                <main className="flex-grow">
                    {view === 'home' && <UserHome />}
                    {view === 'admin' && <AdminApp />}
                </main>
            </div>
        </I18nContext.Provider>
    );
}

// --- NAVBAR ---
function Navbar({ view, setView }) {
    const { t, lang, changeLang } = useI18n();
    const [showLang, setShowLang] = useState(false);

    return (
        <nav className="sticky top-0 z-50 glass border-b border-slate-200">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="flex justify-between items-center h-16">
                    <div className="flex items-center cursor-pointer group" onClick={() => setView('home')}>
                        <div className="w-10 h-10 bg-gradient-to-br from-brand-600 to-indigo-600 rounded-xl flex items-center justify-center text-white mr-3 shadow-lg shadow-brand-500/30 group-hover:scale-105 transition-transform duration-300">
                            <Truck className="h-6 w-6" />
                        </div>
                        <span className="font-display font-black text-2xl tracking-tighter text-transparent bg-clip-text bg-gradient-to-r from-slate-900 to-slate-700">LogisX</span>
                    </div>
                    <div className="flex items-center gap-4">
                        <div className="relative">
                            <button onClick={() => setShowLang(!showLang)} className="flex items-center text-slate-600 hover:text-slate-900 transition">
                                <Globe className="h-5 w-5 mr-1" />
                                <span className="uppercase text-sm font-medium">{lang}</span>
                            </button>
                            {showLang && (
                                <div className="absolute right-0 mt-2 w-32 bg-white border border-slate-200 rounded-lg overflow-hidden shadow-xl z-50">
                                    {['en', 'es', 'fr'].map(l => (
                                        <button key={l} onClick={() => { changeLang(l); setShowLang(false); }} className="block w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 transition">
                                            {l.toUpperCase()}
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </nav>
    );
}

// --- USER HOME ---
function UserHome() {
    const { t } = useI18n();
    const [trackingNumber, setTrackingNumber] = useState('');
    const [trackingData, setTrackingData] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    const handleSearch = async (e) => {
        e.preventDefault();
        if(!trackingNumber.trim()) return;
        setLoading(true); setError(''); setTrackingData(null);
        
        try {
            const res = await fetch(`api.php?action=get_tracking_details&tn=${trackingNumber}`);
            const data = await res.json();
            if(data.status === 'success') {
                setTrackingData(data.data);
            } else {
                setError(t.not_found);
            }
        } catch (err) {
            setError("Network error.");
        }
        setLoading(false);
    };

    // Auto-refresh tracking data
    useEffect(() => {
        let interval;
        if(trackingData) {
            interval = setInterval(async () => {
                const res = await fetch(`api.php?action=get_tracking_details&tn=${trackingData.tracking_number}`);
                const data = await res.json();
                if(data.status === 'success') {
                    setTrackingData(data.data);
                }
            }, 5000); // refresh every 5 sec
        }
        return () => clearInterval(interval);
    }, [trackingData?.tracking_number]);

    return (
        <div className="relative overflow-hidden min-h-[calc(100vh-4rem)] flex flex-col justify-center">
            {/* Background Grid & Blobs */}
            <div className="absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCI+CjxwYXRoIGQ9Ik0wIDBoNDB2NDBIMHoiIGZpbGw9Im5vbmUiLz4KPHBhdGggZD0iTTAgMGg0MHYxSDB6bTAgMzl2MWg0MHYtMXoiIGZpbGw9InJnYmEoMCwwLDAsMC4wMikiLz4KPHBhdGggZD0iTTAgMHY0MGgxVjB6bTM5IDB2NDBoMXYtNDB6IiBmaWxsPSJyZ2JhKDAsMCwwLDAuMDIpIi8+Cjwvc3ZnPg==')] opacity-50 z-0"></div>
            <div className="absolute top-0 left-1/4 w-[30rem] h-[30rem] bg-brand-300/30 rounded-full mix-blend-multiply filter blur-3xl opacity-50 animate-blob z-0"></div>
            <div className="absolute top-0 right-1/4 w-[30rem] h-[30rem] bg-indigo-300/30 rounded-full mix-blend-multiply filter blur-3xl opacity-50 animate-blob animation-delay-2000 z-0"></div>
            <div className="absolute -bottom-32 left-1/2 -translate-x-1/2 w-[40rem] h-[20rem] bg-blue-300/20 rounded-full mix-blend-multiply filter blur-3xl opacity-50 z-0"></div>

            {!trackingData ? (
                <div className="flex-1 flex flex-col items-center justify-center px-4 sm:px-6 lg:px-8 z-10 animate-fade-in-up py-20 md:py-32 w-full max-w-7xl mx-auto relative">
                    
                    {/* Floating decorative elements */}
                    <div className="absolute top-20 left-10 md:left-20 animate-[bounce_8s_infinite] opacity-60 hidden md:block">
                        <div className="w-16 h-16 bg-white/40 backdrop-blur-md rounded-2xl border border-white/50 shadow-xl flex items-center justify-center transform -rotate-12">
                            <Package className="w-8 h-8 text-brand-500" />
                        </div>
                    </div>
                    <div className="absolute bottom-40 right-10 md:right-20 animate-[bounce_10s_infinite] opacity-60 hidden md:block" style={{animationDelay: '1s'}}>
                        <div className="w-20 h-20 bg-white/40 backdrop-blur-md rounded-full border border-white/50 shadow-xl flex items-center justify-center transform rotate-12">
                            <MapPin className="w-10 h-10 text-indigo-500" />
                        </div>
                    </div>

                    {/* New Premium Floating Widgets */}
                    <div className="absolute top-32 right-[5%] md:right-[15%] animate-[bounce_9s_infinite] opacity-95 hidden lg:flex items-center bg-white/70 backdrop-blur-xl p-3 rounded-2xl border border-white/80 shadow-2xl shadow-indigo-500/10 transform rotate-3 hover:scale-105 transition-transform duration-300">
                        <div className="flex -space-x-3 mr-4">
                            <img className="w-10 h-10 rounded-full border-2 border-white object-cover shadow-sm" src="https://i.pravatar.cc/100?img=1" alt="Support Agent 1"/>
                            <img className="w-10 h-10 rounded-full border-2 border-white object-cover shadow-sm" src="https://i.pravatar.cc/100?img=2" alt="Support Agent 2"/>
                            <img className="w-10 h-10 rounded-full border-2 border-white object-cover shadow-sm" src="https://i.pravatar.cc/100?img=3" alt="Support Agent 3"/>
                        </div>
                        <div>
                            <p className="text-xs font-bold text-slate-800">24/7 Support</p>
                            <p className="text-[10px] font-semibold text-emerald-500 flex items-center"><span className="w-1.5 h-1.5 rounded-full bg-emerald-500 mr-1.5 animate-pulse"></span> Online Now</p>
                        </div>
                    </div>

                    <div className="absolute bottom-32 left-[5%] md:left-[10%] animate-[bounce_11s_infinite] opacity-95 hidden lg:flex flex-col bg-white/70 backdrop-blur-xl p-4 rounded-2xl border border-white/80 shadow-2xl shadow-brand-500/10 transform -rotate-3 hover:scale-105 transition-transform duration-300">
                        <div className="flex items-center justify-between mb-2 gap-4">
                            <p className="text-xs font-bold text-slate-800">Delivery Success</p>
                            <div className="bg-emerald-100 p-1 rounded-full"><TrendingUp className="w-3.5 h-3.5 text-emerald-600" /></div>
                        </div>
                        <h4 className="text-2xl font-black text-brand-600">99.9%</h4>
                        <p className="text-[10px] font-medium text-slate-500 uppercase tracking-wider mt-0.5">On-Time Global</p>
                    </div>

                    <div className="text-center max-w-4xl mx-auto mb-12 relative z-10">
                        <div className="inline-flex items-center gap-2 px-5 py-2 rounded-full bg-white/70 backdrop-blur-xl border border-white/80 text-slate-700 text-sm font-semibold mb-8 shadow-[0_8px_30px_rgb(0,0,0,0.04)] hover:shadow-md transition-all duration-300 transform hover:-translate-y-1">
                            <span className="relative flex h-2.5 w-2.5">
                              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                              <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
                            </span>
                            Next-Generation Global Logistics
                        </div>
                        <h1 className="text-5xl sm:text-6xl md:text-7xl lg:text-[5.5rem] font-display font-extrabold tracking-tight mb-8 leading-[1.1]">
                            <span className="text-transparent bg-clip-text bg-gradient-to-br from-slate-900 via-slate-800 to-slate-500">
                                {t.hero_title.split(' ').slice(0, -2).join(' ')}
                            </span>
                            <br/>
                            <span className="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-indigo-500 relative">
                                {t.hero_title.split(' ').slice(-2).join(' ')}
                                <svg className="absolute w-full h-3 -bottom-1 left-0 text-brand-200/50" viewBox="0 0 100 10" preserveAspectRatio="none"><path d="M0 5 Q 50 10 100 5" stroke="currentColor" strokeWidth="4" fill="transparent"/></svg>
                            </span>
                        </h1>
                        <p className="text-xl md:text-2xl text-slate-500 max-w-3xl mx-auto leading-relaxed font-medium">
                            {t.hero_subtitle}
                        </p>
                    </div>

                    <form onSubmit={handleSearch} className="w-full max-w-3xl relative z-20 group perspective-1000">
                        <div className="absolute -inset-2 bg-gradient-to-r from-brand-500 via-indigo-500 to-cyan-500 rounded-[2.5rem] blur-xl opacity-20 group-hover:opacity-40 transition duration-700"></div>
                        <div className="relative flex flex-col sm:flex-row items-center bg-white/80 backdrop-blur-2xl rounded-[2rem] p-3 border border-white shadow-[0_8px_30px_rgb(0,0,0,0.08)] transform transition-transform duration-500 group-hover:-translate-y-1">
                            <div className="flex-1 flex items-center w-full px-4">
                                <Search className="h-7 w-7 text-brand-500 hidden sm:block" />
                                <input 
                                    type="text" 
                                    value={trackingNumber}
                                    onChange={(e)=>setTrackingNumber(e.target.value)}
                                    placeholder={t.track_placeholder}
                                    className="w-full bg-transparent border-none px-4 py-4 sm:py-6 text-slate-900 text-2xl focus:outline-none placeholder-slate-300 font-bold tracking-wider uppercase"
                                />
                            </div>
                            <button disabled={loading} type="submit" className="w-full sm:w-auto mt-2 sm:mt-0 bg-gradient-to-r from-brand-600 to-indigo-600 hover:from-brand-500 hover:to-indigo-500 text-white px-12 py-6 rounded-[1.5rem] font-bold text-xl transition-all duration-300 shadow-lg shadow-brand-500/30 flex justify-center items-center whitespace-nowrap disabled:opacity-50">
                                {loading ? <div className="w-7 h-7 border-4 border-white/30 border-t-white rounded-full animate-spin"></div> : t.track_btn}
                            </button>
                        </div>
                        <div className="flex flex-wrap justify-center gap-8 mt-10 text-sm font-bold text-slate-500 uppercase tracking-wider">
                            <span className="flex items-center hover:text-brand-600 transition-colors cursor-default"><CheckCircle2 className="w-5 h-5 mr-2 text-brand-500" /> Real-time GPS</span>
                            <span className="flex items-center hover:text-brand-600 transition-colors cursor-default"><CheckCircle2 className="w-5 h-5 mr-2 text-brand-500" /> Secure Transport</span>
                            <span className="flex items-center hover:text-brand-600 transition-colors cursor-default"><CheckCircle2 className="w-5 h-5 mr-2 text-brand-500" /> 24/7 Support</span>
                        </div>
                    </form>
                    {error && <p className="mt-8 text-red-600 bg-white/90 backdrop-blur-md px-6 py-4 rounded-2xl border border-red-100 flex items-center font-semibold shadow-xl shadow-red-500/10 text-lg"><Info className="w-6 h-6 mr-3 text-red-500"/> {error}</p>}
                </div>
            ) : (
                <TrackingView data={trackingData} onBack={() => setTrackingData(null)} />
            )}

            {!trackingData && (
                <>
                    {/* Companies Marquee */}
                    <div className="w-full bg-white border-y border-slate-200 py-12 z-10 relative overflow-hidden flex flex-col items-center">
                        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-slate-100/50 via-transparent to-transparent"></div>
                        <h3 className="text-center mb-10 text-sm text-slate-400 uppercase tracking-[0.2em] font-bold relative z-10 flex items-center gap-4">
                            <span className="w-12 h-[1px] bg-gradient-to-r from-transparent to-slate-300"></span>
                            Trusted by Global Industry Leaders
                            <span className="w-12 h-[1px] bg-gradient-to-l from-transparent to-slate-300"></span>
                        </h3>
                        
                        <div className="marquee-container relative w-full max-w-7xl mx-auto mask-edges">
                            <div className="marquee-content inline-flex gap-24 items-center opacity-80 w-max px-12">
                                {/* Duplicate for infinite effect */}
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">AMAZON</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">FEDEX</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">DHL</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">UPS</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">MAERSK</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">EBAY</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">WALMART</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">ALIEXPRESS</h4>
                                
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">AMAZON</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">FEDEX</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">DHL</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">UPS</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">MAERSK</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">EBAY</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">WALMART</h4>
                                <h4 className="text-3xl font-display font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-slate-400 to-slate-700 tracking-tighter hover:from-brand-500 hover:to-brand-600 transition-all duration-300">ALIEXPRESS</h4>
                            </div>
                        </div>
                    </div>

                    {/* Stats Section */}
                    <div className="w-full bg-slate-50 border-y border-slate-200 py-12 z-10 relative">
                        <div className="max-w-7xl mx-auto px-4 grid grid-cols-2 md:grid-cols-4 gap-8 text-center">
                            <div><h4 className="text-4xl font-display font-bold text-slate-900 mb-2">10M+</h4><p className="text-slate-500 text-sm uppercase tracking-wider font-semibold">Packages Delivered</p></div>
                            <div><h4 className="text-4xl font-display font-bold text-slate-900 mb-2">150+</h4><p className="text-slate-500 text-sm uppercase tracking-wider font-semibold">Countries Served</p></div>
                            <div><h4 className="text-4xl font-display font-bold text-slate-900 mb-2">99%</h4><p className="text-slate-500 text-sm uppercase tracking-wider font-semibold">On-time Delivery</p></div>
                            <div><h4 className="text-4xl font-display font-bold text-slate-900 mb-2">24/7</h4><p className="text-slate-500 text-sm uppercase tracking-wider font-semibold">Live Support</p></div>
                        </div>
                    </div>

                    {/* Features / How it works */}
                    <div className="w-full max-w-7xl mx-auto px-4 py-24 z-10 relative">
                        <div className="text-center mb-20">
                            <h2 className="text-4xl md:text-6xl font-display font-extrabold text-slate-900 mb-6 tracking-tight">Why Choose LogisX?</h2>
                            <p className="text-slate-500 max-w-2xl mx-auto text-xl">Experience the next generation of global logistics with real-time tracking, unmatched security, and lightning-fast delivery speeds.</p>
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-10">
                            <div className="bg-white p-10 rounded-3xl text-center group hover:-translate-y-3 transition-all duration-500 border border-slate-200 hover:border-brand-300 hover:shadow-2xl hover:shadow-brand-500/10 relative overflow-hidden">
                                <div className="absolute inset-0 bg-gradient-to-b from-brand-50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                                <div className="w-24 h-24 bg-brand-50 text-brand-600 rounded-[2rem] flex items-center justify-center mx-auto mb-8 group-hover:scale-110 group-hover:bg-brand-100 transition-all duration-500 relative z-10">
                                    <Globe className="text-5xl drop-shadow-sm"/>
                                </div>
                                <h3 className="text-2xl font-bold text-slate-900 mb-4 relative z-10">Global Network</h3>
                                <p className="text-slate-600 text-base leading-relaxed relative z-10">Our infrastructure spans across 150+ countries, ensuring your packages reach any corner of the globe securely and on time.</p>
                            </div>
                            <div className="bg-white p-10 rounded-3xl text-center group hover:-translate-y-3 transition-all duration-500 border border-slate-200 hover:border-cyan-300 hover:shadow-2xl hover:shadow-cyan-500/10 relative overflow-hidden">
                                <div className="absolute inset-0 bg-gradient-to-b from-cyan-50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                                <div className="w-24 h-24 bg-cyan-50 text-cyan-600 rounded-[2rem] flex items-center justify-center mx-auto mb-8 group-hover:scale-110 group-hover:bg-cyan-100 transition-all duration-500 relative z-10">
                                    <Clock className="text-5xl drop-shadow-sm"/>
                                </div>
                                <h3 className="text-2xl font-bold text-slate-900 mb-4 relative z-10">Real-Time Updates</h3>
                                <p className="text-slate-600 text-base leading-relaxed relative z-10">Never wonder where your package is. Get instant status updates directly to your screen with precise GPS timestamps.</p>
                            </div>
                            <div className="bg-white p-10 rounded-3xl text-center group hover:-translate-y-3 transition-all duration-500 border border-slate-200 hover:border-purple-300 hover:shadow-2xl hover:shadow-purple-500/10 relative overflow-hidden">
                                <div className="absolute inset-0 bg-gradient-to-b from-purple-50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                                <div className="w-24 h-24 bg-purple-50 text-purple-600 rounded-[2rem] flex items-center justify-center mx-auto mb-8 group-hover:scale-110 group-hover:bg-purple-100 transition-all duration-500 relative z-10">
                                    <MessageSquare className="text-5xl drop-shadow-sm"/>
                                </div>
                                <h3 className="text-2xl font-bold text-slate-900 mb-4 relative z-10">Live Support</h3>
                                <p className="text-slate-600 text-base leading-relaxed relative z-10">Directly chat with our dispatchers and admin team regarding your specific tracking number in real-time, 24/7.</p>
                            </div>
                        </div>
                    </div>

                    {/* Premium Services */}
                    <div className="w-full bg-slate-50 border-y border-slate-200 py-24 z-10 relative">
                        <div className="max-w-7xl mx-auto px-4">
                            <div className="flex flex-col md:flex-row justify-between items-end mb-16">
                                <div className="max-w-2xl">
                                    <h2 className="text-4xl md:text-5xl font-display font-extrabold text-slate-900 mb-6">Our Premium Services</h2>
                                    <p className="text-slate-500 text-lg">We offer end-to-end logistics solutions tailored for businesses of all sizes. From standard parcels to heavy freight.</p>
                                </div>
                                <button className="mt-6 md:mt-0 px-6 py-3 rounded-xl border border-brand-200 text-brand-600 font-semibold bg-white hover:bg-brand-50 hover:border-brand-300 transition-all duration-300 shadow-sm">View All Services</button>
                            </div>
                            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                                {[
                                    { title: 'Air Freight', icon: 'plane', color: 'brand', text: 'brand-600', desc: 'Fastest delivery for your urgent global shipments.' },
                                    { title: 'Ocean Freight', icon: 'ship', color: 'cyan', text: 'cyan-600', desc: 'Cost-effective solutions for massive cargo volumes.' },
                                    { title: 'Road Transport', icon: 'truck', color: 'yellow', text: 'yellow-600', desc: 'Reliable cross-border and domestic trucking.' },
                                    { title: 'Warehousing', icon: 'warehouse', color: 'purple', text: 'purple-600', desc: 'Secure storage and fulfillment centers worldwide.' }
                                ].map((s, i) => (
                                    <div key={i} className="bg-white rounded-2xl p-8 border border-slate-200 hover:border-slate-300 hover:shadow-lg transition-all duration-300 group cursor-pointer">
                                        <div className={`w-14 h-14 rounded-xl flex items-center justify-center text-2xl mb-6 bg-${s.color}-50 text-${s.text} group-hover:scale-110 transition-transform`}><i className={`fa-solid fa-${s.icon}`}></i></div>
                                        <h3 className="text-xl font-bold text-slate-900 mb-3">{s.title}</h3>
                                        <p className="text-slate-500 text-sm">{s.desc}</p>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Testimonials */}
                    <div className="w-full max-w-7xl mx-auto px-4 py-20 z-10 relative">
                        <div className="text-center mb-16">
                            <h2 className="text-3xl md:text-5xl font-display font-bold text-slate-900 mb-4">What Our Clients Say</h2>
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                            <div className="bg-white border border-slate-200 shadow-sm hover:shadow-md transition-shadow p-8 rounded-2xl flex flex-col h-full">
                                <div className="flex text-yellow-400 mb-4"><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i></div>
                                <p className="text-slate-600 italic mb-6 flex-1">"LogisX changed how we track shipments. The real-time updates and live support chat are absolutely incredible!"</p>
                                <div className="flex items-center gap-4 mt-auto">
                                    <div className="w-12 h-12 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 font-bold text-xl">S</div>
                                    <p className="text-slate-900 font-bold">Sarah Jenkins<br/><span className="text-sm text-slate-500 font-normal">CEO, RetailCo</span></p>
                                </div>
                            </div>
                            <div className="bg-white border border-slate-200 shadow-sm hover:shadow-md transition-shadow p-8 rounded-2xl flex flex-col h-full">
                                <div className="flex text-yellow-400 mb-4"><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i></div>
                                <p className="text-slate-600 italic mb-6 flex-1">"Unmatched delivery speeds and an admin panel that is out of this world. Highly recommend to any logistics business."</p>
                                <div className="flex items-center gap-4 mt-auto">
                                    <div className="w-12 h-12 bg-cyan-100 rounded-full flex items-center justify-center text-cyan-600 font-bold text-xl">M</div>
                                    <p className="text-slate-900 font-bold">Mark Thompson<br/><span className="text-sm text-slate-500 font-normal">Operations Manager</span></p>
                                </div>
                            </div>
                            <div className="bg-white border border-slate-200 shadow-sm hover:shadow-md transition-shadow p-8 rounded-2xl flex flex-col h-full">
                                <div className="flex text-yellow-400 mb-4"><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i><i className="fa-solid fa-star"></i></div>
                                <p className="text-slate-600 italic mb-6 flex-1">"The best tracking system we have ever used. The UI is simply beautiful and so easy to navigate."</p>
                                <div className="flex items-center gap-4 mt-auto">
                                    <div className="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center text-purple-600 font-bold text-xl">A</div>
                                    <p className="text-slate-900 font-bold">Amanda R.<br/><span className="text-sm text-slate-500 font-normal">E-commerce Seller</span></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Call to Action */}
                    <div className="w-full max-w-7xl mx-auto px-4 py-10 z-10 relative">
                        <div className="bg-white rounded-[3rem] p-12 md:p-20 text-center relative overflow-hidden border border-slate-200 shadow-xl shadow-slate-200/50">
                            <div className="absolute inset-0 bg-gradient-to-r from-brand-50 via-slate-50 to-indigo-50"></div>
                            <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-brand-500 via-cyan-500 to-indigo-500"></div>
                            <div className="relative z-10">
                                <h2 className="text-4xl md:text-6xl font-display font-extrabold text-slate-900 mb-8 tracking-tight">Ready to revolutionize<br/>your supply chain?</h2>
                                <p className="text-slate-600 text-xl max-w-2xl mx-auto mb-10">Join thousands of businesses that trust LogisX for reliable, fast, and transparent global shipping.</p>
                                <div className="flex flex-col sm:flex-row gap-4 justify-center">
                                    <button className="bg-slate-900 text-white px-8 py-4 rounded-xl font-bold text-lg hover:bg-slate-800 transition-colors shadow-md">Create an Account</button>
                                    <button className="bg-white border border-slate-300 text-slate-700 px-8 py-4 rounded-xl font-bold text-lg hover:bg-slate-50 transition-colors">Contact Sales</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Footer */}
                    <footer className="w-full border-t border-slate-200 bg-white py-8 z-10 relative mt-auto">
                        <div className="max-w-7xl mx-auto px-4 flex flex-col md:flex-row justify-between items-center gap-4">
                            <div className="flex items-center text-slate-500 cursor-pointer group" onClick={() => window.scrollTo({top: 0, behavior: 'smooth'})}>
                                <div className="w-8 h-8 bg-gradient-to-br from-brand-600 to-indigo-600 rounded-lg flex items-center justify-center text-white mr-2 shadow-md shadow-brand-500/30 group-hover:scale-105 transition-transform duration-300">
                                    <Truck className="h-5 w-5" />
                                </div>
                                <span className="font-display font-black text-xl tracking-tighter text-slate-900">LogisX</span>
                                <span className="ml-2 text-sm">&copy; {new Date().getFullYear()} All rights reserved.</span>
                            </div>
                            <div className="flex gap-6 text-sm text-slate-500">
                                <a href="#" className="hover:text-brand-600 transition">Privacy Policy</a>
                                <a href="#" className="hover:text-brand-600 transition">Terms of Service</a>
                                <a href="#" className="hover:text-brand-600 transition">Contact Us</a>
                            </div>
                        </div>
                    </footer>
                </>
            )}
        </div>
    );
}

function TrackingView({ data, onBack }) {
    const { t } = useI18n();
    return (
        <div className="max-w-6xl mx-auto w-full px-4 py-10 z-10 animate-fade-in-up">
            <button onClick={onBack} className="text-brand-400 hover:text-brand-300 mb-6 flex items-center font-medium transition">
                &larr; Back to Search
            </button>
            
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                {/* Left Column: Tracking Timeline */}
                <div className="lg:col-span-2 space-y-6">
                    <div className="bg-white border border-slate-200 shadow-sm rounded-2xl p-6 md:p-8">
                        <div className="flex flex-col md:flex-row md:items-center justify-between border-b border-slate-200 pb-6 mb-6 gap-4">
                            <div>
                                <h2 className="text-3xl font-display font-bold text-slate-900 tracking-wider mb-2">{data.tracking_number}</h2>
                                <div className="flex items-center gap-3">
                                    <span className="px-3 py-1 rounded-full bg-brand-50 text-brand-700 text-sm font-semibold border border-brand-200 flex items-center">
                                        {data.current_status}
                                    </span>
                                    <span className="text-slate-500 flex items-center text-sm"><Clock className="w-4 h-4 mr-1"/> {data.updated_at}</span>
                                </div>
                            </div>
                            <div className="flex items-center bg-slate-50 rounded-xl p-4 border border-slate-200">
                                <Truck className="w-10 h-10 text-brand-600 opacity-80" />
                                <div className="ml-4">
                                    <p className="text-xs text-slate-500 uppercase font-semibold tracking-wider">Carrier</p>
                                    <p className="text-slate-900 font-medium">{data.carrier_name || 'LogisX Express'}</p>
                                </div>
                            </div>
                        </div>

                        {/* Route Summary */}
                        <div className="flex items-center justify-between bg-slate-50 p-6 rounded-xl border border-slate-200 mb-8 relative overflow-hidden">
                            <div className="absolute inset-0 bg-gradient-to-r from-brand-50/50 to-indigo-50/50"></div>
                            <div className="z-10 w-1/3">
                                <p className="text-sm text-slate-500 mb-1">{t.from}</p>
                                <p className="font-semibold text-lg text-slate-900">{data.from_location}</p>
                            </div>
                            <div className="z-10 flex-1 flex flex-col justify-center px-4 pt-4">
                                {(()=>{
                                    const progressValue = (data.progress !== null && data.progress !== undefined && data.progress !== '') ? `${data.progress}%` : (data.current_status === 'Delivered' ? '100%' : '50%');
                                    return (
                                        <div className="w-full relative">
                                            <div className="absolute -top-6 transition-all duration-1000 flex flex-col items-center" style={{left: progressValue, transform: 'translateX(-50%)'}}>
                                                <span className="bg-brand-600 text-white text-[10px] font-bold px-2 py-0.5 rounded shadow-sm">{progressValue}</span>
                                                <div className="w-1.5 h-1.5 bg-brand-600 rotate-45 -mt-1"></div>
                                            </div>
                                            <div className="w-full h-1 bg-slate-200 relative rounded-full mt-2">
                                                <div className="absolute inset-y-0 left-0 bg-brand-500 transition-all duration-1000 rounded-full" style={{width: progressValue}}></div>
                                                <Truck className="w-7 h-7 text-brand-600 absolute top-1/2 -translate-y-1/2 bg-white rounded-full p-1.5 border-2 border-brand-200 shadow-md transition-all duration-1000 z-10" style={{left: progressValue, transform: 'translate(-50%, -50%)'}}/>
                                            </div>
                                        </div>
                                    );
                                })()}
                            </div>
                            <div className="z-10 w-1/3 text-right">
                                <p className="text-sm text-slate-500 mb-1">{t.to}</p>
                                <p className="font-semibold text-lg text-slate-900">{data.to_location}</p>
                            </div>
                        </div>

                        {/* Timeline */}
                        <div className="pl-2">
                            <h3 className="text-xl font-semibold mb-6 text-slate-900">Tracking History</h3>
                            <div className="space-y-0 relative">
                                {data.updates && data.updates.map((up, i) => (
                                    <div key={up.id} className={`tracking-line relative pl-8 pb-8 ${i === 0 ? 'active' : ''}`}>
                                        <div className={`absolute left-0 top-1.5 w-6 h-6 rounded-full border-4 ${i === 0 ? 'bg-brand-500 border-white shadow-sm' : 'bg-slate-200 border-white'} z-10`}></div>
                                        <div>
                                            <p className={`font-semibold text-lg ${i === 0 ? 'text-brand-600' : 'text-slate-700'}`}>{up.status_text}</p>
                                            <p className="text-sm text-slate-500 mb-2">{up.timestamp} • {up.location}</p>
                                            {up.note && <p className="text-sm text-slate-600 bg-slate-50 p-3 rounded-lg border border-slate-200 inline-block">{up.note}</p>}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>

                {/* Right Column: Details & Chat */}
                <div className="space-y-6">
                    <div className="bg-white border border-slate-200 shadow-sm rounded-2xl p-6">
                        <h3 className="text-lg font-semibold mb-4 text-slate-900 border-b border-slate-200 pb-2">Shipment Details</h3>
                        <div className="space-y-4 text-sm">
                            <div>
                                <p className="text-slate-500 uppercase tracking-wider text-xs mb-1">Reference No.</p>
                                <p className="text-slate-900 font-medium">{data.reference_number || 'N/A'}</p>
                            </div>
                            <div>
                                <p className="text-slate-500 uppercase tracking-wider text-xs mb-1">Pieces</p>
                                <p className="text-slate-900 font-medium">{data.pieces || '1'}</p>
                            </div>
                            <div>
                                <p className="text-slate-500 uppercase tracking-wider text-xs mb-1">Package Type</p>
                                <p className="text-slate-900 font-medium">{data.package_type || 'Standard Box'}</p>
                            </div>
                            <div>
                                <p className="text-slate-500 uppercase tracking-wider text-xs mb-1">Weight</p>
                                <p className="text-slate-900 font-medium">{data.weight || 'N/A'}</p>
                            </div>
                            <div>
                                <p className="text-slate-500 uppercase tracking-wider text-xs mb-1">Pickup Time</p>
                                <p className="text-slate-900 font-medium">{data.pickup_time || 'Pending'}</p>
                            </div>
                            <div>
                                <p className="text-slate-500 uppercase tracking-wider text-xs mb-1">Departure Time</p>
                                <p className="text-slate-900 font-medium">{data.departure_time || 'Pending'}</p>
                            </div>
                            <div className="pt-2 border-t border-slate-200">
                                <p className="text-slate-500 uppercase tracking-wider text-xs mb-1">{t.est_delivery}</p>
                                <p className="text-brand-600 font-medium">{data.estimated_delivery || 'Pending'}</p>
                            </div>
                        </div>
                    </div>

                    {/* Chat Widget inside page */}
                    <div className="bg-white border border-slate-200 shadow-sm rounded-2xl flex flex-col h-[400px]">
                        <div className="p-4 border-b border-slate-200 bg-slate-50 rounded-t-2xl flex items-center justify-between">
                            <h3 className="font-semibold text-slate-900 flex items-center"><MessageSquare className="w-5 h-5 mr-2 text-brand-600"/> Live Support</h3>
                            <span className="w-2 h-2 rounded-full bg-brand-500 animate-pulse"></span>
                        </div>
                        <ChatBox trackingNumber={data.tracking_number} role="user" />
                    </div>
                </div>
            </div>
        </div>
    );
}

// --- CHAT BOX COMPONENT ---
function ChatBox({ trackingNumber, role }) {
    const { t } = useI18n();
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState('');
    const [templates, setTemplates] = useState([]);
    const chatContainerRef = useRef(null);
    const sessionStart = useRef(Date.now());

    const loadChat = async () => {
        const sinceParam = role === 'user' ? `&since=${sessionStart.current}` : '';
        const res = await fetch(`api.php?action=get_chat&tn=${trackingNumber}${sinceParam}`);
        const data = await res.json();
        if(data.status === 'success') {
            setMessages(data.data);
        }
    };

    useEffect(() => {
        loadChat();
        if (role === 'admin') {
            fetch('api.php?action=get_chat_templates')
                .then(r => r.json())
                .then(d => { if(d.status === 'success') setTemplates(d.data); });
        }
        const interval = setInterval(loadChat, 3000); // Polling for real-time chat
        return () => clearInterval(interval);
    }, [trackingNumber, role]);

    useEffect(() => {
        if(chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
        }
    }, [messages]);

    const sendMsg = async (e, forceMsg = null) => {
        if(e) e.preventDefault();
        const msgText = forceMsg || input;
        if(!msgText.trim()) return;
        if(!forceMsg) setInput('');
        
        // Optimistic UI update
        setMessages(prev => [...prev, { sender: role, message: msgText, created_at: new Date().toISOString() }]);
        
        await fetch('api.php?action=send_chat', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ tracking_number: trackingNumber, message: msgText })
        });
        loadChat();
    };


    return (
        <div className="flex-1 flex flex-col overflow-hidden">
            <div ref={chatContainerRef} className="flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar">
                {messages.map((m, i) => {
                    const isMe = m.sender === role;
                    return (
                        <div key={i} className={`flex flex-col ${isMe ? 'items-end' : 'items-start'}`}>
                            <div className={`max-w-[80%] rounded-2xl px-4 py-2 ${isMe ? 'bg-brand-600 text-white rounded-tr-sm' : 'bg-slate-100 text-slate-800 rounded-tl-sm'}`}>
                                <p className="text-sm">{m.message}</p>
                            </div>
                            <span className="text-[10px] text-slate-400 mt-1">{new Date(m.created_at).toLocaleTimeString()}</span>
                        </div>
                    )
                })}
            </div>
            
            {role === 'admin' && templates.length > 0 && (
                <div className="px-4 py-2 bg-slate-50 border-t border-slate-200 flex gap-2 overflow-x-auto custom-scrollbar">
                    {templates.map(tpl => (
                        <button key={tpl.id} onClick={() => sendMsg(null, tpl.message)} className="text-xs whitespace-nowrap bg-indigo-50 text-indigo-700 hover:bg-indigo-100 border border-indigo-200 px-3 py-1.5 rounded-full transition font-medium">
                            {tpl.title}
                        </button>
                    ))}
                </div>
            )}

            <form onSubmit={(e) => sendMsg(e)} className="p-4 border-t border-slate-200 bg-slate-50 rounded-b-2xl flex gap-2">
                <input 
                    type="text" 
                    value={input} onChange={(e)=>setInput(e.target.value)}
                    placeholder={t.type_msg}
                    className="flex-1 bg-white border border-slate-300 rounded-lg px-4 py-2 text-sm text-slate-900 focus:outline-none focus:border-brand-500 transition"
                />
                <button type="submit" className="bg-brand-500 hover:bg-brand-400 text-white p-2 rounded-lg transition"><Send className="w-4 h-4"/></button>
            </form>
        </div>
    );
}

// --- ADMIN APP ---
function AdminApp() {
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetch('api.php?action=check_auth')
            .then(res => res.json())
            .then(data => {
                if(data.status === 'success') setIsAuthenticated(true);
                setLoading(false);
            });
    }, []);

    if(loading) return <div className="h-[80vh] flex items-center justify-center"><div className="w-10 h-10 border-4 border-brand-500/30 border-t-brand-500 rounded-full animate-spin"></div></div>;

    if(!isAuthenticated) return <AdminLogin onLogin={() => setIsAuthenticated(true)} />;

    return <AdminDashboard onLogout={() => setIsAuthenticated(false)} />;
}

function AdminLogin({ onLogin }) {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');

    const handleLogin = async (e) => {
        e.preventDefault();
        const res = await fetch('api.php?action=admin_login', {
            method: 'POST',
            body: JSON.stringify({ username, password })
        });
        const data = await res.json();
        if(data.status === 'success') onLogin();
        else setError(data.message);
    };

    return (
        <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center p-4">
            <div className="bg-white border border-slate-200 shadow-xl max-w-md w-full p-8 rounded-2xl">
                <div className="text-center mb-8">
                    <User className="w-12 h-12 text-brand-600 mx-auto mb-4 bg-brand-50 p-2 rounded-full" />
                    <h2 className="text-2xl font-bold text-slate-900">Admin Access</h2>
                </div>
                {error && <p className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm border border-red-200">{error}</p>}
                <form onSubmit={handleLogin} className="space-y-4">
                    <div>
                        <label className="block text-sm text-slate-500 mb-1">Username</label>
                        <input type="text" value={username} onChange={e=>setUsername(e.target.value)} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-3 text-slate-900 focus:border-brand-500 focus:outline-none transition" />
                    </div>
                    <div>
                        <label className="block text-sm text-slate-500 mb-1">Password</label>
                        <input type="password" value={password} onChange={e=>setPassword(e.target.value)} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-3 text-slate-900 focus:border-brand-500 focus:outline-none transition" />
                    </div>
                    <button type="submit" className="w-full bg-brand-600 hover:bg-brand-700 text-white font-semibold py-3 rounded-lg transition mt-4 shadow-sm">Login to Dashboard</button>
                </form>
            </div>
        </div>
    );
}

function AdminDashboard({ onLogout }) {
    const [stats, setStats] = useState(null);
    const [trackings, setTrackings] = useState([]);
    const [view, setView] = useState('list'); // list, create, edit
    const [selectedTracking, setSelectedTracking] = useState(null);
    const [activeChatTn, setActiveChatTn] = useState(null);

    const loadData = async () => {
        const resStats = await fetch('api.php?action=get_admin_stats');
        const dStats = await resStats.json();
        if(dStats.status === 'success') setStats(dStats.data);

        const resTrk = await fetch('api.php?action=get_trackings');
        const dTrk = await resTrk.json();
        if(dTrk.status === 'success') setTrackings(dTrk.data);
    };

    useEffect(() => {
        loadData();
        const intv = setInterval(loadData, 10000);
        return () => clearInterval(intv);
    }, []);

    const logout = async () => {
        await fetch('api.php?action=admin_logout');
        onLogout();
    };

    return (
        <div className="flex flex-col md:flex-row h-[calc(100vh-4rem)]">
            {/* Sidebar */}
            <div className="w-full md:w-64 bg-white border-b md:border-b-0 md:border-r border-slate-200 flex flex-row md:flex-col shadow-sm z-10 overflow-x-auto md:overflow-visible shrink-0 custom-scrollbar">
                <div className="p-4 flex flex-row md:flex-col items-center md:items-stretch gap-2 flex-1 min-w-max md:min-w-0">
                    <p className="text-xs uppercase tracking-wider text-slate-500 font-semibold mb-0 md:mb-4 ml-2 hidden md:block">Menu</p>
                    <button onClick={()=>setView('list')} className={`flex items-center px-4 py-2 md:py-3 rounded-lg md:mb-2 transition whitespace-nowrap ${view==='list'?'bg-brand-50 text-brand-700 font-semibold':'text-slate-600 hover:bg-slate-50'}`}>
                        <Package className="w-5 h-5 mr-2 md:mr-3" /> Trackings
                    </button>
                    <button onClick={()=>setView('create')} className={`flex items-center px-4 py-2 md:py-3 rounded-lg md:mb-2 transition whitespace-nowrap ${view==='create'?'bg-brand-50 text-brand-700 font-semibold':'text-slate-600 hover:bg-slate-50'}`}>
                        <Plus className="w-5 h-5 mr-2 md:mr-3" /> Create New
                    </button>
                    <button onClick={()=>setView('templates')} className={`flex items-center px-4 py-2 md:py-3 rounded-lg md:mb-2 transition whitespace-nowrap ${view==='templates'?'bg-brand-50 text-brand-700 font-semibold':'text-slate-600 hover:bg-slate-50'}`}>
                        <MessageSquare className="w-5 h-5 mr-2 md:mr-3" /> Chat Templates
                    </button>
                    
                    <div className="hidden md:block">
                        <p className="text-xs uppercase tracking-wider text-slate-500 font-semibold mt-8 mb-4 ml-2">Active Chats</p>
                        <div className="space-y-1">
                            {stats?.active_chats?.map(c => (
                                <button key={c.tracking_number} onClick={()=>setActiveChatTn(c.tracking_number)} className={`w-full flex items-center px-4 py-2 rounded-lg text-sm transition ${activeChatTn===c.tracking_number ? 'bg-indigo-50 text-indigo-700 font-semibold' : 'text-slate-600 hover:bg-slate-50'}`}>
                                    <MessageSquare className="w-4 h-4 mr-2" /> {c.tracking_number}
                                </button>
                            ))}
                        </div>
                    </div>
                </div>
                <div className="p-2 md:p-4 border-l md:border-l-0 md:border-t border-slate-200 bg-slate-50 flex items-center md:items-stretch">
                    <button onClick={logout} className="flex items-center px-4 py-2 md:py-3 rounded-lg text-red-600 hover:bg-red-50 transition font-medium whitespace-nowrap">
                        <LogOut className="w-5 h-5 mr-2 md:mr-3" /> <span className="hidden sm:inline">Logout</span>
                    </button>
                </div>
            </div>

            {/* Main Content */}
            <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 sm:p-8 relative bg-slate-50">
                {stats && view === 'list' && (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-6 mb-8">
                        <div className="bg-white border border-slate-200 shadow-sm p-6 rounded-xl flex items-center">
                            <div className="bg-brand-50 p-4 rounded-full mr-4"><Package className="text-brand-600 w-8 h-8"/></div>
                            <div><p className="text-slate-500 text-sm">Total Trackings</p><h4 className="text-3xl font-bold text-slate-900">{stats.total}</h4></div>
                        </div>
                        <div className="bg-white border border-slate-200 shadow-sm p-6 rounded-xl flex items-center">
                            <div className="bg-amber-50 p-4 rounded-full mr-4"><Clock className="text-amber-500 w-8 h-8"/></div>
                            <div><p className="text-slate-500 text-sm">Pending</p><h4 className="text-3xl font-bold text-slate-900">{stats.pending}</h4></div>
                        </div>
                        <div className="bg-white border border-slate-200 shadow-sm p-6 rounded-xl flex items-center">
                            <div className="bg-indigo-50 p-4 rounded-full mr-4"><CheckCircle2 className="text-indigo-600 w-8 h-8"/></div>
                            <div><p className="text-slate-500 text-sm">Delivered</p><h4 className="text-3xl font-bold text-slate-900">{stats.delivered}</h4></div>
                        </div>
                    </div>
                )}
                
                {view === 'templates' && <AdminTemplates />}

                {view === 'list' && (
                    <div className="bg-white rounded-xl overflow-x-auto border border-slate-200 shadow-sm custom-scrollbar">
                        <table className="w-full text-left border-collapse min-w-[800px]">
                            <thead>
                                <tr className="bg-slate-50 text-slate-500 text-sm border-b border-slate-200 uppercase tracking-wider font-semibold">
                                    <th className="p-4">Tracking No.</th>
                                    <th className="p-4">From/To</th>
                                    <th className="p-4">Status</th>
                                    <th className="p-4 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100 text-sm">
                                {trackings.map(t => (
                                    <tr key={t.id} className="hover:bg-slate-50 transition">
                                        <td className="p-4 font-semibold text-slate-900">{t.tracking_number}</td>
                                        <td className="p-4 text-slate-600">
                                            <div>{t.from_location}</div>
                                            <div className="text-xs text-slate-400 mt-1">&darr; {t.to_location}</div>
                                        </td>
                                        <td className="p-4">
                                            <span className={`px-2 py-1 text-xs rounded-full font-medium ${t.current_status==='Delivered'?'bg-emerald-50 text-emerald-700 border border-emerald-200':'bg-amber-50 text-amber-700 border border-amber-200'}`}>
                                                {t.current_status}
                                            </span>
                                        </td>
                                        <td className="p-4 text-right">
                                            <button onClick={()=>{setSelectedTracking(t); setView('edit');}} className="p-2 text-slate-500 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg mr-2 transition"><Edit2 className="w-4 h-4"/></button>
                                            <button onClick={async ()=>{
                                                if(confirm('Delete?')) {
                                                    await fetch('api.php?action=delete_tracking', {method:'POST', body: JSON.stringify({id: t.id})});
                                                    loadData();
                                                }
                                            }} className="p-2 text-slate-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition"><Trash2 className="w-4 h-4"/></button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {(view === 'create' || view === 'edit') && (
                    <TrackingForm 
                        tracking={view==='edit'?selectedTracking:null} 
                        onSaved={() => { setView('list'); loadData(); }} 
                        onCancel={() => setView('list')}
                    />
                )}

                {/* Floating Admin Chat Modal */}
                {activeChatTn && (
                    <div className="fixed bottom-4 right-8 w-96 bg-white border border-slate-200 rounded-2xl shadow-2xl z-50 flex flex-col h-[500px]">
                        <div className="p-4 border-b border-slate-200 flex justify-between items-center bg-slate-50 rounded-t-2xl">
                            <h3 className="font-semibold text-slate-900">Chat: {activeChatTn}</h3>
                            <button onClick={()=>setActiveChatTn(null)} className="text-slate-500 hover:text-slate-900"><X className="w-5 h-5"/></button>
                        </div>
                        <ChatBox trackingNumber={activeChatTn} role="admin" />
                    </div>
                )}
            </div>
        </div>
    );
}

function TrackingForm({ tracking, onSaved, onCancel }) {
    const isEdit = !!tracking;
    const [form, setForm] = useState(tracking || {
        sender_name: '', sender_address: '', receiver_name: '', receiver_address: '',
        from_location: '', to_location: '', weight: '', package_type: '', estimated_delivery: '',
        carrier_name: 'LogisX Express', reference_number: '', pickup_time: '', departure_time: '', pieces: '1', created_at: '', progress: ''
    });
    
    // Status update logic (only for edit)
    const [newStatus, setNewStatus] = useState('');
    const [newLocation, setNewLocation] = useState('');
    const [newNote, setNewNote] = useState('');
    const [newTimestamp, setNewTimestamp] = useState('');
    const [updates, setUpdates] = useState([]);

    useEffect(() => {
        if(isEdit) loadUpdates();
    }, [tracking]);

    const loadUpdates = async () => {
        const res = await fetch(`api.php?action=get_tracking_details&tn=${tracking.tracking_number}`);
        const data = await res.json();
        if(data.status === 'success') setUpdates(data.data.updates || []);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        const action = isEdit ? 'update_tracking' : 'create_tracking';
        await fetch(`api.php?action=${action}`, {
            method: 'POST',
            body: JSON.stringify(form)
        });
        onSaved();
    };

    const handleAddStatus = async () => {
        if(!newStatus) return;
        await fetch(`api.php?action=add_status`, {
            method: 'POST',
            body: JSON.stringify({ tracking_id: tracking.id, status_text: newStatus, location: newLocation, note: newNote, timestamp: newTimestamp })
        });
        setNewStatus(''); setNewLocation(''); setNewNote(''); setNewTimestamp('');
        loadUpdates();
        onSaved(); // just to refresh parent
    };

    const handleDeleteStatus = async (updateId) => {
        if(!confirm('Delete this status update?')) return;
        await fetch(`api.php?action=delete_status`, {
            method: 'POST',
            body: JSON.stringify({ update_id: updateId, tracking_id: tracking.id })
        });
        loadUpdates();
        onSaved();
    };

    const handleChange = (e) => setForm({...form, [e.target.name]: e.target.value});

    return (
        <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
            <div className={`bg-white shadow-sm border border-slate-200 p-8 rounded-xl ${isEdit ? 'xl:col-span-2' : 'xl:col-span-3'}`}>
                <div className="flex justify-between items-center mb-6">
                    <h2 className="text-2xl font-bold text-slate-900">{isEdit ? 'Edit Tracking' : 'Create Tracking'} {isEdit && <span className="text-brand-600 ml-2">#{tracking.tracking_number}</span>}</h2>
                    <button onClick={onCancel} className="text-slate-500 hover:text-slate-900 font-medium">Cancel</button>
                </div>
                <form onSubmit={handleSubmit} className="space-y-6">
                    <div className="grid grid-cols-2 gap-6">
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">From Location</label>
                            <input name="from_location" value={form.from_location} onChange={handleChange} required className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">To Location</label>
                            <input name="to_location" value={form.to_location} onChange={handleChange} required className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Sender Name</label>
                            <input name="sender_name" value={form.sender_name} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Receiver Name</label>
                            <input name="receiver_name" value={form.receiver_name} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Weight</label>
                            <input name="weight" value={form.weight} onChange={handleChange} placeholder="e.g. 5.2 kg" className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Package Type</label>
                            <input name="package_type" value={form.package_type} onChange={handleChange} placeholder="e.g. Document, Electronics" className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Est. Delivery Date</label>
                            <input type="date" name="estimated_delivery" value={form.estimated_delivery} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Carrier Name</label>
                            <input name="carrier_name" value={form.carrier_name} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Reference No.</label>
                            <input name="reference_number" value={form.reference_number} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Pieces</label>
                            <input type="number" name="pieces" value={form.pieces} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Creation Date (Override)</label>
                            <input type="datetime-local" name="created_at" value={form.created_at} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Pickup Time</label>
                            <input type="datetime-local" name="pickup_time" value={form.pickup_time} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Departure Time</label>
                            <input type="datetime-local" name="departure_time" value={form.departure_time} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Custom Progress % (Optional)</label>
                            <input type="number" min="0" max="100" name="progress" value={form.progress === null ? '' : form.progress} onChange={handleChange} placeholder="e.g. 75" className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2.5 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                    </div>
                    <div className="border-t border-slate-200 pt-6">
                        <button type="submit" className="bg-brand-600 hover:bg-brand-700 text-white font-semibold py-3 px-8 rounded-lg transition shadow-sm">{isEdit ? 'Save Changes' : 'Create Tracking Number'}</button>
                    </div>
                </form>
            </div>

            {isEdit && (
                <div className="bg-white border border-slate-200 shadow-sm p-6 rounded-xl xl:col-span-1 h-fit">
                    <h3 className="text-xl font-bold text-slate-900 mb-4 border-b border-slate-200 pb-2">Add Status Update</h3>
                    <div className="space-y-4 mb-8">
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Status Title</label>
                            <input value={newStatus} onChange={e=>setNewStatus(e.target.value)} placeholder="e.g. In Transit, Out for Delivery" className="w-full bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:border-indigo-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Current Location</label>
                            <input value={newLocation} onChange={e=>setNewLocation(e.target.value)} className="w-full bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:border-indigo-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Custom Date & Time (Optional)</label>
                            <input type="datetime-local" value={newTimestamp} onChange={e=>setNewTimestamp(e.target.value)} className="w-full bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:border-indigo-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm text-slate-500 mb-1 font-medium">Note (Optional)</label>
                            <textarea value={newNote} onChange={e=>setNewNote(e.target.value)} rows="3" className="w-full bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-900 focus:border-indigo-500 focus:outline-none"></textarea>
                        </div>
                        <button onClick={handleAddStatus} className="w-full bg-indigo-600 hover:bg-indigo-700 text-white py-2 rounded-lg transition mt-2 shadow-sm font-semibold">Publish Update</button>
                    </div>

                    <h3 className="text-xl font-bold text-slate-900 mb-4 border-b border-slate-200 pb-2">Manage History</h3>
                    <div className="space-y-3 max-h-96 overflow-y-auto pr-2 custom-scrollbar">
                        {updates.map(up => (
                            <div key={up.id} className="bg-slate-50 border border-slate-200 rounded-lg p-3 relative flex justify-between items-start group">
                                <div>
                                    <p className="font-semibold text-brand-600 text-sm">{up.status_text}</p>
                                    <p className="text-xs text-slate-500">{up.timestamp} • {up.location}</p>
                                    {up.note && <p className="text-xs text-slate-600 mt-1">{up.note}</p>}
                                </div>
                                <button onClick={() => handleDeleteStatus(up.id)} className="text-slate-400 hover:text-red-500 transition ml-2">
                                    <Trash2 className="w-4 h-4" />
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}

function AdminTemplates() {
    const [templates, setTemplates] = useState([]);
    const [isEditing, setIsEditing] = useState(false);
    const [editId, setEditId] = useState(null);
    const [title, setTitle] = useState('');
    const [message, setMessage] = useState('');

    const loadTemplates = async () => {
        const res = await fetch('api.php?action=get_chat_templates');
        const data = await res.json();
        if(data.status === 'success') setTemplates(data.data);
    };

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

    const handleSave = async (e) => {
        e.preventDefault();
        await fetch('api.php?action=save_chat_template', {
            method: 'POST',
            body: JSON.stringify({ id: editId, title, message })
        });
        setIsEditing(false);
        setEditId(null);
        setTitle('');
        setMessage('');
        loadTemplates();
    };

    const handleDelete = async (id) => {
        if(!confirm('Are you sure you want to delete this template?')) return;
        await fetch('api.php?action=delete_chat_template', {
            method: 'POST',
            body: JSON.stringify({ id })
        });
        loadTemplates();
    };

    const setAutoReply = async (id) => {
        await fetch('api.php?action=set_auto_reply', {
            method: 'POST',
            body: JSON.stringify({ id })
        });
        loadTemplates();
    };

    return (
        <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
            <div className="flex justify-between items-center mb-6 pb-4 border-b border-slate-200">
                <h2 className="text-2xl font-bold text-slate-900 flex items-center">
                    <MessageSquare className="w-6 h-6 mr-3 text-brand-600" /> Chat Templates & Auto-Reply
                </h2>
                {!isEditing && (
                    <button onClick={() => setIsEditing(true)} className="bg-brand-600 hover:bg-brand-700 text-white px-4 py-2 rounded-lg font-medium transition shadow-sm flex items-center">
                        <Plus className="w-4 h-4 mr-2" /> Add Template
                    </button>
                )}
            </div>

            {isEditing ? (
                <form onSubmit={handleSave} className="bg-slate-50 p-6 rounded-xl border border-slate-200 mb-6">
                    <h3 className="text-lg font-semibold text-slate-800 mb-4">{editId ? 'Edit Template' : 'New Template'}</h3>
                    <div className="space-y-4">
                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">Button Title (e.g. Greeting, Delivery Delay)</label>
                            <input required type="text" value={title} onChange={e=>setTitle(e.target.value)} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2 text-slate-900 focus:border-brand-500 focus:outline-none" />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">Message Body</label>
                            <textarea required rows="4" value={message} onChange={e=>setMessage(e.target.value)} className="w-full bg-white border border-slate-300 rounded-lg px-4 py-2 text-slate-900 focus:border-brand-500 focus:outline-none"></textarea>
                        </div>
                    </div>
                    <div className="flex justify-end gap-3 mt-6">
                        <button type="button" onClick={() => {setIsEditing(false); setEditId(null); setTitle(''); setMessage('');}} className="px-4 py-2 text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Cancel</button>
                        <button type="submit" className="bg-brand-600 hover:bg-brand-700 text-white px-6 py-2 rounded-lg transition font-medium shadow-sm">Save Template</button>
                    </div>
                </form>
            ) : (
                <div className="space-y-4">
                    <div className="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6 flex items-start">
                        <Info className="w-5 h-5 text-amber-500 mt-0.5 mr-3 flex-shrink-0" />
                        <div>
                            <h4 className="font-semibold text-amber-800">Auto-Reply Configuration</h4>
                            <p className="text-sm text-amber-700 mt-1">Select one template as an "Auto-Reply". When a user sends a message, the system will automatically reply with that template instantly. Set to "None" to disable auto-replies.</p>
                        </div>
                    </div>
                    <div className="flex gap-2 mb-6">
                        <button onClick={() => setAutoReply(null)} className={`px-4 py-2 rounded-lg text-sm font-semibold transition border ${!templates.find(t=>t.is_auto_reply==1) ? 'bg-slate-800 text-white border-slate-800' : 'bg-white text-slate-600 border-slate-300 hover:bg-slate-50'}`}>Disable Auto-Reply</button>
                    </div>

                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        {templates.map(tpl => (
                            <div key={tpl.id} className={`border rounded-xl p-5 relative group transition ${tpl.is_auto_reply == 1 ? 'border-brand-400 bg-brand-50 ring-2 ring-brand-100' : 'border-slate-200 bg-white hover:border-slate-300'}`}>
                                {tpl.is_auto_reply == 1 && (
                                    <span className="absolute top-4 right-4 bg-brand-500 text-white text-[10px] uppercase font-bold tracking-wider px-2 py-1 rounded">Active Auto-Reply</span>
                                )}
                                <h4 className="font-bold text-slate-900 text-lg mb-2 pr-24">{tpl.title}</h4>
                                <p className="text-sm text-slate-600 bg-slate-50 p-3 rounded-lg border border-slate-100">{tpl.message}</p>
                                <div className="mt-4 pt-4 border-t border-slate-100 flex justify-between items-center opacity-100 lg:opacity-0 group-hover:opacity-100 transition">
                                    <button onClick={() => setAutoReply(tpl.id)} className={`text-sm font-medium ${tpl.is_auto_reply == 1 ? 'text-slate-400 cursor-not-allowed' : 'text-brand-600 hover:text-brand-700'}`} disabled={tpl.is_auto_reply == 1}>
                                        {tpl.is_auto_reply == 1 ? 'Current Auto-Reply' : 'Set as Auto-Reply'}
                                    </button>
                                    <div className="flex gap-2">
                                        <button onClick={() => { setTitle(tpl.title); setMessage(tpl.message); setEditId(tpl.id); setIsEditing(true); }} className="text-slate-400 hover:text-indigo-600 transition p-1"><Edit2 className="w-4 h-4" /></button>
                                        <button onClick={() => handleDelete(tpl.id)} className="text-slate-400 hover:text-red-500 transition p-1"><Trash2 className="w-4 h-4" /></button>
                                    </div>
                                </div>
                            </div>
                        ))}
                        {templates.length === 0 && (
                            <div className="col-span-full py-12 text-center border-2 border-dashed border-slate-200 rounded-xl">
                                <MessageSquare className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                                <p className="text-slate-500">No chat templates created yet.</p>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
