// DashboardView Component
// Home dashboard with stats and quick actions

function DashboardView({ token, t, settings, updateSettings, updateMultipleSettings, setActiveTab, setActionParams }) {
    const [stats, setStats] = useState(null);
    const [loading, setLoading] = useState(true);
    const [quickActions, setQuickActions] = useState(() => {
        const saved = localStorage.getItem('quickActions');
        return saved ? JSON.parse(saved) : [];
    });

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

    const fetchDashboard = async () => {
        try {
            const response = await fetch(API_URL + '/dashboard', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setStats(data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

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

    if (loading) return <div className="loading">{t('common.loading') || "Loading your dashboard..."}</div>;

    return (
        <div style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
            <DailyContentBanner t={t} settings={settings} updateMultipleSettings={updateMultipleSettings} />
            <h2 className="page-title">{t('common.welcome') || (stats?.greeting || 'Welcome')}!</h2>

            <div className="stats-grid">
                <div className="stat-card">
                    <div className="stat-value">{stats?.total_notes || 0}</div>
                    <div className="stat-label">{t('dashboard.totalNotes')}</div>
                </div>

                <div className="stat-card">
                    <div className="stat-value">{stats?.active_goals || 0}</div>
                    <div className="stat-label">{t('dashboard.activeGoals')}</div>
                </div>
            </div>

            <div className="card">
                <h3 style={{ marginBottom: '16px', fontSize: '18px', fontWeight: '600' }}>{t('dashboard.quickActions')}</h3>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: '12px' }}>
                    {/* Default Quick Actions */}
                    <button
                        onClick={() => { setActiveTab('notes'); setActionParams({ action: 'create' }); }}
                        className="btn btn-primary"
                        style={{
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            gap: '8px',
                            padding: '16px',
                            minHeight: '100px',
                            justifyContent: 'center',
                            position: 'relative'
                        }}
                    >
                        <span style={{ fontSize: '28px' }}>📝</span>
                        <span style={{ fontSize: '14px' }}>{t('dashboard.createNote')}</span>
                    </button>

                    <button
                        className="btn btn-secondary"
                        style={{
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            gap: '8px',
                            padding: '16px',
                            minHeight: '100px',
                            justifyContent: 'center',
                            position: 'relative'
                        }}
                    >
                        <span style={{ fontSize: '28px' }}>❓</span>
                        <span style={{ fontSize: '14px' }}>{t('dashboard.ask')}</span>
                    </button>

                    {/* User-added Tools Quick Actions */}
                    {quickActions.map(tool => (
                        <div
                            key={tool.id}
                            style={{
                                position: 'relative',
                                cursor: 'pointer',
                                padding: '16px',
                                textAlign: 'center',
                                border: '2px solid var(--primary-light)',
                                background: 'var(--card-bg)',
                                borderRadius: '12px',
                                transition: 'all 0.2s',
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                justifyContent: 'center',
                                gap: '8px',
                                minHeight: '100px'
                            }}
                            onClick={() => {
                                setActiveTab('tools');
                                setTimeout(() => {
                                    setActionParams({ openTool: tool.id });
                                }, 100);
                            }}
                            onMouseEnter={(e) => {
                                e.currentTarget.style.transform = 'translateY(-2px)';
                                e.currentTarget.style.borderColor = 'var(--primary)';
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.transform = 'translateY(0)';
                                e.currentTarget.style.borderColor = 'var(--primary-light)';
                            }}
                        >
                            {/* Remove button */}
                            <button
                                onClick={(e) => {
                                    e.stopPropagation();
                                    removeQuickAction(tool.id);
                                }}
                                style={{
                                    position: 'absolute',
                                    top: '4px',
                                    right: '4px',
                                    background: 'var(--danger)',
                                    color: 'white',
                                    border: 'none',
                                    borderRadius: '50%',
                                    width: '20px',
                                    height: '20px',
                                    cursor: 'pointer',
                                    fontSize: '12px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    opacity: 0.8,
                                    transition: 'opacity 0.2s'
                                }}
                                onMouseEnter={(e) => {
                                    e.target.style.opacity = '1';
                                }}
                                onMouseLeave={(e) => {
                                    e.target.style.opacity = '0.8';
                                }}
                                title="Remove from Quick Actions"
                            >
                                ×
                            </button>

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

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