function ToolsView({ token, t, actionParams }) {
    const [activeTool, setActiveTool] = useState(null);
    const [activeCategory, setActiveCategory] = useState('all');
    const [recentlyUsed, setRecentlyUsed] = useState(() => {
        const saved = localStorage.getItem('recentlyUsedTools');
        return saved ? JSON.parse(saved) : [];
    });

    // Quick Actions state
    const [quickActions, setQuickActions] = useState(() => {
        const saved = localStorage.getItem('quickActions');
        return saved ? JSON.parse(saved) : [];
    });

    const [openMenuId, setOpenMenuId] = useState(null);

    // Handle opening tool from Dashboard Quick Actions
    React.useEffect(() => {
        if (actionParams?.openTool) {
            setActiveTool(actionParams.openTool);
        }
    }, [actionParams]);

    const toolCategories = [
        {
            id: 'calculators',
            name: t.calculators || 'Calculators',
            tools: [
                { id: 'basic-calc', name: t.basic_calculator || 'Basic Calculator', icon: '➕', component: BasicCalculator },
                { id: 'scientific-calc', name: t.scientific_calculator || 'Scientific Calculator', icon: '🔬', component: ScientificCalculator },
                { id: 'bmi-calc', name: t.bmi_calculator || 'BMI Calculator', icon: '⚖️', component: BMICalculator },
                { id: 'age-calc', name: t.age_calculator || 'Age Calculator', icon: '🎂', component: AgeCalculator },
                { id: 'discount-calc', name: t.discount_calculator || 'Discount Calculator', icon: '🏷️', component: DiscountCalculator },
                { id: 'gst-calc', name: t.gst_calculator || 'GST Calculator', icon: '🧾', component: GSTCalculator },
                { id: 'investment-calc', name: t.investment_calculator || 'Investment Calculator', icon: '💹', component: InvestmentCalculator },
                { id: 'loan-calc', name: t.loan_emi_calculator || 'Loan EMI Calculator', icon: '🏦', component: LoanCalculator },
                { id: 'currency-conv', name: t.currency_converter || 'Currency Converter', icon: '💱', component: CurrencyConverter },
            ]
        },
        {
            id: 'converters',
            name: t.converters || 'Converters',
            tools: [
                { id: 'temp-conv', name: t.temperature || 'Temperature', icon: '🌡️', component: TemperatureConverter },
                { id: 'length-conv', name: 'Length', icon: '📏', component: LengthConverter },
                { id: 'mass-conv', name: t.mass_weight || 'Mass/Weight', icon: '⚖️', component: MassConverter },
                { id: 'data-conv', name: t.data_size || 'Data Size', icon: '💾', component: DataConverter },
                { id: 'speed-conv', name: t.speed || 'Speed', icon: '🚀', component: SpeedConverter },
                { id: 'numeric-conv', name: t.number_systems || 'Number Systems', icon: '🔢', component: NumericConverter },
            ]
        },
        {
            id: 'daily',
            name: 'Daily Features',
            tools: [
                { id: 'daily-word', name: 'Daily Word', icon: '📖', component: DailyWord },
                { id: 'daily-quote', name: 'Daily Quote', icon: '💭', component: DailyQuote },
            ]
        },
        {
            id: 'advanced',
            name: t.advanced_tools || 'Advanced Tools',
            tools: [
                { id: 'graph-2d', name: t.graph_2d || '2D Graph Plotter', icon: '📈', component: Graph2DPlotter },
                { id: 'graph-3d', name: t.graph_3d || '3D Graph Plotter', icon: '📊', component: Graph3DPlotter },
                { id: 'shape-pack', name: t.shape_packing || 'Shape Packing', icon: '📦', component: ShapePackingCalculator },
            ]
        }
    ];

    const trackToolUsage = (toolId) => {
        const tool = toolCategories.flatMap(cat => cat.tools).find(tl => tl.id === toolId);
        if (!tool) return;

        const filtered = recentlyUsed.filter(tl => tl.id !== toolId);
        const updated = [{ ...tool, timestamp: Date.now() }, ...filtered].slice(0, 6);
        setRecentlyUsed(updated);
        localStorage.setItem('recentlyUsedTools', JSON.stringify(updated));
        setActiveTool(toolId);
    };

    // Quick Actions functions
    const isInQuickActions = (toolId) => {
        return quickActions.some(qa => qa.id === toolId);
    };

    const addToQuickActions = (tool, categoryId) => {
        const toolData = { ...tool, categoryId };
        const updated = [...quickActions, toolData];
        setQuickActions(updated);
        localStorage.setItem('quickActions', JSON.stringify(updated));
        setOpenMenuId(null);
    };

    const removeFromQuickActions = (toolId) => {
        const updated = quickActions.filter(qa => qa.id !== toolId);
        setQuickActions(updated);
        localStorage.setItem('quickActions', JSON.stringify(updated));
        setOpenMenuId(null);
    };

    const toggleMenu = (toolId, e) => {
        e.stopPropagation();
        setOpenMenuId(openMenuId === toolId ? null : toolId);
    };

    // Close menu when clicking outside
    React.useEffect(() => {
        const handleClickOutside = () => setOpenMenuId(null);
        document.addEventListener('click', handleClickOutside);
        return () => document.removeEventListener('click', handleClickOutside);
    }, []);

    if (activeTool) {
        const tool = toolCategories.flatMap(cat => cat.tools).find(tl => tl.id === activeTool);
        const ToolComponent = tool?.component;

        return (
            <div style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
                <button className="btn btn-secondary mb-4" onClick={() => setActiveTool(null)}>
                    ← {t('tools.backToTools') || "Back to Tools"}
                </button>
                {ToolComponent && <ToolComponent token={token} t={t} />}
            </div>
        );
    }

    return (
        <div style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
            <h2 className="page-title">Tools & Utilities 🔧</h2>
            <p style={{ color: 'var(--text-secondary)', marginBottom: '24px' }}>
                Comprehensive suite of calculators, converters, and advanced tools for students, researchers, and engineers.
            </p>

            {/* Recently Used Section */}
            {recentlyUsed.length > 0 && (
                <div style={{ marginBottom: '32px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                        <h3 style={{ fontSize: '20px', fontWeight: '600', margin: 0, color: 'var(--text-primary)' }}>
                            🕒 Recently Used
                        </h3>
                        <button
                            onClick={() => {
                                setRecentlyUsed([]);
                                localStorage.removeItem('recentlyUsedTools');
                            }}
                            style={{
                                padding: '8px 16px',
                                border: '1px solid var(--border-color)',
                                background: 'var(--bg-secondary)',
                                borderRadius: '6px',
                                cursor: 'pointer',
                                fontSize: '13px',
                                color: 'var(--text-secondary)',
                                fontWeight: '500',
                                transition: 'all 0.2s'
                            }}
                            onMouseEnter={(e) => {
                                e.target.style.background = 'var(--danger-light)';
                                e.target.style.color = 'var(--danger)';
                                e.target.style.borderColor = 'var(--danger)';
                            }}
                            onMouseLeave={(e) => {
                                e.target.style.background = 'var(--bg-secondary)';
                                e.target.style.color = 'var(--text-secondary)';
                                e.target.style.borderColor = 'var(--border-color)';
                            }}
                        >
                            Clear
                        </button>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: '12px' }}>
                        {recentlyUsed.map(tool => (
                            <div
                                key={tool.id}
                                onClick={() => trackToolUsage(tool.id)}
                                className="card"
                                style={{
                                    cursor: 'pointer',
                                    padding: '20px',
                                    textAlign: 'center',
                                    transition: 'all 0.2s',
                                    position: 'relative',
                                    border: '2px solid var(--primary-light)'
                                }}
                            >
                                <div style={{ fontSize: '32px', marginBottom: '8px' }}>{tool.icon}</div>
                                <div style={{ fontSize: '14px', fontWeight: '500', color: 'var(--text-primary)' }}>{tool.name}</div>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {toolCategories.map(category => (
                <div key={category.id} style={{ marginBottom: '32px' }}>
                    <h3 style={{ fontSize: '20px', fontWeight: '600', marginBottom: '16px', color: 'var(--text-primary)' }}>
                        {category.name}
                    </h3>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: '12px' }}>
                        {category.tools.map(tool => (
                            <div
                                key={tool.id}
                                className="card"
                                style={{
                                    cursor: 'pointer',
                                    padding: '20px',
                                    textAlign: 'center',
                                    transition: 'all 0.2s',
                                    position: 'relative'
                                }}
                                onClick={() => trackToolUsage(tool.id)}
                            >
                                {/* 3-dot menu button */}
                                <button
                                    onClick={(e) => toggleMenu(tool.id, e)}
                                    style={{
                                        position: 'absolute',
                                        top: '8px',
                                        right: '8px',
                                        background: 'var(--bg-secondary)',
                                        border: '1px solid var(--border-color)',
                                        borderRadius: '6px',
                                        width: '28px',
                                        height: '28px',
                                        cursor: 'pointer',
                                        fontSize: '18px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        color: 'var(--text-secondary)',
                                        transition: 'all 0.2s'
                                    }}
                                    onMouseEnter={(e) => {
                                        e.target.style.background = 'var(--bg-tertiary)';
                                        e.target.style.borderColor = 'var(--primary)';
                                    }}
                                    onMouseLeave={(e) => {
                                        e.target.style.background = 'var(--bg-secondary)';
                                        e.target.style.borderColor = 'var(--border-color)';
                                    }}
                                >
                                    ⋮
                                </button>

                                {/* Dropdown menu */}
                                {openMenuId === tool.id && (
                                    <div
                                        onClick={(e) => e.stopPropagation()}
                                        style={{
                                            position: 'absolute',
                                            top: '40px',
                                            right: '8px',
                                            background: 'var(--card-bg)',
                                            border: '1px solid var(--border-color)',
                                            borderRadius: '8px',
                                            boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                                            zIndex: 10,
                                            minWidth: '180px',
                                            overflow: 'hidden'
                                        }}
                                    >
                                        <button
                                            onClick={() => isInQuickActions(tool.id)
                                                ? removeFromQuickActions(tool.id)
                                                : addToQuickActions(tool, category.id)
                                            }
                                            style={{
                                                width: '100%',
                                                padding: '12px 16px',
                                                border: 'none',
                                                background: 'transparent',
                                                textAlign: 'left',
                                                cursor: 'pointer',
                                                fontSize: '14px',
                                                color: 'var(--text-primary)',
                                                transition: 'background 0.2s'
                                            }}
                                            onMouseEnter={(e) => e.target.style.background = 'var(--bg-secondary)'}
                                            onMouseLeave={(e) => e.target.style.background = 'transparent'}
                                        >
                                            {isInQuickActions(tool.id)
                                                ? '✓ Remove from Quick Actions'
                                                : '⚡ Add to Quick Actions'}
                                        </button>
                                    </div>
                                )}

                                <div style={{ fontSize: '32px', marginBottom: '8px' }}>{tool.icon}</div>
                                <div style={{ fontSize: '14px', fontWeight: '500', color: 'var(--text-primary)' }}>{tool.name}</div>
                            </div>
                        ))}
                    </div>
                </div>
            ))}
        </div>
    );
}

// Export to global scope
window.ToolsView = ToolsView;
