const { useState, useEffect } = React;

function ensureHoroscopeUnifiedTheme() {
    const currentPage = window.location.pathname.split('/').pop() || 'dial.html';
    if (/^(dial|horoscope)\.html$/.test(currentPage)) return;
    document.body.classList.add('horoscope-unified');
    if (!document.querySelector('link[data-horoscope-theme]')) {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = '/css/horoscope-theme.css?v=2';
        link.dataset.horoscopeTheme = 'true';
        document.head.appendChild(link);
    }
}

ensureHoroscopeUnifiedTheme();

function PlayfulTabIcon({ name, soft = false }) {
    const outline = soft ? '#7A82A2' : '#687093';
    const common = {
        viewBox:'0 0 32 32',
        fill:'none',
        stroke:outline,
        strokeWidth:1.35,
        strokeLinecap:'round',
        strokeLinejoin:'round',
        className:'w-[28px] h-[28px]',
        style:{filter:'drop-shadow(0 3px 2px rgba(73,65,111,.16))'},
        'aria-hidden':true
    };
    const shine = <path d="M9 8.5c3-2.2 6.5-2.6 10-1.1" stroke="#FFFFFF" strokeWidth="1.7" opacity=".72" />;
    const icons = {
        home: (
            <svg {...common}>
                <defs><linearGradient id="tab-home" x1="8" y1="5" x2="24" y2="28"><stop stopColor="#E6D9FF"/><stop offset="1" stopColor="#A98BE5"/></linearGradient></defs>
                <path d="m4 15 12-10 12 10v13H4V15Z" fill="url(#tab-home)" />
                <path d="M11 28v-9h10v9" fill="#FFF09A" />
                <path d="M8 15h16" stroke="#FFFFFF" strokeWidth="2" />
                {shine}
            </svg>
        ),
        divination: (
            <svg {...common}>
                <defs><linearGradient id="tab-card" x1="8" y1="4" x2="24" y2="29"><stop stopColor="#BCA7FF"/><stop offset="1" stopColor="#795BE0"/></linearGradient></defs>
                <rect x="7" y="3" width="18" height="26" rx="4" fill="url(#tab-card)" />
                <rect x="10" y="6" width="12" height="20" rx="2.5" fill="#FCF8FF" stroke="#FFFFFF" />
                <path d="m16 9 1.7 4.2L22 15l-4.3 1.8L16 21l-1.7-4.2L10 15l4.3-1.8L16 9Z" fill="#FFD568" />
                <path d="M10 7.5h7" stroke="#FFFFFF" strokeWidth="1.5" opacity=".72" />
            </svg>
        ),
        ai: (
            <svg {...common}>
                <defs><linearGradient id="tab-chat" x1="7" y1="4" x2="24" y2="26"><stop stopColor="#A6F0E3"/><stop offset="1" stopColor="#55C4B6"/></linearGradient></defs>
                <path d="M4 8a5 5 0 0 1 5-5h14a5 5 0 0 1 5 5v11a5 5 0 0 1-5 5h-8l-7 5v-6a5 5 0 0 1-4-4V8Z" fill="url(#tab-chat)" />
                <circle cx="12" cy="14" r="1.3" fill={outline} stroke="none" />
                <circle cx="20" cy="14" r="1.3" fill={outline} stroke="none" />
                <path d="M12 19c2.5 1.7 5.5 1.7 8 0" stroke="#FFFFFF" strokeWidth="2" />
                {shine}
            </svg>
        ),
        community: (
            <svg {...common}>
                <defs><linearGradient id="tab-pink" x1="5" y1="4" x2="13" y2="14"><stop stopColor="#FFBED0"/><stop offset="1" stopColor="#F27498"/></linearGradient></defs>
                <rect x="4" y="4" width="10" height="10" rx="3" fill="url(#tab-pink)" />
                <rect x="18" y="4" width="10" height="10" rx="3" fill="#FFD86D" />
                <rect x="4" y="18" width="10" height="10" rx="3" fill="#72D5C7" />
                <rect x="18" y="18" width="10" height="10" rx="3" fill="#85BCF0" />
                <path d="M8 9h2M22 9h2M8 23h2M22 23h2" stroke="#FFFFFF" strokeWidth="2" />
                <path d="M6.5 6.5h4M20.5 6.5h4" stroke="#FFFFFF" strokeWidth="1.3" opacity=".65" />
            </svg>
        ),
        profile: (
            <svg {...common}>
                <defs><linearGradient id="tab-person" x1="8" y1="5" x2="23" y2="28"><stop stopColor="#FFD0DE"/><stop offset=".45" stopColor="#FF91B0"/><stop offset=".46" stopColor="#BDE3FF"/><stop offset="1" stopColor="#76B5E9"/></linearGradient></defs>
                <circle cx="16" cy="10" r="6" fill="#FF9DB8" />
                <path d="M5 29c.7-8 4.5-12 11-12s10.3 4 11 12H5Z" fill="url(#tab-person)" />
                <circle cx="14" cy="10" r=".8" fill={outline} stroke="none" />
                <circle cx="18" cy="10" r=".8" fill={outline} stroke="none" />
                <path d="M14 13c1.3 1 2.7 1 4 0" stroke="#FFFFFF" />
                <path d="M13 5.5c2-1 4-1 6 0" stroke="#FFFFFF" strokeWidth="1.4" opacity=".7" />
            </svg>
        )
    };
    return icons[name];
}

function TabBar({ currentPath, variant = 'default' }) {
    useEffect(() => {
        const viewport = window.visualViewport;
        const syncViewportHeight = () => {
            const height = viewport ? viewport.height : window.innerHeight;
            document.documentElement.style.setProperty('--app-height', `${Math.round(height)}px`);
        };
        syncViewportHeight();

        // Some calculation pages render the fixed tab bar outside their
        // scrollable #root. Reserve its space inside that viewport so the
        // final action cannot end up behind the browser chrome or tab bar.
        const pageName = window.location.pathname.split('/').pop() || 'dial.html';
        const appRoot = document.getElementById('root');
        const hasExternalTabbar = Boolean(document.getElementById('tabbar-root'));
        if (appRoot && hasExternalTabbar && pageName !== 'dial.html') {
            appRoot.style.height = 'var(--app-height, 100dvh)';
            appRoot.style.boxSizing = 'border-box';
            appRoot.style.paddingBottom = 'calc(82px + env(safe-area-inset-bottom, 0px))';
            appRoot.dataset.tabbarViewport = 'true';
        }

        viewport?.addEventListener('resize', syncViewportHeight);
        viewport?.addEventListener('scroll', syncViewportHeight);
        window.addEventListener('orientationchange', syncViewportHeight);
        return () => {
            viewport?.removeEventListener('resize', syncViewportHeight);
            viewport?.removeEventListener('scroll', syncViewportHeight);
            window.removeEventListener('orientationchange', syncViewportHeight);
        };
    }, []);

    const tabs = [
        { id: 'home', name: '首页', icon: (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                <polyline points="9 22 9 12 15 12 15 22"></polyline>
            </svg>
        ), path: 'dial.html', activePattern: /(dial\.html|app_home\.html)$/ },
        { id: 'divination', name: '测算', icon: (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                <rect x="4" y="2" width="16" height="20" rx="2" ry="2"></rect>
                <line x1="8" y1="6" x2="16" y2="6"></line>
                <line x1="8" y1="10" x2="16" y2="10"></line>
                <line x1="8" y1="14" x2="12" y2="14"></line>
            </svg>
        ), path: 'divination.html', activePattern: /(divination\.html|quick_test\.html|index\.html|bazi\.html|horoscope\.html|compatibility\.html|destiny\.html|attachment\.html|mental\.html|relationship\.html|app_divination\.html)$/ },
        { id: 'ai', name: 'AI陪伴', icon: (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                <path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"></path>
                <path d="M8 9h.01M12 9h.01M16 9h.01"></path>
            </svg>
        ), path: 'ai.html', activePattern: /(ai\.html|ai_chat\.html)$/ },
        { id: 'community', name: '广场', icon: (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                <rect x="3" y="3" width="7" height="7" rx="2"></rect>
                <rect x="14" y="3" width="7" height="7" rx="2"></rect>
                <rect x="3" y="14" width="7" height="7" rx="2"></rect>
                <rect x="14" y="14" width="7" height="7" rx="2"></rect>
            </svg>
        ), path: 'community.html', activePattern: /(community\.html|app_community\.html)$/ },
        { id: 'profile', name: '我的', icon: (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                <circle cx="12" cy="7" r="4"></circle>
            </svg>
        ), path: 'profile.html', activePattern: /(profile\.html|app_profile\.html|history\.html)$/ }
    ];

    const currentFilename = currentPath || window.location.pathname.split('/').pop() || 'dial.html';
    const useFloatingStyle = true;
    const useDreamyStyle = variant === 'dreamy' || document.body.classList.contains('horoscope-unified');
    const usePlayfulStyle = variant === 'playful' || useDreamyStyle;
    
    const activeIndex = tabs.findIndex(tab => tab.activePattern.test(currentFilename)) !== -1 
        ? tabs.findIndex(tab => tab.activePattern.test(currentFilename)) 
        : 0;

    const handleNavigation = (path) => {
        if (path === '#') return;
        window.location.href = window.location.protocol === 'file:' ? path : '/' + path;
    };

    return (
        <React.Fragment>
            <div
                className="w-full shrink-0 flex-none"
                style={{height:'calc(82px + env(safe-area-inset-bottom, 0px))'}}
                aria-hidden="true"
            ></div>
            
            <div className={useFloatingStyle
                ? `fixed left-1/2 -translate-x-1/2 w-[calc(100%-20px)] max-w-[410px] h-[58px] rounded-[18px] backdrop-blur-2xl z-[80] flex justify-around items-center px-1 ${useDreamyStyle ? 'bg-white/60 border border-white/82 shadow-[0_10px_30px_rgba(75,61,121,0.11),inset_0_1px_0_rgba(255,255,255,0.72)]' : usePlayfulStyle ? 'bg-white/74 border border-white/90 shadow-[0_10px_30px_rgba(75,61,121,0.14),inset_0_1px_0_rgba(255,255,255,0.8)]' : 'bg-white/78 border border-white/90 shadow-[0_10px_30px_rgba(75,61,121,0.16)]'}`
                : "fixed bottom-0 left-1/2 -translate-x-1/2 w-full max-w-[430px] h-[60px] bg-white/60 backdrop-blur-2xl border-t border-white/60 z-[9999] flex justify-around items-center pb-[env(safe-area-inset-bottom)] shadow-[0_-5px_25px_rgba(139,93,209,0.08)]"
            } style={useFloatingStyle ? {bottom:'max(8px, env(safe-area-inset-bottom, 0px))'} : undefined}>
                {tabs.map((tab, idx) => {
                    const isActive = idx === activeIndex;

                    return (
                        <div 
                            key={tab.id}
                            onClick={() => handleNavigation(tab.path)}
                            className="flex flex-col items-center justify-center cursor-pointer flex-1 h-full select-none relative"
                        >
                            {/* Default active background used by the other pages. */}
                            {isActive && !useFloatingStyle && (
                                <div className="absolute inset-0 bg-gradient-to-t from-[#8b5dd1]/10 to-transparent w-full h-full rounded-t-lg -z-10"></div>
                            )}
                            
                            <div className={`flex items-center justify-center transition-all duration-300 ${useDreamyStyle ? (isActive ? 'w-8 h-8 rounded-full mb-0.5 bg-white/42 border border-white/75 shadow-[0_0_14px_rgba(139,114,232,0.22)]' : 'w-8 h-8 mb-0.5 opacity-60') : usePlayfulStyle ? (isActive ? 'w-9 h-9 rounded-full mb-0 bg-white/62 border border-white/90 shadow-[0_0_18px_rgba(139,114,232,0.3)] -translate-y-0.5' : 'w-8 h-8 mb-0.5 opacity-65') : `${useFloatingStyle ? 'w-8 h-8 rounded-full mb-0.5' : 'w-5 h-5 mb-1'} ${isActive ? (useFloatingStyle ? 'text-[#7857c6] bg-[#eee8ff] shadow-[0_3px_10px_rgba(120,87,198,0.18)] -translate-y-0.5' : 'text-[#8b5dd1]') : 'text-[#9ca3b3]'}`}`}>
                                {usePlayfulStyle ? <PlayfulTabIcon name={tab.id} soft={useDreamyStyle} /> : tab.icon}
                            </div>
                            <span className={`text-[10px] leading-none transition-all duration-300 ${useDreamyStyle ? (isActive ? 'text-[#65749B] font-bold' : 'text-[#747C92] font-medium') : usePlayfulStyle ? (isActive ? 'text-[#554A70] font-black' : 'text-[#777183] font-semibold') : (isActive ? (useFloatingStyle ? 'text-[#6f50b8] font-bold' : 'text-[#8b5dd1] font-bold shadow-sm') : 'text-[#73798a] font-medium')}`}>
                                {tab.name}
                            </span>
                            {useFloatingStyle && isActive && !usePlayfulStyle && (
                                <span className="absolute -bottom-0.5 w-4 h-[2px] rounded-full bg-[#8664d1]"></span>
                            )}
                        </div>
                    );
                })}
            </div>
        </React.Fragment>
    );
}

window.TabBar = TabBar;
