import React, { useState, useEffect } from 'react';
import { Globe, ChevronDown } from 'lucide-react';
import ReactMarkdown from 'react-markdown';

const LegalDocuments = () => {
    const [currentDoc, setCurrentDoc] = useState('terms');
    const [language, setLanguage] = useState('zh-CN');
    const [showLangMenu, setShowLangMenu] = useState(false);
    const [hideHeader, setHideHeader] = useState(true);
    const [content, setContent] = useState('');
    const [loading, setLoading] = useState(true);

    // 动态导入 Markdown 文件
    useEffect(() => {
        const loadMarkdown = async () => {
            setLoading(true);
            try {
                const docPath = currentDoc === 'terms' ? 'terms' : 'privacy';
                const response = await import(`./data/${docPath}/${language}.md?raw`);
                setContent(response.default);
            } catch (error) {
                console.error('Error loading markdown:', error);
                setContent('内容加载失败，请稍后重试。');
            } finally {
                setLoading(false);
            }
        };

        loadMarkdown();
    }, [currentDoc, language]);

    // 解析URL并设置初始状态
    // 解析 URL query 并设置初始状态
    useEffect(() => {
        const searchParams = new URLSearchParams(window.location.search);
        const docType = searchParams.get('content') ;
        const lang = searchParams.get('language') ;


        console.log(lang);
        if (docType === null && lang === null) {
            setHideHeader(false);
            return;
        }

        // 映射文档类型
        const docMap = {
            'user-agreement': 'terms',
            'terms': 'terms',
            'privacy-policy': 'privacy',
            'privacy': 'privacy'
        };

        // 映射语言类型
        const langMap = {
            'zh': 'zh-CN',
            'zh-FT': 'zh-TW',
            'en': 'en',
            'ms': 'ms',
        }

        if (docMap[docType.toLowerCase()] && langMap[lang]) {
            setCurrentDoc(docMap[docType.toLowerCase()]);
            setLanguage(langMap[lang]);
            setHideHeader(true);
        } else {
            setHideHeader(false);
        }
    }, []);

    const languages = {
        'zh-CN': '简体中文',
        'zh-TW': '繁體中文',
        'en': 'English',
        'ms': 'Bahasa Melayu'
    };

    const navItems = {
        'zh-CN': { terms: '用户协议', privacy: '隐私政策' },
        'zh-TW': { terms: '用戶協議', privacy: '隱私政策' },
        'en': { terms: 'Terms', privacy: 'Privacy' },
        'ms': { terms: 'Terma', privacy: 'Privasi' }
    };

    const lastUpdated = {
        'zh-CN': '最后更新时间',
        'zh-TW': '最後更新時間',
        'en': 'Last Updated',
        'ms': 'Kemaskini Terakhir'
    };

    const titles = {
        terms: {
            'zh-CN': '用户协议',
            'zh-TW': '用戶協議',
            'en': 'Terms of Service',
            'ms': 'Perjanjian Pengguna'
        },
        privacy: {
            'zh-CN': '隐私政策',
            'zh-TW': '隱私政策',
            'en': 'Privacy Policy',
            'ms': 'Dasar Privasi'
        }
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
            {/* Header - 根据 hideHeader 状态决定是否显示 */}
            {!hideHeader && (
                <header className="sticky top-0 z-50 bg-white/80 backdrop-blur-xl border-b border-gray-200/50">
                    <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
                        <div className="flex items-center justify-between h-16 sm:h-20">
                            {/* Logo */}
                            <div className="flex items-center space-x-2">
                                <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center">
                                    <span className="text-white text-sm sm:text-base font-bold">S</span>
                                </div>
                                <span className="text-lg sm:text-xl font-semibold text-gray-900 hidden sm:inline">
                  Social App
                </span>
                            </div>

                            {/* Navigation */}
                            <nav className="flex items-center space-x-2 sm:space-x-4">
                                <button
                                    onClick={() => setCurrentDoc('terms')}
                                    className={`px-3 sm:px-4 py-2 rounded-lg text-sm sm:text-base font-medium transition-all ${
                                        currentDoc === 'terms'
                                            ? 'bg-gray-900 text-white shadow-lg'
                                            : 'text-gray-600 hover:bg-gray-100'
                                    }`}
                                >
                                    {navItems[language].terms}
                                </button>
                                <button
                                    onClick={() => setCurrentDoc('privacy')}
                                    className={`px-3 sm:px-4 py-2 rounded-lg text-sm sm:text-base font-medium transition-all ${
                                        currentDoc === 'privacy'
                                            ? 'bg-gray-900 text-white shadow-lg'
                                            : 'text-gray-600 hover:bg-gray-100'
                                    }`}
                                >
                                    {navItems[language].privacy}
                                </button>

                                {/* Language Selector */}
                                <div className="relative">
                                    <button
                                        onClick={() => setShowLangMenu(!showLangMenu)}
                                        className="flex items-center space-x-1 sm:space-x-2 px-2 sm:px-3 py-2 rounded-lg text-gray-600 hover:bg-gray-100 transition-all"
                                    >
                                        <Globe className="w-4 h-4 sm:w-5 sm:h-5" />
                                        <span className="text-xs sm:text-sm font-medium hidden sm:inline">
                      {languages[language]}
                    </span>
                                        <ChevronDown className="w-3 h-3 sm:w-4 sm:h-4" />
                                    </button>

                                    {showLangMenu && (
                                        <div className="absolute right-0 mt-2 w-40 sm:w-48 bg-white rounded-xl shadow-2xl border border-gray-100 py-2 z-50">
                                            {Object.entries(languages).map(([code, name]) => (
                                                <button
                                                    key={code}
                                                    onClick={() => {
                                                        setLanguage(code);
                                                        setShowLangMenu(false);
                                                    }}
                                                    className={`w-full text-left px-4 py-2.5 text-sm transition-colors ${
                                                        language === code
                                                            ? 'bg-blue-50 text-blue-600 font-medium'
                                                            : 'text-gray-700 hover:bg-gray-50'
                                                    }`}
                                                >
                                                    {name}
                                                </button>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            </nav>
                        </div>
                    </div>
                </header>
            )}

            {/* Main Content */}
            <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12 lg:py-16">
                <article className="bg-white rounded-2xl sm:rounded-3xl shadow-xl p-6 sm:p-10 lg:p-16">
                    {/* Title */}
                    <div className="mb-8 sm:mb-12">
                        <h1 className="text-3xl sm:text-4xl lg:text-5xl font-bold text-gray-900 mb-4 sm:mb-6">
                            {titles[currentDoc][language]}
                        </h1>
                        <div className="flex items-center space-x-2 text-xs sm:text-sm text-gray-500">
                            <span>{lastUpdated[language]}:</span>
                            <time>2025-12-01</time>
                        </div>
                    </div>

                    {/* Content */}
                    {loading ? (
                        <div className="flex items-center justify-center py-12">
                            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
                        </div>
                    ) : (
                        <div className="prose prose-sm sm:prose-base lg:prose-lg max-w-none
              prose-headings:font-bold prose-headings:text-gray-900 prose-headings:mt-8 prose-headings:mb-4
              prose-h1:text-3xl prose-h1:mt-0
              prose-h2:text-2xl prose-h2:border-b prose-h2:border-gray-200 prose-h2:pb-2
              prose-h3:text-xl
              prose-p:text-gray-700 prose-p:leading-relaxed prose-p:mb-4 prose-p:text-justify
              prose-a:text-blue-600 prose-a:no-underline hover:prose-a:underline
              prose-strong:text-gray-900 prose-strong:font-semibold
              prose-ul:my-4 prose-ul:list-disc prose-ul:pl-6
              prose-ol:my-4 prose-ol:list-decimal prose-ol:pl-6
              prose-li:my-2 prose-li:text-gray-700">
                            <ReactMarkdown
                                components={{
                                    p: ({node, ...props}) => <p className="mb-4" {...props} />,
                                    h1: ({node, ...props}) => <h1 className="mb-6 mt-0" {...props} />,
                                    h2: ({node, ...props}) => <h2 className="mb-4 mt-8" {...props} />,
                                    h3: ({node, ...props}) => <h3 className="mb-3 mt-6" {...props} />,
                                    ul: ({node, ...props}) => <ul className="my-4 space-y-2" {...props} />,
                                    ol: ({node, ...props}) => <ol className="my-4 space-y-2" {...props} />,
                                }}
                            >
                                {content}
                            </ReactMarkdown>
                        </div>
                    )}
                </article>

                {/* Footer */}
                <footer className="mt-8 sm:mt-12 text-center text-xs sm:text-sm text-gray-500">
                    <p>© 2024 Social App. All rights reserved.</p>
                </footer>
            </main>

            {/* Click outside to close language menu */}
            {showLangMenu && (
                <div
                    className="fixed inset-0 z-40"
                    onClick={() => setShowLangMenu(false)}
                />
            )}
        </div>
    );
};

export default LegalDocuments;