const { useState, useEffect } = React;

const NavDropdown = ({ label, items, href }) => {
    const [isOpen, setIsOpen] = useState(false);
    return (
        <div className="relative group h-full flex items-center" onMouseEnter={() => setIsOpen(true)} onMouseLeave={() => setIsOpen(false)}>
            <button
                className="flex items-center gap-1 text-sm font-medium text-gray-600 hover:text-clay-500 transition-colors py-2"
                onClick={() => { if (href) window.location.href = href; }}
                type="button"
            >
                {label} <i className="fa-solid fa-chevron-down text-xs opacity-50"></i>
            </button>
            {isOpen && (
                <div className="absolute top-full left-0 w-48 bg-white shadow-[0_20px_50px_-12px_rgba(0,0,0,0.1)] rounded-xl border border-gray-100 py-2 z-50 animate-fadeIn">
                    {items.map((item, idx) => (
                        <a key={idx} href={item.href} className="block px-4 py-2 text-sm text-gray-700 hover:bg-slate-50 hover:text-clay-600 transition-colors">{item.label}</a>
                    ))}
                </div>
            )}
        </div>
    );
};

const MegaDropdown = ({ label, columns, href }) => {
    const [isOpen, setIsOpen] = useState(false);

    return (
        <div
            className="relative h-full flex items-center"
            onMouseEnter={() => setIsOpen(true)}
            onMouseLeave={() => setIsOpen(false)}
        >
            <button
                className={`flex items-center gap-2 text-sm font-medium transition-colors py-2 px-2 rounded-lg ${isOpen ? 'text-clay-600 bg-slate-50' : 'text-gray-600 hover:text-clay-500 hover:bg-slate-50'}`}
                onClick={() => { if (href) window.location.href = href; }}
                type="button"
                aria-haspopup="menu"
                aria-expanded={isOpen}
            >
                <span>{label}</span>
                <i className={`fa-solid fa-chevron-down text-[11px] transition-transform ${isOpen ? 'rotate-180' : ''} opacity-60`}></i>
            </button>

            {isOpen && (
                <div className="absolute top-full left-1/2 -translate-x-1/2 pt-3 z-50">
                    <div className="w-[56rem] max-w-[92vw] bg-white rounded-2xl border border-gray-100 shadow-[0_30px_80px_-20px_rgba(0,0,0,0.25)] overflow-hidden animate-fadeIn">
                        <div className="px-6 py-4 border-b border-gray-100 bg-gradient-to-b from-slate-50 to-white">
                            <div className="text-xs font-bold uppercase tracking-widest text-gray-400">Browse</div>
                            <div className="mt-1 text-sm text-gray-600">Learn about kava & kratom, the industry, and the association.</div>
                        </div>

                        <div className="p-6">
                            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                                {columns.map((col, i) => (
                                    <div key={i} className="min-w-0">
                                        <div className="text-[11px] font-bold uppercase tracking-widest text-gray-400 mb-3">{col.heading}</div>
                                        <div className="space-y-1">
                                            {col.items.map((item, j) => (
                                                <a
                                                    key={j}
                                                    href={item.href}
                                                    className="group flex items-start justify-between gap-3 text-sm text-gray-700 hover:text-forest-900 rounded-xl px-3 py-2 hover:bg-slate-50 transition-colors"
                                                >
                                                    <span className="leading-snug">{item.label}</span>
                                                    <i className="fa-solid fa-arrow-right text-[11px] mt-1 opacity-0 group-hover:opacity-60 transition-opacity"></i>
                                                </a>
                                            ))}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

const Button = ({ children, variant = 'primary', className = '', onClick }) => {
    const base = "px-8 py-3 rounded-full font-bold transition-all duration-300 flex items-center justify-center gap-2 transform hover:scale-105";
    const variants = {
        primary: "bg-clay-500 text-white hover:bg-clay-600 shadow-[0_0_40px_-10px_rgba(192,108,75,0.5)]",
        forest: "bg-forest-800 text-white hover:bg-forest-900 shadow-md",
        gold: "bg-gold-500 text-forest-900 hover:bg-gold-600 shadow-md",
        outline: "bg-transparent border-2 border-white text-white hover:bg-white/10"
    };
    return <button onClick={onClick} className={`${base} ${variants[variant]} ${className}`}>{children}</button>;
};

const Header = () => {
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
    return (
        <nav className="fixed w-full z-50 bg-white/90 backdrop-blur-md border-b border-gray-200/50 shadow-sm transition-all duration-300">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="flex justify-between h-24 items-center">
                    <a href="/" className="flex items-center gap-3 cursor-pointer group">
                        <div className="w-20 h-20 rounded-full overflow-hidden bg-white flex items-center justify-center border border-gray-200 group-hover:border-clay-500 transition-colors">
                            <img src="/assets/kkra-logo.png" alt="KKRA" className="w-full h-full object-contain p-1" />
                        </div>
                        <div className="leading-tight">
                            <div className="font-bold text-brand-green tracking-wide text-sm md:text-base">KAVA & KRATOM</div>
                            <div className="text-xs text-clay-500 uppercase tracking-widest font-bold">Retailers Association</div>
                        </div>
                    </a>
                    <div className="hidden md:flex items-center space-x-8 h-full">
                        <MegaDropdown label="About" columns={[
                            {
                                heading: 'About Kratom',
                                items: [
                                    { label: 'What is Kratom?', href: '/what-is-kratom/' },
                                    { label: 'Understanding Kratom: Traditional Use vs. Modern Concerns', href: '/understanding-kratom/' },
                                    { label: 'The Entourage Effect in Kratom: Why the Whole Plant Matters', href: '/kratom-entourage-effect/' },
                                ]
                            },
                            {
                                heading: 'About Kava',
                                items: [
                                    { label: 'What is Kava?', href: '/what-is-kava/' },
                                    { label: 'Kava: An Ancient Pacific Tradition and a Modern Pro-Social Beverage', href: '/kava-ancient-tradition/' },
                                ]
                            },
                            {
                                heading: 'About Kava Bars',
                                items: [
                                    { label: 'What are Kava Bars?', href: '/what-are-kava-bars/' },
                                ]
                            },
                            {
                                heading: 'About the Association',
                                items: [
                                    { label: 'About the Association', href: '/about-us/' },
                                    { label: 'Why Join?', href: '/why-join/' },
                                ]
                            },
                        ]} />
                        <NavDropdown label="Membership" href="/membership/" items={[
                            { label: "Individual Membership", href: "/membership/individual/" },
                            { label: "Business Membership", href: "/membership/business/" }
                        ]} />
                        <NavDropdown label="Advocacy" items={[ 
                            { label: "Our Policy Priorities", href: "/about-us/" },
                            { label: "Advocacy Initiatives", href: "/join/" }
                        ]} />
                        <NavDropdown label="Resources" items={[ 
                            // { label: "Scientific Studies", href: "#" }, // Coming soon
                            // { label: "Press Release", href: "#" }, // Coming soon
                            { label: "Sweepstakes", href: "/tallahassee-tea-party-sweepstakes-giveaway.html" }
                        ]} />
                        <Button variant="forest" className="!px-6 !py-2 !text-sm" onClick={() => window.location.href='/donate/'}>Donate</Button>
                    </div>
                    <div className="flex items-center md:hidden">
                        <button onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)} className="text-gray-500 hover:text-clay-500 p-2">
                            <i className={`fa-solid ${isMobileMenuOpen ? 'fa-xmark' : 'fa-bars'} text-2xl`}></i>
                        </button>
                    </div>
                </div>
            </div>
            {isMobileMenuOpen && (
                <div className="md:hidden bg-white border-t border-gray-100 pb-4 shadow-xl max-h-[80vh] overflow-y-auto">
                    <div className="px-4 pt-4 space-y-4">
                        <div className="pt-2 text-xs font-bold uppercase tracking-widest text-gray-400">About</div>
                        <a href="/what-is-kava/" className="block py-2 text-gray-700">What is Kava?</a>
                        <a href="/kava-ancient-tradition/" className="block py-2 text-gray-700">Kava: Ancient Tradition (Article)</a>
                        <a href="/what-is-kratom/" className="block py-2 text-gray-700">What is Kratom?</a>
                        <a href="/understanding-kratom/" className="block py-2 text-gray-700">Understanding Kratom</a>
                        <a href="/kratom-entourage-effect/" className="block py-2 text-gray-700">Kratom Entourage Effect</a>
                        <a href="/what-are-kava-bars/" className="block py-2 text-gray-700">What are Kava Bars?</a>
                        <a href="/about-us/" className="block py-2 text-gray-700">About the Association</a>
                        <a href="/membership/" className="block py-2 text-gray-700">Membership</a>
                        <a href="/membership/individual/" className="block py-2 text-gray-700">Individual Membership</a>
                        <a href="/membership/business/" className="block py-2 text-gray-700">Business Membership</a>
                        <a href="/about-us/" className="block py-2 text-gray-700">Policy Priorities</a>
                        <a href="/why-join/" className="block py-2 text-gray-700">Advocacy Initiatives</a>
                        <a href="/tallahassee-tea-party-sweepstakes-giveaway.html" className="block py-2 text-gray-700">Sweepstakes</a>
                        <button className="w-full bg-forest-800 text-white py-3 rounded-full font-bold mt-4" onClick={() => window.location.href='/donate/'}>Donate</button>
                    </div>
                </div>
            )}
        </nav>
    );
};

const Footer = () => {
    const [email, setEmail] = useState('');
    const [status, setStatus] = useState('idle'); // idle, loading, success, error
    const [message, setMessage] = useState('');

    const handleSubscribe = async (e) => {
        e.preventDefault();
        if (!email) return;

        setStatus('loading');
        setMessage('');

        try {
            const res = await fetch('/backend/subscribe.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email })
            });
            const data = await res.json();

            if (res.ok && data.success) {
                setStatus('success');
                setMessage(data.message || 'Subscribed successfully!');
                setEmail('');
            } else {
                setStatus('error');
                setMessage(data.error || data.message || 'Something went wrong.');
            }
        } catch (err) {
            setStatus('error');
            setMessage('Connection failed. Please try again.');
        }
    };

    return (
    <footer className="bg-slate-900 text-white pt-16 pb-8 border-t border-slate-800 font-sans">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-12 mb-12">
                <div className="col-span-1 md:col-span-1">
                    <div className="flex items-center gap-3 mb-6">
                        <div className="w-10 h-10 rounded-full overflow-hidden bg-white flex items-center justify-center border border-slate-700">
                            <img src="/assets/kkra-logo.png" alt="KKRA" className="w-full h-full object-contain p-1" />
                        </div>
                        <div className="leading-tight">
                            <div className="font-bold text-white tracking-wide text-base">KAVA & KRATOM</div>
                            <div className="text-xs text-clay-400 uppercase tracking-widest font-bold">Retailers Association</div>
                        </div>
                    </div>
                    <p className="text-slate-400 text-sm leading-relaxed">Dedicated to the safe, responsible, and legal access to traditional botanical products through science and advocacy.</p>
                </div>
                <div>
                    <h4 className="font-bold text-clay-400 mb-4 uppercase text-xs tracking-wider">Resources</h4>
                    <ul className="space-y-2 text-sm text-slate-300">
                        {/* <li><a href="#" className="hover:text-white transition">Research Library</a></li> */}
                        {/* <li><a href="#" className="hover:text-white transition">GMP Guidelines</a></li> */}
                        <li><span className="text-slate-600 cursor-not-allowed">Research Library (Coming Soon)</span></li>
                        <li><span className="text-slate-600 cursor-not-allowed">GMP Guidelines (Coming Soon)</span></li>
                    </ul>
                </div>
                <div>
                    <h4 className="font-bold text-clay-400 mb-4 uppercase text-xs tracking-wider">Advocacy</h4>
                    <ul className="space-y-2 text-sm text-slate-300">
                        {/* <li><a href="#" className="hover:text-white transition">Legislative Map</a></li> */}
                        <li><span className="text-slate-600 cursor-not-allowed">Legislative Map (Coming Soon)</span></li>
                        <li><a href="/donate.html" className="hover:text-white transition">Donate</a></li>
                    </ul>
                </div>
                <div>
                    <h4 className="font-bold text-clay-400 mb-4 uppercase text-xs tracking-wider">Stay Informed</h4>
                    <form onSubmit={handleSubscribe} className="flex gap-2 mb-4">
                        <input 
                            type="email" 
                            placeholder="Enter email" 
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            disabled={status === 'loading' || status === 'success'}
                            className="bg-slate-800 border-none rounded px-3 py-2 text-sm w-full focus:ring-1 focus:ring-clay-400 text-white disabled:opacity-50" 
                        />
                        <button 
                            type="submit" 
                            disabled={status === 'loading' || status === 'success'}
                            className="bg-clay-500 hover:bg-clay-600 text-white rounded px-3 py-2 text-sm font-bold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {status === 'loading' ? <i className="fa-solid fa-spinner fa-spin"></i> : <i className="fa-solid fa-paper-plane"></i>}
                        </button>
                    </form>
                    {message && (
                        <div className={`text-xs ${status === 'success' ? 'text-green-400' : 'text-red-400'}`}>
                            {message}
                        </div>
                    )}
                </div>
            </div>
            <div className="border-t border-slate-800 pt-8 text-xs text-slate-500 text-justify">
                <div className="flex flex-col md:flex-row justify-between items-center mt-8 gap-4">
                    <div className="flex flex-col gap-1 text-center md:text-left">
                        <span>&copy; 2026 Kava & Kratom Retailers Association. All rights reserved.</span>
                        <span className="text-slate-300">
                            Built with Love by the Makers of{' '}
                            <a href="https://happykava.app/" target="_blank" rel="noopener noreferrer" className="text-clay-400 hover:text-clay-300 underline underline-offset-4 transition">HappyKava App</a>
                        </span>
                    </div>
                    <div className="flex gap-4">
                        <a href="/privacy-policy.html" className="hover:text-white transition">Privacy Policy</a>
                        <a href="/terms-of-service.html" className="hover:text-white transition">Terms of Service</a>
                    </div>
                </div>
            </div>
        </div>
    </footer>
    );
};

const Hero = () => (
    <div className="relative pt-24 min-h-[85vh] md:min-h-[90vh] flex items-center">
        <div className="absolute inset-0 z-0 bg-[#1a4731] hero-pattern"></div>
        <div className="absolute inset-0 z-0 bg-gradient-to-r from-forest-900/95 to-forest-800/85"></div>
        
        <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 flex flex-col items-center text-center animate-fadeIn">
            <span className="inline-block py-1.5 px-4 rounded-full bg-white/10 border border-white/20 text-white text-xs font-bold tracking-widest mb-8 uppercase">
                The Authority on Botanical Safety
            </span>
            <h1 className="text-4xl md:text-6xl lg:text-7xl font-serif font-bold text-white mb-8 leading-tight max-w-5xl">
                The Unified Voice of the <span className="text-clay-500 italic">Kava and Kratom</span> Retail Industry
            </h1>
            <p className="mt-4 max-w-2xl text-xl text-gray-200 font-light mb-10 leading-relaxed">
                Uniting the kava and kratom retail industry for science-based advocacy and sensible regulation.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 w-full justify-center">
                <Button variant="primary" onClick={() => window.location.href='/membership/'}>
                    Become a Member <i className="fa-solid fa-arrow-right ml-1"></i>
                </Button>
                <Button variant="outline" onClick={() => window.location.href='/why-join/'}>
                    <i className="fa-solid fa-circle-info"></i> More Info
                </Button>
            </div>
        </div>
    </div>
);

const WhyJoinSection = ({ showTitle = true }) => (
    <div className="py-20 bg-white">
        <div className="max-w-6xl mx-auto px-6">
            {showTitle && <h2 className="text-4xl md:text-5xl font-serif font-bold text-forest-900 text-center mb-16">Why Join?</h2>}
            <div className="grid md:grid-cols-2 gap-10">
                {[ 
                    {
                        icon: '/assets/icons/why-join-unified-advocacy.svg',
                        title: 'Unified Advocacy',
                        body: 'Gain a powerful voice in regulatory discussions with lawmakers at local, state, and federal levels. Our collective representation amplifies your concerns and protects your business interests.'
                    },
                    {
                        icon: '/assets/icons/why-join-regulatory-resources.svg',
                        title: 'Regulatory Resources',
                        body: 'Access expert legal guidance on compliance issues, stay informed about regulatory changes, and receive support during legislative challenges that could impact your business.'
                    },
                    {
                        icon: '/assets/icons/why-join-industry-standards.svg',
                        title: 'Industry Standards',
                        body: 'Demonstrate your commitment to quality and safety by adopting our industry-leading best practices and standards that enhance consumer confidence and business reputation.'
                    },
                    {
                        icon: '/assets/icons/why-join-scientific-resources.svg',
                        title: 'Scientific Resources',
                        body: 'Gain exclusive access to peer-reviewed research, expert analyses, and educational materials that support product knowledge and informed customer conversations.'
                    },
                ].map((card, i) => (
                    <div key={i} className="flex gap-6 items-start">
                        <div className="w-14 h-14 flex items-center justify-center flex-shrink-0">
                            <img src={card.icon} alt="" className="w-14 h-14" />
                        </div>
                        <div>
                            <h3 className="text-2xl font-serif font-bold text-forest-900">{card.title}</h3>
                            <p className="mt-3 text-gray-700 leading-relaxed">{card.body}</p>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    </div>
);

const CampaignSlides = () => (
    <section className="bg-slate-50 border-t border-slate-100">
        <div className="max-w-7xl mx-auto px-6 py-12 space-y-8">
            <div className="bg-white rounded-[2.5rem] border border-slate-100 shadow-sm overflow-hidden">
                <div className="p-8 md:p-10">
                    <div className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-4">Organized Advocacy</div>
                    <p className="text-xl md:text-2xl font-serif font-bold text-forest-900 leading-relaxed">
                        Without organized advocacy, kratom faces the constant threat of blanket prohibition that ignores science, tradition, and the millions of Americans who depend on safe access to this botanical.
                    </p>
                </div>
            </div>

            <div className="bg-forest-900 rounded-[2.5rem] border border-forest-900 shadow-2xl overflow-hidden">
                <div className="p-8 md:p-10 text-white">
                    <div className="text-xs font-bold uppercase tracking-widest text-white/70 mb-4">Join the Movement</div>
                    <h3 className="text-4xl md:text-5xl font-serif font-bold mb-2">Don’t stand on the sidelines</h3>
                    <p className="text-xl md:text-2xl text-white/80 font-serif italic mb-8">
                        while the future of the industry is decided without you.
                    </p>
                    <p className="text-white font-bold text-lg mb-8">
                        Your industry needs you, and KKRA makes sure you’re heard.
                    </p>
                    <div className="flex flex-col sm:flex-row gap-3">
                        <a href="/membership/" className="inline-flex items-center justify-center px-6 py-3 rounded-full font-bold bg-gold-500 text-forest-900 hover:bg-gold-600 transition-colors">Become a Member</a>
                        <a href="/donate/" className="inline-flex items-center justify-center px-6 py-3 rounded-full font-bold border-2 border-white/30 text-white hover:bg-white/10 transition-colors">Donate</a>
                    </div>
                </div>
            </div>
        </div>
    </section>
);

// Make components available globally
window.NavDropdown = NavDropdown;
window.MegaDropdown = MegaDropdown;
window.Button = Button;
window.Header = Header;
window.Footer = Footer;
window.Hero = Hero;
window.WhyJoinSection = WhyJoinSection;
window.CampaignSlides = CampaignSlides;

// KKRA runtime config (override by setting these before components.jsx loads)
window.KKRA_API_BASE = window.KKRA_API_BASE || '/api';
window.KKRA_ZEFFY = window.KKRA_ZEFFY || {
    // Fill these with real Zeffy embed links when available.
    // Example modal button attribute expects: https://www.zeffy.com/embed/ticketing/<slug>?modal=true
    individual_one_time_modal: '',
    individual_monthly_modal: '',
    business_standard_monthly_modal: '',
    business_standard_annual_modal: '',
    business_executive_annual_modal: '',
};
