import { useState, useEffect, useRef, useMemo } from 'react'
import logo from './assets/logo.svg'
import {
    Box,
    Typography,
    Drawer,
    List,
    ListItem,
    ListItemButton,
    ListItemIcon,
    ListItemText,
    AppBar,
    Toolbar,
    IconButton,
    Divider,
    GlobalStyles,
    Tooltip,
    Container,
    Paper,
    Chip,
    Switch,
    FormControlLabel,
    Button,
    Snackbar,
    Alert,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    TextField,
    Select,
    MenuItem,
    FormControl,
    InputLabel,
    LinearProgress,
    Tabs,
    Tab,
    InputAdornment,
    CircularProgress,
    Stack,
    Grid,
    Avatar
} from '@mui/material'
import {
    Dashboard as DashboardIcon,
    Folder as ProjectIcon,
    Settings as SettingsIcon,
    Language as LanguageIcon,
    Storage as DbIcon,
    Dns as ServerIcon,
    Code as PhpIcon,
    PlayArrow as StartIcon,
    Stop as StopIcon,
    Delete as DeleteIcon,
    Download as DownloadIcon,
    CheckCircle as InstalledIcon,
    CloudDownload as AvailableIcon,
    Refresh as RefreshIcon,
    FolderOpen as FolderOpenIcon,
    Save as SaveIcon,
    LanguageOutlined as WebIcon,
    Terminal as TerminalIcon,
    Close as CloseIcon,
    ContentCopy as ContentCopyIcon,
    OpenInNew as OpenIcon,
    Edit as EditIcon,
    Folder as FolderIcon,
    Language as HostIcon,
    Launch as LaunchIcon,
    Handyman as ToolsIcon,
    Restore as ResetIcon
} from '@mui/icons-material'
import Swal from 'sweetalert2'
import { useTranslation } from 'react-i18next'
import { supportedLngs } from './i18n'
import MariaDbImportWizard from './components/MariaDbImportWizard'
import MariaDbExportWizard from './components/MariaDbExportWizard'
import NginxCodeEditor from './components/NginxCodeEditor'
import ApacheCodeEditor from './components/ApacheCodeEditor'
import PhpExtensionManager from './components/PhpExtensionManager'

declare global {
    interface Window {
        api: any
    }
}

const drawerWidth = 240

interface ServiceInfo {
    status: string;
    cpu?: number;
    memory?: number;
}

interface ServiceStatus {
    [key: string]: ServiceInfo;
}

interface AppSettings {
    nginxPort: string
    apachePort: string
    serverType: 'nginx' | 'apache'
    phpPort: string
    mariaDbPort: string
    mariaDbPorts?: Record<string, string>
    allowRemoteAccess: boolean
    language: string
}

function App(): JSX.Element {
    const { t, i18n } = useTranslation()
    const [status, setStatus] = useState<ServiceStatus>({
        nginx: { status: 'stopped' },
        apache: { status: 'stopped' },
        php: { status: 'stopped' },
        mariadb: { status: 'stopped' }
    })
    const [activeTab, setActiveTab] = useState('dashboard')
    const [settingsTab, setSettingsTab] = useState(0)
    const [dashboardTab, setDashboardTab] = useState(0)
    const [projects, setProjects] = useState<any[]>([])
    const [phpVersions, setPhpVersions] = useState<any[]>([])
    const [mariaDbVersions, setMariaDbVersions] = useState<any[]>([])
    const [nginxVersions, setNginxVersions] = useState<any[]>([])
    const [apacheVersions, setApacheVersions] = useState<any[]>([])
    const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false)
    const slugify = (text: string) => text.toLowerCase().trim().replace(/[^\w\s-]/g, '').replace(/[\s_-]+/g, '-').replace(/^-+|-+$/g, '');
    const [newProject, setNewProject] = useState<any>({ name: '', path: '', phpVersion: '', mariaDbVersion: '', host: 'localhost', serverType: 'nginx' })
    const [settings, setSettings] = useState<AppSettings>({
        nginxPort: '80',
        apachePort: '8080',
        serverType: 'nginx',
        phpPort: '9001',
        mariaDbPort: '3306',
        allowRemoteAccess: false,
        language: 'tr'
    })
    const [notification, setNotification] = useState<{ open: boolean, message: string, severity: 'success' | 'error' }>({
        open: false,
        message: '',
        severity: 'success'
    })

    // Log States
    const [logDialogOpen, setLogDialogOpen] = useState(false)
    const [selectedService, setSelectedService] = useState('')
    const [logs, setLogs] = useState<string[]>([])
    const [pmaInstalled, setPmaInstalled] = useState(false)
    const [pmaLoading, setPmaLoading] = useState(false)
    const [pmaProgress, setPmaProgress] = useState(0)
    const [isMariaDbWizardOpen, setIsMariaDbWizardOpen] = useState(false)
    const [isMariaDbExportWizardOpen, setIsMariaDbExportWizardOpen] = useState(false)
    const [isNginxConfigOpen, setIsNginxConfigOpen] = useState(false)
    const [nginxConfig, setNginxConfig] = useState('')
    const [isApacheConfigOpen, setIsApacheConfigOpen] = useState(false)
    const [apacheConfig, setApacheConfig] = useState('')
    const [isProjectNginxConfigOpen, setIsProjectNginxConfigOpen] = useState(false)
    const [projectNginxConfig, setProjectNginxConfig] = useState('')
    const [selectedProjectHost, setSelectedProjectHost] = useState('')
    const [isPhpExtensionsOpen, setIsPhpExtensionsOpen] = useState(false)
    const [selectedPhpVersion, setSelectedPhpVersion] = useState('')

    const parseNginxError = (message: string) => {
        const match = message.match(/in (.*):(\d+)/)
        if (!match) return null
        const filePath = match[1].replace(/\\/g, '/')
        const line = parseInt(match[2])
        const fileName = filePath.split('/').pop() || ''
        const isProjectConfig = filePath.includes('/generated_configs/projects/') || filePath.includes('/generated_configs/projects_apache/')
        const host = isProjectConfig ? fileName.replace('.conf', '') : null
        return { filePath, line, host }
    }

    const fetchStatus = async () => {
        if (window.api && window.api.getServiceStatus) {
            const currentStatus = await window.api.getServiceStatus()
            if (currentStatus) setStatus(currentStatus)
        }
    }

    const fetchSettings = async () => {
        if (window.api && window.api.getSettings) {
            const s = await window.api.getSettings()
            if (s) setSettings(s)
        }
    }

    const fetchProjects = async () => {
        if (window.api && window.api.getProjects) {
            const list = await window.api.getProjects()
            setProjects(list || [])
        }
    }

    const fetchPhpVersions = async () => {
        if (window.api && window.api.getPhpVersions) {
            const list = await window.api.getPhpVersions()
            setPhpVersions(list || [])
        }
    }

    const fetchMariaDbVersions = async () => {
        if (window.api && window.api.getMariaDbVersions) {
            const list = await window.api.getMariaDbVersions()
            setMariaDbVersions(list || [])
        }
    }

    const fetchNginxVersions = async () => {
        if (window.api && window.api.getNginxVersions) {
            const list = await window.api.getNginxVersions()
            setNginxVersions(list || [])
        }
    }

    const fetchApacheVersions = async () => {
        if (!window.api || !window.api.getApacheVersions) return
        const v = await window.api.getApacheVersions()
        setApacheVersions(v || [])
    }

    const fetchLogs = async (service: string) => {
        if (window.api && window.api.getServiceLogs) {
            const list = await window.api.getServiceLogs(service)
            setLogs(list || [])
        }
    }


    useEffect(() => {
        if (isProjectDialogOpen && !newProject.id) {
            const updates: Partial<typeof newProject> = {}
            if (!newProject.phpVersion && phpVersions.length > 0) {
                const installedPhp = phpVersions.find(v => v.status === 'installed')
                if (installedPhp) updates.phpVersion = installedPhp.version
            }
            if (!newProject.mariaDbVersion && mariaDbVersions.length > 0) {
                const installedMariaDb = mariaDbVersions.find(v => v.status === 'installed')
                if (installedMariaDb) updates.mariaDbVersion = installedMariaDb.version
            }
            if (Object.keys(updates).length > 0) {
                setNewProject(prev => ({ ...prev, ...updates }))
            }
        }
    }, [isProjectDialogOpen, phpVersions, mariaDbVersions])

    useEffect(() => {
        if (!window.api) return

        const fetchPmaStatus = async () => {
            if (window.api && window.api.pmaStatus) {
                const installed = await window.api.pmaStatus()
                setPmaInstalled(installed)
            }
        }

        fetchStatus()
        fetchProjects()
        fetchPhpVersions()
        fetchMariaDbVersions()
        fetchNginxVersions()
        fetchApacheVersions()
        fetchSettings()
        fetchPmaStatus()

        const removePhpListener = window.api.onBinaryProgress ? window.api.onBinaryProgress((data) => {
            if (!data) return
            const { id, progress } = data
            setPhpVersions(prev => prev.map(v => v.id === id ? { ...v, progress, status: progress === 100 ? 'installed' : 'downloading' } : v))
        }) : null

        const removeMariaDbListener = window.api.onMariaDbProgress ? window.api.onMariaDbProgress((data) => {
            if (!data) return
            const { id, progress } = data
            setMariaDbVersions(prev => prev.map(v => v.id === id ? { ...v, progress, status: progress === 100 ? 'installed' : 'downloading' } : v))
        }) : null

        const removeNginxListener = window.api.onNginxProgress ? window.api.onNginxProgress((data) => {
            if (!data) return
            const { id, progress } = data
            setNginxVersions(prev => prev.map(v => v.id === id ? { ...v, progress, status: progress === 100 ? 'installed' : 'downloading' } : v))
        }) : null

        const removeApacheListener = window.api.onApacheProgress ? window.api.onApacheProgress((data) => {
            if (!data) return
            const { id, progress } = data
            setApacheVersions(prev => prev.map(v => v.id === id ? { ...v, progress, status: progress === 100 ? 'installed' : 'downloading' } : v))
        }) : null

        const removePmaListener = window.api.onPmaProgress ? window.api.onPmaProgress((p: number) => {
            setPmaProgress(p)
        }) : null

        const interval = setInterval(() => {
            fetchStatus()
            // fetchProjects() // Reduced frequency for these
            // fetchPhpVersions()
            // fetchMariaDbVersions()
            // fetchNginxVersions()
        }, 3000)

        let logInterval: NodeJS.Timeout | null = null
        if (logDialogOpen && selectedService) {
            logInterval = setInterval(() => {
                fetchLogs(selectedService)
            }, 1000)
        }

        return () => {
            clearInterval(interval)
            if (logInterval) clearInterval(logInterval)
            if (typeof removePhpListener === 'function') removePhpListener()
            if (typeof removeMariaDbListener === 'function') removeMariaDbListener()
            if (typeof removeNginxListener === 'function') removeNginxListener()
            if (typeof removeApacheListener === 'function') removeApacheListener()
            if (typeof removePmaListener === 'function') removePmaListener()
        }
    }, [logDialogOpen, selectedService])

    useEffect(() => {
        if (logDialogOpen) {
            const end = document.getElementById('log-end')
            if (end) end.scrollIntoView({ behavior: 'smooth' })
        }
    }, [logs, logDialogOpen])

    const handleSelectPath = async () => {
        if (window.api && window.api.selectDirectory) {
            const pathStr = await window.api.selectDirectory()
            if (pathStr) {
                const folderName = pathStr.split(/[/\\]/).pop() || ''
                const slug = slugify(folderName)
                setNewProject(prev => ({ ...prev, path: pathStr, name: folderName, host: slug }))
            }
        }
    }

    const handleToggleService = async (service: string) => {
        if (!window.api) return

        const isStarting = ((status[service] as any)?.status || status[service] || 'stopped') === 'stopped'
        if (isStarting) {
            setStatus(prev => ({ ...prev, [service]: { status: 'starting' } }))
        }

        const result = ((status[service] as any)?.status || status[service] || 'stopped') === 'running'
            ? await window.api.stopService(service)
            : await window.api.startService(service)

        // Refresh status after operation
        fetchStatus()

        if (!result.success) {
            Swal.fire({
                title: t('common.error'),
                text: result.message,
                icon: 'error',
                confirmButtonText: t('common.ok'),
                background: '#1e1e1e',
                color: '#fff',
                confirmButtonColor: '#153E5E',
                customClass: {
                    popup: 'swal2-dark-popup'
                }
            })
        } else {
            setNotification({
                open: true,
                message: result.message,
                severity: 'success'
            })
        }
    }

    const handleOpenLogs = async (service: string) => {
        setSelectedService(service)
        setLogDialogOpen(true)
        await fetchLogs(service)
    }

    const handleResetData = async (service: string) => {
        const confirmResult = await Swal.fire({
            title: t('common.reset_confirm_title'),
            text: t('common.reset_confirm_text', { service }),
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: t('common.reset_btn'),
            cancelButtonText: t('common.cancel'),
            background: '#1e1e1e',
            color: '#fff',
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6'
        })

        if (confirmResult.isConfirmed) {
            const result = await window.api.invoke('services:reset-data', service)
            Swal.fire({
                title: result.success ? t('common.success') : t('common.error'),
                text: result.message,
                icon: result.success ? 'success' : 'error',
                background: '#1e1e1e',
                color: '#fff'
            })
            fetchStatus()
        }
    }

    const handleSaveSettings = async () => {
        if (window.api && window.api.saveSettings) {
            const result = await window.api.saveSettings(settings)
            if (result.success) {
                setNotification({ open: true, message: t('settings.saved'), severity: 'success' })
            }
        }
    }

    const handleLanguageChange = (event: any) => {
        const newLang = event.target.value
        i18n.changeLanguage(newLang)
        setSettings(prev => ({ ...prev, language: newLang }))
    }

    const handleStartAll = async () => {
        if (!window.api) return
        const criticalServices = ['nginx', 'apache']
        for (const s of criticalServices) {
            if (status[s]?.status === 'stopped') setStatus(prev => ({ ...prev, [s]: { status: 'starting' } }))
        }

        const phpToStart = phpVersions.filter(v => v.status === 'installed').map(v => `php:${v.version}`)
        for (const s of phpToStart) {
            if ((status[s]?.status || 'stopped') === 'stopped') setStatus(prev => ({ ...prev, [s]: { status: 'starting' } }))
        }

        const mariaDbToStart = mariaDbVersions.filter(v => v.status === 'installed').map(v => `mariadb:${v.version}`)
        for (const s of mariaDbToStart) {
            if ((status[s]?.status || 'stopped') === 'stopped') setStatus(prev => ({ ...prev, [s]: { status: 'starting' } }))
        }

        await Promise.all([
            ...criticalServices.filter(s => status[s]?.status !== 'running').map(s => window.api?.startService(s)),
            ...phpToStart.filter(s => (status[s]?.status || 'stopped') !== 'running').map(s => window.api?.startService(s)),
            ...mariaDbToStart.filter(s => (status[s]?.status || 'stopped') !== 'running').map(s => window.api?.startService(s))
        ])

        fetchStatus()
        setNotification({ open: true, message: t('dashboard.all_started'), severity: 'success' })
    }

    const handleStopAll = async () => {
        if (!window.api) return
        const criticalServices = ['nginx', 'apache']
        const phpToStop = Object.keys(status).filter(s => s.startsWith('php:') && (status[s]?.status === 'running' || status[s]?.status === 'starting'))
        const mariaDbToStop = Object.keys(status).filter(s => (s.startsWith('mariadb:') || s.startsWith('mysql:')) && (status[s]?.status === 'running' || status[s]?.status === 'starting'))

        await Promise.all([
            ...criticalServices.filter(s => status[s]?.status === 'running' || status[s]?.status === 'starting').map(s => window.api?.stopService(s)),
            ...phpToStop.map(s => window.api?.stopService(s)),
            ...mariaDbToStop.map(s => window.api?.stopService(s)),
            window.api?.stopService('mariadb') // Also stop default
        ])

        fetchStatus()
        setNotification({ open: true, message: t('dashboard.all_stopped'), severity: 'success' })
    }

    const formatMemory = (bytes?: number) => {
        if (!bytes) return ''
        const mb = bytes / (1024 * 1024)
        if (mb > 1024) return `${(mb / 1024).toFixed(1)} GB`
        return `${Math.round(mb)} MB`
    }

    const getStatusChip = (s: string | { status: string, cpu?: number, memory?: number }) => {
        const state = typeof s === 'string' ? s : s.status

        if (state === 'starting') {
            return <Chip label={t('common.starting')} color="warning" size="small" sx={{ fontWeight: 'bold' }} icon={<CircularProgress size={14} color="inherit" />} />
        }
        if (state === 'stopping') {
            return <Chip label={t('common.stopping')} color="warning" size="small" sx={{ fontWeight: 'bold' }} icon={<CircularProgress size={14} color="inherit" />} />
        }
        const color = state === 'running' ? 'success' : state === 'stopped' ? 'error' : 'warning'
        
        return <Chip label={t(`common.${state}`).toUpperCase()} color={color} size="small" sx={{ fontWeight: 'bold' }} />
    }

    const ResourceMonitor = ({ cpu, memory }: { cpu?: number; memory?: number }) => {
        if (cpu === undefined && memory === undefined) return null;

        const ramMB = memory ? Math.round(memory / (1024 * 1024)) : 0;
        const ramLimit = 1024; // 1GB scale for visual
        const cpuValue = cpu || 0;
        const ramPercent = Math.min((ramMB / ramLimit) * 100, 100);

        return (
            <Box sx={{ mt: 1.5, mb: 1 }}>
                <Box sx={{ mb: 1.5 }}>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                        <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.5)', fontSize: '0.7rem', fontWeight: 'bold' }}>CPU</Typography>
                        <Typography variant="caption" sx={{ color: 'primary.light', fontSize: '0.7rem', fontWeight: 'bold' }}>{cpuValue}%</Typography>
                    </Box>
                    <LinearProgress 
                        variant="determinate" 
                        value={cpuValue} 
                        sx={{ 
                            height: 4, 
                            borderRadius: 2, 
                            bgcolor: 'rgba(255,255,255,0.05)',
                            '.MuiLinearProgress-bar': {
                                borderRadius: 2,
                                backgroundImage: `linear-gradient(90deg, #33d9b2 ${cpuValue}%, #ff5252 100%)`,
                                bgcolor: 'transparent'
                            }
                        }} 
                    />
                </Box>
                <Box>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                        <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.5)', fontSize: '0.7rem', fontWeight: 'bold' }}>RAM</Typography>
                        <Typography variant="caption" sx={{ color: 'secondary.light', fontSize: '0.7rem', fontWeight: 'bold' }}>{formatMemory(memory as number)}</Typography>
                    </Box>
                    <LinearProgress 
                        variant="determinate" 
                        value={ramPercent} 
                        sx={{ 
                            height: 4, 
                            borderRadius: 2, 
                            bgcolor: 'rgba(255,255,255,0.05)',
                            '.MuiLinearProgress-bar': {
                                borderRadius: 2,
                                bgcolor: 'secondary.main'
                            }
                        }} 
                    />
                </Box>
            </Box>
        );
    };

    const ProjectResourceMonitor = ({ serverStats, phpStats, serverType }: { serverStats?: ServiceInfo; phpStats?: ServiceInfo; serverType: string }) => {
        const hasServerStat = serverStats?.cpu !== undefined || serverStats?.memory !== undefined;
        const hasPhpStat = phpStats?.cpu !== undefined || phpStats?.memory !== undefined;

        if (!hasServerStat && !hasPhpStat) return null;

        const renderMiniStats = (stats?: ServiceInfo, label: string = 'Service') => {
            if (!stats) return null;
            const cpu = stats.cpu || 0;
            const memory = stats.memory || 0;
            const ramMB = Math.round(memory / (1024 * 1024));
            const ramPercent = Math.min((ramMB / 1024) * 100, 100);

            return (
                <Box sx={{ flex: 1 }}>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                        <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.4)', fontSize: '0.65rem', fontWeight: 700 }}>{label.toUpperCase()}</Typography>
                        <Box sx={{ display: 'flex', gap: 1 }}>
                            <Typography variant="caption" sx={{ color: 'primary.light', fontSize: '0.65rem', fontWeight: 700 }}>{cpu}%</Typography>
                            <Typography variant="caption" sx={{ color: 'secondary.light', fontSize: '0.65rem', fontWeight: 700 }}>{formatMemory(memory)}</Typography>
                        </Box>
                    </Box>
                    <Box sx={{ display: 'flex', gap: '2px' }}>
                        <LinearProgress 
                            variant="determinate" 
                            value={cpu} 
                            sx={{ 
                                height: 3, 
                                borderRadius: 1, 
                                flex: 1,
                                bgcolor: 'rgba(255,255,255,0.05)',
                                '.MuiLinearProgress-bar': { borderRadius: 1, backgroundImage: `linear-gradient(90deg, #33d9b2 ${cpu}%, #ff5252 100%)`, bgcolor: 'transparent' }
                            }} 
                        />
                        <LinearProgress 
                            variant="determinate" 
                            value={ramPercent} 
                            sx={{ 
                                height: 3, 
                                borderRadius: 1, 
                                flex: 1,
                                bgcolor: 'rgba(255,255,255,0.05)',
                                '.MuiLinearProgress-bar': { borderRadius: 1, bgcolor: 'secondary.main' }
                            }} 
                        />
                    </Box>
                </Box>
            );
        };

        return (
            <Box sx={{ mt: 1.5, display: 'flex', gap: 2 }}>
                {renderMiniStats(serverStats, serverType)}
                {renderMiniStats(phpStats, 'PHP')}
            </Box>
        );
    };

    const handleAddProject = async () => {
        if (!window.api) return
        if (newProject.id) {
            await window.api.updateProject(newProject)
        } else {
            await window.api.addProject(newProject)
        }
        setIsProjectDialogOpen(false)
        setNewProject({ name: '', path: '', phpVersion: '', mariaDbVersion: '', host: 'localhost' })
        setNotification({ open: true, message: newProject.id ? t('projects.updated') : t('projects.added'), severity: 'success' })
        fetchProjects()
    }

    const handleRemoveProject = async (id: string) => {
        if (!window.api) return
        const result = await Swal.fire({
            title: t('common.are_you_sure'),
            text: t('projects.delete_confirm'),
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ff4444',
            cancelButtonColor: '#3085d6',
            confirmButtonText: t('common.yes_delete'),
            cancelButtonText: t('common.cancel'),
            background: '#1e1e1e',
            color: '#fff'
        })

        if (result.isConfirmed) {
            await window.api.removeProject(id)
            setNotification({ open: true, message: t('projects.deleted'), severity: 'success' })
            fetchProjects()
        }
    }

    const handleOpenNginxConfig = async () => {
        if (window.api && window.api.invoke) {
            const config = await window.api.invoke('nginx:config:get')
            setNginxConfig(config)
            setIsNginxConfigOpen(true)
        }
    }

    const handleSaveNginxConfig = async () => {
        if (window.api && window.api.invoke) {
            const result = await window.api.invoke('nginx:config:save', nginxConfig)
            if (result.success) {
                Swal.fire({
                    title: t('common.success'),
                    text: t('server.nginx.config_saved'),
                    icon: 'success',
                    background: '#1e1e1e',
                    color: '#fff',
                    confirmButtonColor: '#153E5E',
                    customClass: { popup: 'swal2-dark-popup' }
                })
                setIsNginxConfigOpen(false)
            }
        }
    }

    const handleOpenApacheConfig = async () => {
        if (window.api && window.api.invoke) {
            const config = await window.api.invoke('apache:config:get')
            setApacheConfig(config)
            setIsApacheConfigOpen(true)
        }
    }

    const handleSaveApacheConfig = async () => {
        if (window.api && window.api.invoke) {
            const result = await window.api.invoke('apache:config:save', apacheConfig)
            if (result.success) {
                Swal.fire({
                    title: t('common.success'),
                    text: t('server.apache.config_saved'),
                    icon: 'success',
                    background: '#1e1e1e',
                    color: '#fff',
                    confirmButtonColor: '#153E5E',
                    customClass: { popup: 'swal2-dark-popup' }
                })
                setIsApacheConfigOpen(false)
            }
        }
    }

    const handleTestApacheConfig = async () => {
        if (window.api && window.api.invoke) {
            const result = await window.api.invoke('apache:config:test')
            const formattedMessage = result.message
                .replace(/failed/g, '<span style="color: #ff5252;">failed</span>')
                .replace(/successful/g, '<span style="color: #33d9b2;">successful</span>')

            Swal.fire({
                title: result.success ? 'Başarılı' : 'Yapılandırma Hatası',
                html: `
                    <div class="nginx-error-container">
                        ${formattedMessage}
                    </div>
                `,
                icon: result.success ? 'success' : 'error',
                background: '#1e1e1e',
                color: '#fff',
                width: '600px'
            })
        }
    }

    const handleTestNginxConfig = async () => {
        if (window.api && window.api.invoke) {
            const result = await window.api.invoke('nginx:config:test')
            const errorInfo = !result.success ? parseNginxError(result.message) : null
            const formattedMessage = result.message
                .replace(/\[emerg\]/g, '<span style="color: #ff5252; font-weight: bold;">[emerg]</span>')
                .replace(/\[warn\]/g, '<span style="color: #ffb142; font-weight: bold;">[warn]</span>')
                .replace(/failed/g, '<span style="color: #ff5252;">failed</span>')
                .replace(/successful/g, '<span style="color: #33d9b2;">successful</span>')

            Swal.fire({
                title: result.success ? 'Başarılı' : 'Yapılandırma Hatası',
                html: `
                    <div class="nginx-error-container">
                        ${formattedMessage}
                    </div>
                    ${errorInfo?.host ? `
                        <div style="margin-top: 15px; text-align: center;">
                            <p style="font-size: 0.9rem; color: #ffb142;">
                                <b>{t('common.error')}:</b> ${errorInfo.host} (Satır: ${errorInfo.line})
                            </p>
                        </div>
                    ` : ''}
                `,
                icon: result.success ? 'success' : 'error',
                showCancelButton: !result.success && !!errorInfo?.host,
                confirmButtonText: !result.success && errorInfo?.host ? t('common.go_to_fix') : t('common.ok'),
                cancelButtonText: t('common.close'),
                background: '#1e1e1e',
                color: '#fff',
                width: '600px'
            }).then((alertResult) => {
                if (alertResult.isConfirmed && !result.success && errorInfo?.host) {
                    setIsNginxConfigOpen(false) // Close global if open
                    handleOpenProjectNginxConfig(errorInfo.host)
                }
            })
        }
    }

    const handleOpenProjectNginxConfig = async (host: string) => {
        if (window.api && window.api.invoke) {
            const config = await window.api.invoke('project:nginx:get', host)
            setProjectNginxConfig(config)
            setSelectedProjectHost(host)
            setIsProjectNginxConfigOpen(true)
        }
    }

    const handleSaveProjectNginxConfig = async () => {
        if (window.api && window.api.invoke) {
            const result = await window.api.invoke('project:nginx:save', selectedProjectHost, projectNginxConfig)
            if (result.success) {
                Swal.fire({
                    title: t('common.success'),
                    text: t('server.nginx.config_saved'),
                    icon: 'success',
                    background: '#1e1e1e',
                    color: '#fff',
                    confirmButtonColor: '#153E5E',
                    customClass: { popup: 'swal2-dark-popup' }
                })
                setIsProjectNginxConfigOpen(false)
            }
        }
    }

    const handleDownloadPhp = async (id: string) => {
        if (!window.api) return
        const result = await window.api.downloadPhpVersion(id)
        setNotification({
            open: true,
            message: result.message,
            severity: result.success ? 'success' : 'error'
        })
        fetchPhpVersions()
    }

    const handleDownloadMariaDb = async (id: string) => {
        if (!window.api) return
        const result = await window.api.downloadMariaDbVersion(id)
        setNotification({
            open: true,
            message: result.message,
            severity: result.success ? 'success' : 'error'
        })
        fetchMariaDbVersions()
    }

    const handleDownloadNginx = async (id: string) => {
        if (!window.api) return
        const result = await window.api.downloadNginxVersion(id)
        setNotification({
            open: true,
            message: result.message,
            severity: result.success ? 'success' : 'error'
        })
        fetchNginxVersions()
    }

    const handleDownloadApache = async (id: string) => {
        if (!window.api) return
        const result = await window.api.downloadApacheVersion(id)
        setNotification({
            open: true,
            message: result.message,
            severity: result.success ? 'success' : 'error'
        })
        fetchApacheVersions()
    }

    const handleSetupPma = async () => {
        if (!window.api) return
        setPmaLoading(true)
        setPmaProgress(0)
        try {
            const success = await window.api.pmaSetup()
            if (success) {
                setNotification({ open: true, message: t('server.phpmyadmin.installed_success'), severity: 'success' })
            } else {
                setNotification({ open: true, message: t('server.phpmyadmin.installed_error'), severity: 'error' })
            }
        } finally {
            setPmaLoading(false)
        }
    }

    const handleOpenPma = () => {
        const port = settings.serverType === 'apache' ? settings.apachePort : settings.nginxPort
        window.open(`http://localhost:${port}/phpmyadmin`, '_blank')
    }

    const handleOpenPhpExtensions = (version: string) => {
        setSelectedPhpVersion(version)
        setIsPhpExtensionsOpen(true)
    }

    const installedPhpVersions = phpVersions.filter(v => v.status === 'installed')

    return (
        <>
            <GlobalStyles styles={{
                '.swal2-container': {
                    zIndex: '9999 !important'
                },
                '.nginx-error-container': {
                    textAlign: 'left !important',
                    fontFamily: 'monospace !important',
                    fontSize: '0.8rem !important',
                    whiteSpace: 'pre-wrap !important',
                    backgroundColor: 'rgba(0,0,0,0.2) !important',
                    padding: '10px !important',
                    borderRadius: '5px !important',
                    border: '1px solid rgba(255,255,255,0.1) !important'
                }
            }} />
            <Box sx={{ display: 'flex', minHeight: '100vh', backgroundImage: 'radial-gradient(circle at 50% 0%, #153E5E 0%, #121212 100%)', bgcolor: 'transparent' }}>
                <AppBar
                    position="fixed"
                    sx={{
                        width: { sm: `calc(100% - ${drawerWidth}px)` },
                        ml: { sm: `${drawerWidth}px` },
                        zIndex: (theme) => theme.zIndex.drawer - 1,
                        bgcolor: 'rgba(21, 62, 94, 0.85)',
                        backdropFilter: 'blur(10px)'
                    }}
                >
                    <Toolbar sx={{ gap: 1 }}>
                        <Box sx={{ flexGrow: 1 }} />
                        <Tooltip title={t('dashboard.start_all')}>
                            <IconButton color="inherit" onClick={handleStartAll} sx={{ '&:hover': { color: 'success.main' } }}>
                                <StartIcon />
                            </IconButton>
                        </Tooltip>
                        <Tooltip title={t('dashboard.stop_all')}>
                            <IconButton color="inherit" onClick={handleStopAll} sx={{ '&:hover': { color: 'error.main' } }}>
                                <StopIcon />
                            </IconButton>
                        </Tooltip>
                        <Divider orientation="vertical" flexItem sx={{ mx: 1, borderColor: 'rgba(255,255,255,0.1)' }} />
                        <FormControl size="small" variant="outlined" sx={{ minWidth: 80 }}>
                            <Select
                                value={i18n.language}
                                onChange={handleLanguageChange}
                                displayEmpty
                                IconComponent={LanguageIcon}
                                sx={{
                                    color: 'white',
                                    height: '35px',
                                    fontSize: '0.8rem',
                                    '.MuiOutlinedInput-notchedOutline': { borderColor: 'rgba(255,255,255,0.2)' },
                                    '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: 'rgba(255,255,255,0.4)' },
                                    '&.Mui-focused .MuiOutlinedInput-notchedOutline': { borderColor: 'primary.main' },
                                    '.MuiSelect-icon': { color: 'white' }
                                }}
                            >
                                {supportedLngs.map(lang => (
                                    <MenuItem key={lang} value={lang}>
                                        {lang.toUpperCase()}
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                        <IconButton color="inherit" onClick={() => setActiveTab('settings')} sx={{ ml: 1 }}>
                            <SettingsIcon />
                        </IconButton>
                    </Toolbar>
                </AppBar>

                <Drawer
                    variant="permanent"
                    sx={{
                        width: drawerWidth,
                        flexShrink: 0,
                        [`& .MuiDrawer-paper`]: { width: drawerWidth, boxSizing: 'border-box', bgcolor: 'rgba(18, 18, 18, 0.95)', borderRight: '1px solid rgba(255, 255, 255, 0.05)' },
                    }}
                >
                    <Box sx={{ p: 2, display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '120px' }}>
                        <img src={logo} alt="Logo" style={{ width: '90%', maxWidth: '210px', objectFit: 'contain' }} />
                    </Box>
                    <Divider sx={{ opacity: 0.1 }} />
                    <Box sx={{ overflow: 'auto' }}>
                        <List>
                            <ListItem disablePadding>
                                <ListItemButton selected={activeTab === 'dashboard'} onClick={() => setActiveTab('dashboard')}>
                                    <ListItemIcon><DashboardIcon color={activeTab === 'dashboard' ? 'primary' : 'inherit'} /></ListItemIcon>
                                    <ListItemText primary={t('dashboard.title')} />
                                </ListItemButton>
                            </ListItem>
                            <ListItem disablePadding>
                                <ListItemButton selected={activeTab === 'projects'} onClick={() => setActiveTab('projects')}>
                                    <ListItemIcon><ProjectIcon color={activeTab === 'projects' ? 'primary' : 'inherit'} /></ListItemIcon>
                                    <ListItemText primary={t('projects.title')} />
                                </ListItemButton>
                            </ListItem>
                            <ListItem disablePadding>
                                <ListItemButton selected={activeTab === 'tools'} onClick={() => setActiveTab('tools')}>
                                    <ListItemIcon><ToolsIcon color={activeTab === 'tools' ? 'primary' : 'inherit'} /></ListItemIcon>
                                    <ListItemText primary={t('common.tools')} />
                                </ListItemButton>
                            </ListItem>
                        </List>
                        <Divider />
                        <List>
                            <ListItem disablePadding>
                                <ListItemButton selected={activeTab === 'settings'} onClick={() => setActiveTab('settings')}>
                                    <ListItemIcon><SettingsIcon color={activeTab === 'settings' ? 'primary' : 'inherit'} /></ListItemIcon>
                                    <ListItemText primary={t('settings.general')} />
                                </ListItemButton>
                            </ListItem>
                        </List>
                    </Box>
                </Drawer>

                <Box component="main" sx={{ flexGrow: 1, p: 3 }}>
                    <Toolbar />
                    <Container maxWidth="md">
                        {activeTab === 'settings' && (
                            <Box>


                                <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
                                    <Tabs value={settingsTab} onChange={(_e, v) => setSettingsTab(v)} textColor="primary" indicatorColor="primary" variant="scrollable" scrollButtons="auto">
                                        <Tab label="PHP" icon={<PhpIcon />} iconPosition="start" />
                                        <Tab label="MariaDB" icon={<DbIcon />} iconPosition="start" />
                                        <Tab label="Nginx" icon={<WebIcon />} iconPosition="start" />
                                        <Tab label="Apache" icon={<ServerIcon />} iconPosition="start" />
                                        <Tab label={t('settings.server_settings')} icon={<ServerIcon />} iconPosition="start" />
                                    </Tabs>
                                </Box>

                                {settingsTab === 0 && (
                                    <Paper sx={{ bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2 }}>
                                        <Box sx={{ p: 2, borderBottom: '1px solid rgba(255, 255, 255, 0.05)' }}>
                                            <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>{t('settings.php_versions')}</Typography>
                                            <Typography variant="body2" color="text.secondary">{t('settings.php_versions_desc')}</Typography>
                                        </Box>
                                        <List sx={{ maxHeight: 500, overflow: 'auto' }}>
                                            {phpVersions.length === 0 && (
                                                <ListItem><ListItemText primary={t('common.loading')} /></ListItem>
                                            )}
                                            {phpVersions.map((v) => (
                                                <ListItem key={v.id} sx={{ py: 2 }}>
                                                    <ListItemIcon>
                                                        {v.status === 'installed' ? <InstalledIcon color="success" /> : <AvailableIcon color="action" />}
                                                    </ListItemIcon>
                                                    <ListItemText
                                                        primary={`PHP ${v.version}`}
                                                        secondary={v.status === 'downloading' ? `${t('common.loading')} %${Math.round(v.progress)}` : v.status === 'installed' ? t('php.extensions.active') : t('common.available')}
                                                        sx={{ flexGrow: 1 }}
                                                    />
                                                    <Box sx={{ minWidth: 120, textAlign: 'right' }}>
                                                        {v.status === 'available' && (
                                                            <Button variant="outlined" size="small" startIcon={<DownloadIcon />} onClick={() => handleDownloadPhp(v.id)}>
                                                                {t('common.download')}
                                                            </Button>
                                                        )}
                                                        {v.status === 'downloading' && (
                                                            <Box sx={{ width: '100%', mt: 1 }}>
                                                                <LinearProgress variant="determinate" value={v.progress} sx={{ height: 8, borderRadius: 5 }} />
                                                            </Box>
                                                        )}
                                                        {v.status === 'installed' && (
                                                            <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                                                                <Button variant="outlined" size="small" startIcon={<ToolsIcon />} onClick={() => handleOpenPhpExtensions(v.version)}>
                                                                    {t('php.extensions.title', { version: '' }).replace('  ', ' ')}
                                                                </Button>
                                                                <Chip label={t('common.ok').toUpperCase()} color="success" variant="outlined" size="small" />
                                                            </Box>
                                                        )}
                                                    </Box>
                                                </ListItem>
                                            ))}
                                        </List>
                                    </Paper>
                                )}

                                {settingsTab === 1 && (
                                    <Paper sx={{ bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2 }}>
                                        <Box sx={{ p: 2, borderBottom: '1px solid rgba(255, 255, 255, 0.05)' }}>
                                            <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>{t('settings.mariadb_versions')}</Typography>
                                            <Typography variant="body2" color="text.secondary">{t('settings.mariadb_versions_desc')}</Typography>
                                        </Box>
                                        <List sx={{ maxHeight: 500, overflow: 'auto' }}>
                                            {mariaDbVersions.length === 0 && (
                                                <ListItem><ListItemText primary={t('common.loading')} /></ListItem>
                                            )}
                                            {mariaDbVersions.map((v) => (
                                                <ListItem key={v.id} sx={{ py: 2 }}>
                                                    <ListItemIcon>
                                                        {v.status === 'installed' ? <InstalledIcon color="success" /> : <AvailableIcon color="action" />}
                                                    </ListItemIcon>
                                                    <ListItemText
                                                        primary={`MariaDB ${v.version}`}
                                                        secondary={v.status === 'downloading' ? `${t('common.loading')} %${Math.round(v.progress)}` : v.status === 'installed' ? t('php.extensions.active') : t('common.available')}
                                                        sx={{ flexGrow: 1 }}
                                                    />
                                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                                                        {v.status === 'installed' && (
                                                            <TextField
                                                                label="Port"
                                                                value={settings.mariaDbPorts?.[v.id] || ''}
                                                                placeholder={v.port}
                                                                onChange={(e) => {
                                                                    const newPorts = { ...(settings.mariaDbPorts || {}), [v.id]: e.target.value }
                                                                    setSettings({ ...settings, mariaDbPorts: newPorts })
                                                                }}
                                                                variant="outlined"
                                                                size="small"
                                                                sx={{ width: 80 }}
                                                            />
                                                        )}
                                                        <Box sx={{ minWidth: 120, textAlign: 'right' }}>
                                                            {v.status === 'available' && (
                                                                <Button variant="outlined" size="small" startIcon={<DownloadIcon />} onClick={() => handleDownloadMariaDb(v.id)}>
                                                                    {t('common.download')}
                                                                </Button>
                                                            )}
                                                            {v.status === 'downloading' && (
                                                                <Box sx={{ width: '100%', mt: 1 }}>
                                                                    <LinearProgress variant="determinate" value={v.progress} sx={{ height: 8, borderRadius: 5 }} />
                                                                </Box>
                                                            )}
                                                            {v.status === 'installed' && (
                                                                <Chip label={t('common.ok').toUpperCase()} color="success" variant="outlined" size="small" />
                                                            )}
                                                        </Box>
                                                    </Box>
                                                </ListItem>
                                            ))}
                                        </List>
                                    </Paper>
                                )}

                                {settingsTab === 2 && (
                                    <Paper sx={{ bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2 }}>
                                        <Box sx={{ p: 2, borderBottom: '1px solid rgba(255, 255, 255, 0.05)' }}>
                                            <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>{t('settings.nginx_versions')}</Typography>
                                            <Typography variant="body2" color="text.secondary">{t('settings.nginx_versions_desc')}</Typography>
                                        </Box>
                                        <List sx={{ maxHeight: 500, overflow: 'auto' }}>
                                            {nginxVersions.length === 0 && (
                                                <ListItem><ListItemText primary={t('common.loading')} /></ListItem>
                                            )}
                                            {nginxVersions.map((v) => (
                                                <ListItem key={v.id} sx={{ py: 2 }}>
                                                    <ListItemIcon>
                                                        {v.status === 'installed' ? <InstalledIcon color="success" /> : <AvailableIcon color="action" />}
                                                    </ListItemIcon>
                                                    <ListItemText
                                                        primary={`Nginx ${v.version}`}
                                                        secondary={v.status === 'downloading' ? `${t('common.loading')} %${Math.round(v.progress)}` : v.status === 'installed' ? t('php.extensions.active') : t('common.available')}
                                                        sx={{ flexGrow: 1 }}
                                                    />
                                                    <Box sx={{ minWidth: 120, textAlign: 'right' }}>
                                                        {v.status === 'available' && (
                                                            <Button variant="outlined" size="small" startIcon={<DownloadIcon />} onClick={() => handleDownloadNginx(v.id)}>
                                                                {t('common.download')}
                                                            </Button>
                                                        )}
                                                        {v.status === 'downloading' && (
                                                            <Box sx={{ width: '100%', mt: 1 }}>
                                                                <LinearProgress variant="determinate" value={v.progress} sx={{ height: 8, borderRadius: 5 }} />
                                                            </Box>
                                                        )}
                                                        {v.status === 'installed' && (
                                                            <Chip label={t('common.ok').toUpperCase()} color="success" variant="outlined" size="small" />
                                                        )}
                                                    </Box>
                                                </ListItem>
                                            ))}
                                        </List>
                                    </Paper>
                                )}

                                {settingsTab === 3 && (
                                    <Paper sx={{ bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2 }}>
                                        <Box sx={{ p: 2, borderBottom: '1px solid rgba(255, 255, 255, 0.05)' }}>
                                            <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>{t('settings.apache_versions')}</Typography>
                                            <Typography variant="body2" color="text.secondary">{t('settings.apache_versions_desc')}</Typography>
                                        </Box>
                                        <List sx={{ maxHeight: 500, overflow: 'auto' }}>
                                            {apacheVersions.length === 0 && (
                                                <ListItem><ListItemText primary={t('common.loading')} /></ListItem>
                                            )}
                                            {apacheVersions.map((v) => (
                                                <ListItem key={v.id} sx={{ py: 2 }}>
                                                    <ListItemIcon>
                                                        {v.status === 'installed' ? <InstalledIcon color="success" /> : <AvailableIcon color="action" />}
                                                    </ListItemIcon>
                                                    <ListItemText
                                                        primary={`Apache ${v.version}`}
                                                        secondary={v.status === 'downloading' ? `${t('common.loading')} %${Math.round(v.progress)}` : v.status === 'installed' ? t('php.extensions.active') : t('common.available')}
                                                        sx={{ flexGrow: 1 }}
                                                    />
                                                    <Box sx={{ minWidth: 120, textAlign: 'right' }}>
                                                        {v.status === 'available' && (
                                                            <Button variant="outlined" size="small" startIcon={<DownloadIcon />} onClick={() => handleDownloadApache(v.id)}>
                                                                {t('common.download')}
                                                            </Button>
                                                        )}
                                                        {v.status === 'downloading' && (
                                                            <Box sx={{ width: '100%', mt: 1 }}>
                                                                <LinearProgress variant="determinate" value={v.progress} sx={{ height: 8, borderRadius: 5 }} />
                                                            </Box>
                                                        )}
                                                        {v.status === 'installed' && (
                                                            <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                                                                <Button variant="outlined" size="small" startIcon={<SettingsIcon />} onClick={handleOpenApacheConfig}>
                                                                    {t('common.settings').toUpperCase()}
                                                                </Button>
                                                                <Chip label={t('common.ok').toUpperCase()} color="success" variant="outlined" size="small" />
                                                            </Box>
                                                        )}
                                                    </Box>
                                                </ListItem>
                                            ))}
                                        </List>
                                    </Paper>
                                )}

                                {settingsTab === 4 && (
                                    <Paper sx={{ p: 4, bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2 }}>
                                        <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                            <SettingsIcon color="primary" />
                                            {t('settings.server')}
                                        </Typography>
                                        <Grid container spacing={3} sx={{ mt: 1 }}>
                                            <Grid item xs={12} sm={6}>
                                                <TextField variant="outlined" fullWidth label={t('settings.nginx_port')} value={settings.nginxPort} onChange={(e) => setSettings({ ...settings, nginxPort: e.target.value })} />
                                            </Grid>
                                            <Grid item xs={12} sm={6}>
                                                <TextField variant="outlined" fullWidth label={t('settings.apache_port')} value={settings.apachePort} onChange={(e) => setSettings({ ...settings, apachePort: e.target.value })} />
                                            </Grid>
                                            <Grid item xs={12} sm={6}>
                                                <TextField variant="outlined" fullWidth label={t('settings.php_port')} value={settings.phpPort} onChange={(e) => setSettings({ ...settings, phpPort: e.target.value })} />
                                            </Grid>
                                            <Grid item xs={12} sm={6}>
                                                <TextField variant="outlined" fullWidth label={t('settings.mariadb_port')} value={settings.mariaDbPort} onChange={(e) => setSettings({ ...settings, mariaDbPort: e.target.value })} />
                                            </Grid>
                                            <Grid item xs={12}>
                                                <FormControl fullWidth>
                                                    <InputLabel>{t('settings.server_type_select')}</InputLabel>
                                                    <Select
                                                        value={settings.serverType}
                                                        label={t('settings.server_type_select')}
                                                        onChange={(e) => setSettings({ ...settings, serverType: e.target.value as any })}
                                                    >
                                                        <MenuItem value="nginx">Nginx</MenuItem>
                                                        <MenuItem value="apache">Apache</MenuItem>
                                                    </Select>
                                                </FormControl>
                                            </Grid>
                                            <Grid item xs={12}>
                                                <FormControlLabel
                                                    control={<Switch checked={settings.allowRemoteAccess} onChange={(e) => setSettings({ ...settings, allowRemoteAccess: e.target.checked })} />}
                                                    label={t('settings.remote_access')}
                                                />
                                            </Grid>
                                            <Grid item xs={12} sx={{ mt: 2 }}>
                                                <Button variant="contained" color="primary" size="large" startIcon={<SaveIcon />} onClick={handleSaveSettings} fullWidth>
                                                    {t('common.save')}
                                                </Button>
                                            </Grid>
                                        </Grid>
                                    </Paper>
                                )}
                            </Box>
                        )}

                        {activeTab === 'dashboard' && (
                            <>


                                <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
                                    <Tabs value={dashboardTab} onChange={(_e, v) => setDashboardTab(v)} textColor="primary" indicatorColor="primary">
                                        <Tab label={t('common.all')} />
                                        <Tab label="Nginx" />
                                        <Tab label="Apache" />
                                        <Tab label="PHP" />
                                        <Tab label="MariaDB" />
                                    </Tabs>
                                </Box>

                                <Grid container spacing={3} sx={{ mb: 4 }}>
                                    {/* Nginx Box */}
                                    {(dashboardTab === 0 || dashboardTab === 1) && (
                                        <Grid item xs={12} sm={6} md={4}>
                                            <Paper elevation={4} sx={{
                                                p: 3, borderRadius: 3,
                                                bgcolor: 'rgba(255, 255, 255, 0.03)',
                                                backdropFilter: 'blur(10px)',
                                                border: '1px solid rgba(255, 255, 255, 0.05)',
                                                transition: 'transform 0.2s',
                                                '&:hover': { transform: 'scale(1.02)' }
                                            }}>
                                                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                                                    <WebIcon color="primary" sx={{ fontSize: 40 }} />
                                                    {getStatusChip(status.nginx)}
                                                </Box>
                                                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>Nginx</Typography>
                                                <Typography variant="body2" color="text.secondary">Port: {settings.nginxPort}</Typography>
                                                <ResourceMonitor cpu={status.nginx?.cpu} memory={status.nginx?.memory} />
                                                <Box sx={{ mt: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <Box sx={{ display: 'flex', gap: 1 }}>
                                                        <IconButton onClick={() => handleOpenLogs('nginx')} title={t('diagnostics.logs')} size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)' }}>
                                                            <TerminalIcon fontSize="small" />
                                                        </IconButton>
                                                        <IconButton
                                                            onClick={handleOpenNginxConfig}
                                                            title={t('server.nginx.config')}
                                                            size="small"
                                                            sx={{ bgcolor: 'rgba(255,255,255,0.05)', '&:hover': { color: 'primary.main' } }}
                                                        >
                                                            <SettingsIcon fontSize="small" />
                                                        </IconButton>
                                                        <IconButton
                                                            onClick={() => {
                                                                window.api.invoke('services:reload', 'nginx').then((res: any) => {
                                                                    Swal.fire({
                                                                        title: res.success ? t('common.success') : t('common.error'),
                                                                        text: res.message,
                                                                        icon: res.success ? 'success' : 'error',
                                                                        background: '#1e1e1e',
                                                                        color: '#fff',
                                                                        confirmButtonColor: '#153E5E',
                                                                        customClass: { popup: 'swal2-dark-popup' }
                                                                    })
                                                                })
                                                            }}
                                                            title={t('server.nginx.save_reload')}
                                                            size="small"
                                                            disabled={status.nginx?.status !== 'running'}
                                                            sx={{ bgcolor: 'rgba(255,255,255,0.05)', '&:hover': { color: 'primary.main' } }}
                                                        >
                                                            <RefreshIcon fontSize="small" />
                                                        </IconButton>
                                                    </Box>
                                                    <Switch
                                                        checked={status.nginx?.status === 'running' || status.nginx?.status === 'starting'}
                                                        onChange={() => handleToggleService('nginx')}
                                                        disabled={status.nginx?.status === 'starting'}
                                                    />
                                                </Box>
                                            </Paper>
                                        </Grid>
                                    )}

                                    {/* Apache Box */}
                                    {(dashboardTab === 0 || dashboardTab === 2) && (
                                        <Grid item xs={12} sm={6} md={4}>
                                            <Paper elevation={4} sx={{
                                                p: 3, borderRadius: 3,
                                                bgcolor: 'rgba(255, 255, 255, 0.03)',
                                                backdropFilter: 'blur(10px)',
                                                border: '1px solid rgba(255, 255, 255, 0.05)',
                                                transition: 'transform 0.2s',
                                                '&:hover': { transform: 'scale(1.02)' }
                                            }}>
                                                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                                                    <ServerIcon color="primary" sx={{ fontSize: 40 }} />
                                                    {getStatusChip(status.apache)}
                                                </Box>
                                                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>Apache</Typography>
                                                <Typography variant="body2" color="text.secondary">Port: {settings.apachePort}</Typography>
                                                <ResourceMonitor cpu={status.apache?.cpu} memory={status.apache?.memory} />
                                                <Box sx={{ mt: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <Box sx={{ display: 'flex', gap: 1 }}>
                                                        <IconButton onClick={() => handleOpenLogs('apache')} title={t('diagnostics.logs')} size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)' }}>
                                                            <TerminalIcon fontSize="small" />
                                                        </IconButton>
                                                        <IconButton
                                                            onClick={handleOpenApacheConfig}
                                                            title={t('server.apache.config')}
                                                            size="small"
                                                            sx={{ bgcolor: 'rgba(255,255,255,0.05)', '&:hover': { color: 'primary.main' } }}
                                                        >
                                                            <SettingsIcon fontSize="small" />
                                                        </IconButton>
                                                        <IconButton
                                                            onClick={() => {
                                                                window.api.invoke('services:reload', 'apache').then((res: any) => {
                                                                    Swal.fire({
                                                                        title: res.success ? t('common.success') : t('common.error'),
                                                                        text: res.message,
                                                                        icon: res.success ? 'success' : 'error',
                                                                        background: '#1e1e1e',
                                                                        color: '#fff',
                                                                        confirmButtonColor: '#153E5E',
                                                                        customClass: { popup: 'swal2-dark-popup' }
                                                                    })
                                                                })
                                                            }}
                                                            title={t('server.apache.save_reload')}
                                                            size="small"
                                                            disabled={status.apache?.status !== 'running'}
                                                            sx={{ bgcolor: 'rgba(255,255,255,0.05)', '&:hover': { color: 'primary.main' } }}
                                                        >
                                                            <RefreshIcon fontSize="small" />
                                                        </IconButton>
                                                    </Box>
                                                    <Switch
                                                        checked={status.apache?.status === 'running' || status.apache?.status === 'starting'}
                                                        onChange={() => handleToggleService('apache')}
                                                        disabled={status.apache?.status === 'starting'}
                                                    />
                                                </Box>
                                            </Paper>
                                        </Grid>
                                    )}

                                    {/* PHP Boxes */}
                                    {(dashboardTab === 0 || dashboardTab === 3) && installedPhpVersions.map(v => (
                                        <Grid item xs={12} sm={6} md={4} key={v.id}>
                                            <Paper elevation={4} sx={{
                                                p: 3, borderRadius: 3,
                                                bgcolor: 'rgba(255, 255, 255, 0.03)',
                                                backdropFilter: 'blur(10px)',
                                                border: '1px solid rgba(255, 255, 255, 0.05)',
                                                transition: 'transform 0.2s',
                                                '&:hover': { transform: 'scale(1.02)' }
                                            }}>
                                                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                                                    <PhpIcon color="primary" sx={{ fontSize: 40 }} />
                                                    {getStatusChip(status[`php:${v.version}`] || { status: 'stopped' })}
                                                </Box>
                                                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>PHP {v.version}</Typography>
                                                <Typography variant="body2" color="text.secondary">Port: {v.port || '?'}</Typography>
                                                <ResourceMonitor cpu={status[`php:${v.version}`]?.cpu} memory={status[`php:${v.version}`]?.memory} />
                                                <Box sx={{ mt: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <IconButton onClick={() => handleOpenLogs(`php:${v.version}`)} size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)' }}>
                                                        <TerminalIcon fontSize="small" />
                                                    </IconButton>
                                                    <Switch
                                                        checked={status[`php:${v.version}`]?.status === 'running' || status[`php:${v.version}`]?.status === 'starting'}
                                                        onChange={() => handleToggleService(`php:${v.version}`)}
                                                        disabled={status[`php:${v.version}`]?.status === 'starting'}
                                                    />
                                                </Box>
                                            </Paper>
                                        </Grid>
                                    ))}

                                    {/* MariaDB Boxes */}
                                    {(dashboardTab === 0 || dashboardTab === 4) && mariaDbVersions.filter(v => v.status === 'installed').map(v => (
                                        <Grid item xs={12} sm={6} md={4} key={v.id}>
                                            <Paper elevation={4} sx={{
                                                p: 3, borderRadius: 3,
                                                bgcolor: 'rgba(255, 255, 255, 0.03)',
                                                backdropFilter: 'blur(10px)',
                                                border: '1px solid rgba(255, 255, 255, 0.05)',
                                                transition: 'transform 0.2s',
                                                '&:hover': { transform: 'scale(1.02)' }
                                            }}>
                                                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                                                    <DbIcon color="primary" sx={{ fontSize: 40 }} />
                                                    {getStatusChip(status[`mariadb:${v.version}`] || { status: 'stopped' })}
                                                </Box>
                                                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>MariaDB {v.version}</Typography>
                                                <Typography variant="body2" color="text.secondary">Port: {settings.mariaDbPorts?.[v.id] || v.port}</Typography>
                                                <ResourceMonitor cpu={status[`mariadb:${v.version}`]?.cpu} memory={status[`mariadb:${v.version}`]?.memory} />
                                                <Box sx={{ mt: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <Box sx={{ display: 'flex', gap: 1 }}>
                                                        <IconButton onClick={() => handleOpenLogs(`mariadb:${v.version}`)} title={t('diagnostics.logs')} size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)' }}>
                                                            <TerminalIcon fontSize="small" />
                                                        </IconButton>
                                                        <IconButton onClick={() => handleResetData(`mariadb:${v.version}`)} title={t('common.reset')} size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)', '&:hover': { color: 'error.main' } }}>
                                                            <ResetIcon fontSize="small" />
                                                        </IconButton>
                                                    </Box>
                                                    <Switch
                                                        checked={status[`mariadb:${v.version}`]?.status === 'running' || status[`mariadb:${v.version}`]?.status === 'starting'}
                                                        onChange={() => handleToggleService(`mariadb:${v.version}`)}
                                                        disabled={status[`mariadb:${v.version}`]?.status === 'starting'}
                                                    />
                                                </Box>
                                            </Paper>
                                        </Grid>
                                    ))}
                                </Grid>
                            </>
                        )}

                        {activeTab === 'tools' && (
                            <Box>
                                <Typography variant="h5" sx={{ mb: 3, fontWeight: 'medium' }}>
                                    {t('common.tools')}
                                </Typography>
                                <Paper sx={{ mb: 3, p: 3, bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2, border: '1px solid rgba(255, 255, 255, 0.05)' }}>
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 3 }}>
                                        <Box sx={{ p: 2, bgcolor: 'rgba(255, 255, 255, 0.05)', borderRadius: 3 }}>
                                            <DbIcon color="primary" sx={{ fontSize: 32 }} />
                                        </Box>
                                        <Box sx={{ flexGrow: 1 }}>
                                            <Typography variant="h6" sx={{ fontWeight: 'bold' }}>phpMyAdmin</Typography>
                                            <Typography variant="body2" color="text.secondary">
                                                {pmaInstalled ? t('pma.ready_desc') : t('pma.install_desc')}
                                            </Typography>
                                        </Box>
                                        <Box>
                                            {!pmaInstalled ? (
                                                <Button
                                                    variant="contained"
                                                    size="large"
                                                    onClick={handleSetupPma}
                                                    disabled={pmaLoading}
                                                    startIcon={pmaLoading ? <CircularProgress size={20} /> : <DownloadIcon />}
                                                    sx={{ borderRadius: 2 }}
                                                >
                                                    {pmaLoading ? t('pma.installing') : t('pma.install_button')}
                                                </Button>
                                            ) : (
                                                <Button
                                                    variant="contained"
                                                    size="large"
                                                    onClick={handleOpenPma}
                                                    startIcon={<OpenIcon />}
                                                    sx={{ borderRadius: 2 }}
                                                >
                                                    {t('pma.open')}
                                                </Button>
                                            )}
                                        </Box>
                                    </Box>
                                    {pmaLoading && (
                                        <Box sx={{ mt: 3 }}>
                                            <LinearProgress variant="determinate" value={pmaProgress} sx={{ height: 8, borderRadius: 4 }} />
                                            <Typography variant="caption" sx={{ mt: 1, display: 'block', textAlign: 'center', color: 'primary.main', fontWeight: 'bold' }}>
                                                {t('pma.progress', { progress: Math.round(pmaProgress) })}
                                            </Typography>
                                        </Box>
                                    )}
                                </Paper>

                                <Paper sx={{ p: 3, bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2, border: '1px solid rgba(255, 255, 255, 0.05)', mb: 3 }}>
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 3 }}>
                                        <Box sx={{ p: 2, bgcolor: 'rgba(255, 255, 255, 0.05)', borderRadius: 3 }}>
                                            <DbIcon color="primary" sx={{ fontSize: 32 }} />
                                        </Box>
                                        <Box sx={{ flexGrow: 1 }}>
                                            <Typography variant="h6" sx={{ fontWeight: 'bold' }}>{t('mariadb.import.title')}</Typography>
                                            <Typography variant="body2" color="text.secondary">
                                                {t('mariadb.import.desc')}
                                            </Typography>
                                        </Box>
                                        <Box>
                                            <Button
                                                variant="contained"
                                                size="large"
                                                onClick={() => setIsMariaDbWizardOpen(true)}
                                                startIcon={<DbIcon />}
                                                sx={{ borderRadius: 2 }}
                                            >
                                                {t('mariadb.import.button')}
                                            </Button>
                                        </Box>
                                    </Box>
                                </Paper>

                                <Paper sx={{ p: 3, bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2, border: '1px solid rgba(255, 255, 255, 0.05)' }}>
                                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 3 }}>
                                        <Box sx={{ p: 2, bgcolor: 'rgba(255, 255, 255, 0.05)', borderRadius: 3 }}>
                                            <DbIcon color="secondary" sx={{ fontSize: 32 }} />
                                        </Box>
                                        <Box sx={{ flexGrow: 1 }}>
                                            <Typography variant="h6" sx={{ fontWeight: 'bold' }}>{t('mariadb.export.title')}</Typography>
                                            <Typography variant="body2" color="text.secondary">
                                                {t('mariadb.export.desc')}
                                            </Typography>
                                        </Box>
                                        <Box>
                                            <Button
                                                variant="contained"
                                                color="secondary"
                                                size="large"
                                                onClick={() => setIsMariaDbExportWizardOpen(true)}
                                                startIcon={<DbIcon />}
                                                sx={{ borderRadius: 2 }}
                                            >
                                                {t('mariadb.export.button')}
                                            </Button>
                                        </Box>
                                    </Box>
                                </Paper>
                            </Box>
                        )}


                        {activeTab === 'projects' && (
                            <Box>
                                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                                    <Typography variant="h5" sx={{ fontWeight: 'medium' }}>
                                        {t('projects.title')}
                                    </Typography>
                                    <Button variant="contained" startIcon={<ProjectIcon />} onClick={() => setIsProjectDialogOpen(true)}>
                                        {t('projects.add_new')}
                                    </Button>
                                </Box>

                                {projects.length === 0 ? (
                                    <Paper sx={{ p: 4, textAlign: 'center', bgcolor: 'rgba(255, 255, 255, 0.03)' }}>
                                        <Typography variant="body1" color="text.secondary">{t('projects.empty')}</Typography>
                                    </Paper>
                                ) : (
                                    <Grid container spacing={3}>
                                        {projects.map((project) => (
                                            <Grid item xs={12} md={6} key={project.id}>
                                                <Paper
                                                    elevation={0}
                                                    sx={{
                                                        p: 2.5,
                                                        background: 'rgba(255, 255, 255, 0.03)',
                                                        backdropFilter: 'blur(10px)',
                                                        border: '1px solid rgba(255, 255, 255, 0.05)',
                                                        borderRadius: 3,
                                                        transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                                        '&:hover': {
                                                            background: 'rgba(255, 255, 255, 0.06)',
                                                            transform: 'translateY(-4px)',
                                                            borderColor: 'rgba(57, 167, 255, 0.3)',
                                                            boxShadow: '0 12px 24px rgba(0,0,0,0.3)'
                                                        }
                                                    }}
                                                >
                                                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2, gap: 1 }}>
                                                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, minWidth: 0 }}>
                                                            <Avatar sx={{ bgcolor: 'rgba(57, 167, 255, 0.1)', color: '#39A7FF', flexShrink: 0 }}>
                                                                <FolderIcon />
                                                            </Avatar>
                                                            <Box sx={{ minWidth: 0, flexGrow: 1 }}>
                                                                <Typography variant="h6" noWrap sx={{ fontWeight: 700, color: '#fff', lineHeight: 1.2, textOverflow: 'ellipsis' }}>
                                                                    {project.name}
                                                                </Typography>
                                                                <Typography variant="caption" noWrap sx={{ color: 'rgba(255, 255, 255, 0.4)', fontFamily: 'monospace', display: 'block', textOverflow: 'ellipsis' }}>
                                                                    {project.path.length > 40 ? '...' + project.path.slice(-37) : project.path}
                                                                </Typography>
                                                            </Box>
                                                        </Box>
                                                        <Box sx={{ display: 'flex', gap: 0.5, flexShrink: 0 }}>
                                                            <Tooltip title={t('common.edit')}>
                                                                <IconButton size="small" onClick={() => {
                                                                    setNewProject(project)
                                                                    setIsProjectDialogOpen(true)
                                                                }} sx={{ color: 'rgba(255,255,255,0.4)', '&:hover': { color: '#39A7FF' } }}>
                                                                    <EditIcon fontSize="small" />
                                                                </IconButton>
                                                            </Tooltip>
                                                            {project.serverType !== 'apache' && (
                                                                <Tooltip title={t('server.nginx.config')}>
                                                                    <IconButton size="small" onClick={() => handleOpenProjectNginxConfig(project.host)} sx={{ color: 'rgba(255,255,255,0.4)', '&:hover': { color: '#39A7FF' } }}>
                                                                        <TerminalIcon fontSize="small" />
                                                                    </IconButton>
                                                                </Tooltip>
                                                            )}
                                                            <Tooltip title="Sil">
                                                <IconButton size="small" onClick={() => handleRemoveProject(project.id)} sx={{ color: 'rgba(255,255,255,0.4)', '&:hover': { color: '#ff4444' } }}>
                                                                    <DeleteIcon fontSize="small" />
                                                                </IconButton>
                                                            </Tooltip>
                                                        </Box>
                                                    </Box>

                                                    <Stack spacing={1.5}>
                                                        <Box sx={{ display: 'flex', gap: 1 }}>
                                                            <Chip
                                                                size="small"
                                                                icon={<PhpIcon sx={{ fontSize: '1rem !important' }} />}
                                                                label={`PHP ${project.phpVersion}`}
                                                                sx={{ bgcolor: 'rgba(71, 74, 255, 0.1)', color: '#777bb4', fontWeight: 600, border: '1px solid rgba(71, 74, 255, 0.2)' }}
                                                            />
                                                            <Chip
                                                                size="small"
                                                                icon={project.serverType === 'apache' ? <ServerIcon sx={{ fontSize: '1rem !important' }} /> : <WebIcon sx={{ fontSize: '1rem !important' }} />}
                                                                label={project.serverType === 'apache' ? 'Apache' : 'Nginx'}
                                                                sx={{ bgcolor: 'rgba(255, 255, 255, 0.05)', color: '#fff', fontWeight: 600 }}
                                                            />
                                                        </Box>

                                                        <ProjectResourceMonitor 
                                                            serverType={project.serverType === 'apache' ? 'Apache' : 'Nginx'}
                                                            serverStats={project.serverType === 'apache' ? status.apache : status.nginx}
                                                            phpStats={status[`php:${project.phpVersion}`]}
                                                        />

                                                        <Paper variant="outlined" sx={{
                                                            p: 1.5,
                                                            bgcolor: 'rgba(0,0,0,0.2)',
                                                            borderColor: 'rgba(255,255,255,0.05)',
                                                            borderRadius: 2,
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            justifyContent: 'space-between'
                                                        }}>
                                                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                                                <HostIcon sx={{ fontSize: '1rem', color: 'rgba(255,255,255,0.3)' }} />
                                                                <Typography variant="body2" sx={{ color: '#fff', fontWeight: 500, fontFamily: 'monospace' }}>
                                                                    {project.host}
                                                                </Typography>
                                                            </Box>
                                                            <Button
                                                                size="small"
                                                                endIcon={<LaunchIcon />}
                                                                onClick={() => {
                                                                    const port = project.serverType === 'apache' ? settings.apachePort : settings.nginxPort
                                                                    window.open(`http://localhost:${port}/${project.host}/`, '_blank')
                                                                }}
                                                                sx={{
                                                                    color: '#39A7FF',
                                                                    textTransform: 'none',
                                                                    fontSize: '0.75rem',
                                                                    p: '2px 8px',
                                                                    '&:hover': { bgcolor: 'rgba(57, 167, 255, 0.1)' }
                                                                }}
                                                            >
                                                                {t('projects.browse')}
                                                            </Button>
                                                        </Paper>
                                                    </Stack>
                                                </Paper>
                                            </Grid>
                                        ))}
                                    </Grid>
                                )}
                            </Box>
                        )}
                    </Container>
                </Box >

                <Snackbar
                    open={notification.open}
                    autoHideDuration={4000}
                    onClose={() => setNotification({ ...notification, open: false })}
                >
                    <Alert severity={notification.severity} variant="filled" sx={{ width: '100%' }}>
                        {notification.message}
                    </Alert>
                </Snackbar>

                {/* Log Viewer Dialog */}
                <Dialog
                    open={logDialogOpen}
                    onClose={() => setLogDialogOpen(false)}
                    maxWidth="md"
                    fullWidth
                    PaperProps={{
                        sx: {
                            bgcolor: '#1e1e1e',
                            color: '#d4d4d4',
                            borderRadius: 2,
                            boxShadow: '0 8px 32px rgba(0,0,0,0.5)'
                        }
                    }}
                >
                    <DialogTitle sx={{
                        borderBottom: '1px solid #333',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        pb: 1
                    }}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <TerminalIcon color="primary" />
                            <Typography variant="h6" sx={{ fontWeight: 600, color: '#fff' }}>
                                {selectedService?.toUpperCase()} - {t('diagnostics.logs', 'Servis Logları')}
                            </Typography>
                        </Box>
                        <IconButton size="small" onClick={() => setLogDialogOpen(false)} sx={{ color: '#666' }}>
                            <CloseIcon />
                        </IconButton>
                    </DialogTitle>
                    <DialogContent sx={{ p: 0, bgcolor: '#000' }}>
                        <Box
                            sx={{
                                height: '400px',
                                overflowY: 'auto',
                                p: 2,
                                fontFamily: '"Fira Code", "Consolas", monospace',
                                fontSize: '0.875rem',
                                display: 'flex',
                                flexDirection: 'column',
                                gap: '2px'
                            }}
                        >
                            {logs.length === 0 ? (
                                <Typography sx={{ color: '#666', fontStyle: 'italic', textAlign: 'center', mt: 4 }}>
                                    {t('diagnostics.noLogs', 'Henüz log kaydı bulunmuyor.')}
                                </Typography>
                            ) : (
                                logs.map((log, i) => {
                                    let color = '#d4d4d4'
                                    if (log.toLowerCase().includes('error') || log.toLowerCase().includes('failed') || log.toLowerCase().includes('emerg') || log.toLowerCase().includes('exit code 1')) {
                                        color = '#f44336'
                                    } else if (log.toLowerCase().includes('warning') || log.toLowerCase().includes('warn')) {
                                        color = '#ff9800'
                                    } else if (log.toLowerCase().includes('starting') || log.toLowerCase().includes('started') || log.toLowerCase().includes('ready') || log.toLowerCase().includes('success')) {
                                        color = '#4caf50'
                                    }

                                    return (
                                        <Box key={i} sx={{ display: 'flex', gap: 1 }}>
                                            <Typography
                                                component="span"
                                                sx={{
                                                    color: '#569cd6',
                                                    minWidth: '80px',
                                                    userSelect: 'none',
                                                    fontSize: '0.8rem',
                                                    opacity: 0.7
                                                }}
                                            >
                                                {log.match(/\[(\d+:\d+:\d+)\]/)?.[1] || ''}
                                            </Typography>
                                            <Typography
                                                component="span"
                                                sx={{
                                                    color,
                                                    whiteSpace: 'pre-wrap',
                                                    wordBreak: 'break-all'
                                                }}
                                            >
                                                {log.replace(/\[\d+:\d+:\d+\]\s*/, '')}
                                            </Typography>
                                        </Box>
                                    )
                                })
                            )}
                            <div id="log-end" />
                        </Box>
                    </DialogContent>
                    <DialogActions sx={{ borderTop: '1px solid #333', p: 1, gap: 1 }}>
                        <Button
                            startIcon={<ContentCopyIcon />}
                            onClick={() => {
                                navigator.clipboard.writeText(logs.join('\n'))
                            }}
                            sx={{ color: '#888', '&:hover': { color: '#fff' } }}
                        >
                            {t('common.copy', 'Kopyala')}
                        </Button>
                        <Box sx={{ flexGrow: 1 }} />
                        <Button
                            variant="contained"
                            onClick={() => setLogDialogOpen(false)}
                            sx={{ borderRadius: '20px' }}
                        >
                            {t('common.close', 'Kapat')}
                        </Button>
                    </DialogActions>
                </Dialog>

                <Dialog open={isProjectDialogOpen} onClose={() => {
                    setIsProjectDialogOpen(false)
                    setNewProject({ name: '', path: '', phpVersion: '', mariaDbVersion: '', host: 'localhost', serverType: 'nginx' })
                }} fullWidth maxWidth="sm">
                    <DialogTitle>{newProject.id ? t('projects.edit') : t('projects.add_new')}</DialogTitle>
                    <DialogContent>
                        <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
                            <TextField
                                label={t('projects.name')}
                                fullWidth
                                value={newProject.name}
                                onChange={(e) => setNewProject({ ...newProject, name: e.target.value })}
                            />
                            <TextField
                                label={t('projects.path')}
                                fullWidth
                                value={newProject.path}
                                InputProps={{
                                    endAdornment: (
                                        <InputAdornment position="end">
                                            <IconButton onClick={handleSelectPath} edge="end">
                                                <FolderOpenIcon />
                                            </IconButton>
                                        </InputAdornment>
                                    ),
                                }}
                                onChange={(e) => setNewProject({ ...newProject, path: e.target.value })}
                            />
                            <TextField
                                label={t('projects.hostname_placeholder')}
                                fullWidth
                                value={newProject.host}
                                onChange={(e) => setNewProject({ ...newProject, host: e.target.value })}
                            />
                            <FormControl fullWidth disabled={installedPhpVersions.length === 0}>
                                <InputLabel id="php-version-label">{t('projects.php_version')}</InputLabel>
                                <Select
                                    labelId="php-version-label"
                                    value={newProject.phpVersion}
                                    label={t('projects.php_version')}
                                    onChange={(e) => setNewProject({ ...newProject, phpVersion: e.target.value })}
                                >
                                    {installedPhpVersions.length > 0 ? (
                                        installedPhpVersions.map(v => (
                                            <MenuItem key={v.id} value={v.version}>PHP {v.version}</MenuItem>
                                        ))
                                    ) : (
                                        <MenuItem disabled value="">{t('projects.no_php_warning')}</MenuItem>
                                    )}
                                </Select>
                            </FormControl>
                            <FormControl fullWidth>
                                <InputLabel id="server-type-label">{t('projects.server_type')}</InputLabel>
                                <Select
                                    labelId="server-type-label"
                                    value={newProject.serverType || 'nginx'}
                                    label={t('projects.server_type')}
                                    onChange={(e) => setNewProject({ ...newProject, serverType: e.target.value as any })}
                                >
                                    <MenuItem value="nginx">Nginx</MenuItem>
                                    <MenuItem value="apache">{t('projects.apache_htaccess')}</MenuItem>
                                </Select>
                            </FormControl>
                        </Box>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => {
                            setIsProjectDialogOpen(false)
                            setNewProject({ name: '', path: '', phpVersion: '', mariaDbVersion: '', host: 'localhost', serverType: 'nginx' })
                        }}>{t('common.cancel')}</Button>
                        <Button
                            onClick={handleAddProject}
                            variant="contained"
                            disabled={!newProject.name || !newProject.path || installedPhpVersions.length === 0}
                        >
                            {newProject.id ? t('common.save') : t('common.save')}
                        </Button>
                    </DialogActions>
                </Dialog>

                <MariaDbImportWizard
                    open={isMariaDbWizardOpen}
                    onClose={() => setIsMariaDbWizardOpen(false)}
                    mariaDbVersions={mariaDbVersions}
                />

                <MariaDbExportWizard
                    open={isMariaDbExportWizardOpen}
                    onClose={() => setIsMariaDbExportWizardOpen(false)}
                    mariaDbVersions={mariaDbVersions}
                />

                <Dialog
                    open={isNginxConfigOpen}
                    onClose={() => setIsNginxConfigOpen(false)}
                    maxWidth="md"
                    fullWidth
                    PaperProps={{
                        sx: {
                            bgcolor: '#1e1e1e',
                            color: '#fff',
                            borderRadius: 3,
                            border: '1px solid rgba(255,255,255,0.1)'
                        }
                    }}
                >
                    <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Typography variant="h6">{t('server.nginx.config_title')}</Typography>
                        <IconButton onClick={() => setIsNginxConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.5)' }}>
                            <CloseIcon />
                        </IconButton>
                    </DialogTitle>
                    <DialogContent dividers sx={{ borderColor: 'rgba(255,255,255,0.1)' }}>
                        <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.4)', mb: 2, display: 'block' }}>
                            {t('server.nginx.config_warning')}
                        </Typography>
                        <NginxCodeEditor
                            value={nginxConfig}
                            onChange={(val) => setNginxConfig(val)}
                        />
                    </DialogContent>
                    <DialogActions sx={{ p: 2, gap: 1 }}>
                        <Button
                            onClick={handleTestNginxConfig}
                            variant="outlined"
                            startIcon={<RefreshIcon />}
                            sx={{ color: '#fff', borderColor: 'rgba(255,255,255,0.3)' }}
                        >
                            {t('server.nginx.test_config')}
                        </Button>
                        <Button onClick={() => setIsNginxConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.6)' }}>
                            {t('common.cancel')}
                        </Button>
                        <Button
                            onClick={handleSaveNginxConfig}
                            variant="contained"
                            startIcon={<SaveIcon />}
                        >
                            {t('server.nginx.save_reload')}
                        </Button>
                    </DialogActions>
                </Dialog>

                <Dialog
                    open={isProjectNginxConfigOpen}
                    onClose={() => setIsProjectNginxConfigOpen(false)}
                    maxWidth="md"
                    fullWidth
                    PaperProps={{
                        sx: {
                            bgcolor: '#1e1e1e',
                            color: '#fff',
                            borderRadius: 3,
                            border: '1px solid rgba(255,255,255,0.1)'
                        }
                    }}
                >
                    <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Typography variant="h6">{t('server.project_nginx.title', { host: selectedProjectHost })}</Typography>
                        <IconButton onClick={() => setIsProjectNginxConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.5)' }}>
                            <CloseIcon />
                        </IconButton>
                    </DialogTitle>
                    <DialogContent dividers sx={{ borderColor: 'rgba(255,255,255,0.1)' }}>
                        <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.4)', mb: 2, display: 'block' }}>
                            {t('server.project_nginx.tip', { host: selectedProjectHost })}
                        </Typography>
                        <NginxCodeEditor
                            value={projectNginxConfig}
                            onChange={(val) => setProjectNginxConfig(val)}
                        />
                    </DialogContent>
                    <DialogActions sx={{ p: 2, gap: 1 }}>
                        <Button
                            onClick={async () => {
                                if (window.api && window.api.invoke) {
                                    // We need to test the global config because this project is part of it
                                    // But we should ideally save the project config first (to the temp or real file)
                                    // For now, testing global config is the most reliable
                                    const result = await window.api.invoke('project:nginx:test', selectedProjectHost, projectNginxConfig)
                                    const errorInfo = !result.success ? parseNginxError(result.message) : null
                                    const formattedMessage = result.message
                                        .replace(/\[emerg\]/g, '<span style="color: #ff5252; font-weight: bold;">[emerg]</span>')
                                        .replace(/\[warn\]/g, '<span style="color: #ffb142; font-weight: bold;">[warn]</span>')
                                        .replace(/failed/g, '<span style="color: #ff5252;">failed</span>')
                                        .replace(/successful/g, '<span style="color: #33d9b2;">successful</span>')

                                    Swal.fire({
                                        title: result.success ? t('common.success') : t('server.nginx.test_failed'),
                                        html: `
                                            <div class="nginx-error-container">
                                                ${formattedMessage}
                                            </div>
                                            ${!result.success && errorInfo ? `
                                                <div style="margin-top: 15px; text-align: center;">
                                                    <p style="font-size: 0.9rem; color: #ffb142;">
                                                        <b>{t('server.project_nginx.error_line', { line: errorInfo.line })}</b>
                                                    </p>
                                                </div>
                                            ` : ''}
                                        `,
                                        icon: result.success ? 'success' : 'error',
                                        background: '#1e1e1e',
                                        color: '#fff',
                                        width: '600px'
                                    })
                                }
                            }}
                            variant="outlined"
                            startIcon={<RefreshIcon />}
                            sx={{ color: '#fff', borderColor: 'rgba(255,255,255,0.3)' }}
                        >
                            {t('server.nginx.test_config')}
                        </Button>
                        <Button onClick={() => setIsProjectNginxConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.6)' }}>
                            {t('common.cancel')}
                        </Button>
                        <Button
                            onClick={handleSaveProjectNginxConfig}
                            variant="contained"
                            startIcon={<SaveIcon />}
                        >
                            {t('server.nginx.save_reload')}
                        </Button>
                    </DialogActions>
                </Dialog>
                <Dialog
                    open={isApacheConfigOpen}
                    onClose={() => setIsApacheConfigOpen(false)}
                    maxWidth="md"
                    fullWidth
                    PaperProps={{
                        sx: {
                            bgcolor: '#1e1e1e',
                            color: '#fff',
                            borderRadius: 3,
                            border: '1px solid rgba(255,255,255,0.1)'
                        }
                    }}
                >
                    <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Typography variant="h6">{t('server.apache.config_title')}</Typography>
                        <IconButton onClick={() => setIsApacheConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.5)' }}>
                            <CloseIcon />
                        </IconButton>
                    </DialogTitle>
                    <DialogContent dividers sx={{ borderColor: 'rgba(255,255,255,0.1)' }}>
                        <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.4)', mb: 2, display: 'block' }}>
                            {t('server.apache.config_desc')}
                        </Typography>
                        <ApacheCodeEditor
                            value={apacheConfig}
                            onChange={(val) => setApacheConfig(val)}
                        />
                    </DialogContent>
                    <DialogActions sx={{ p: 2, gap: 1 }}>
                        <Button
                            onClick={handleTestApacheConfig}
                            variant="outlined"
                            startIcon={<RefreshIcon />}
                            sx={{ color: '#fff', borderColor: 'rgba(255,255,255,0.3)' }}
                        >
                            {t('server.apache.test_config')}
                        </Button>
                        <Button onClick={() => setIsApacheConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.6)' }}>
                            {t('common.cancel')}
                        </Button>
                        <Button onClick={handleSaveApacheConfig} variant="contained" color="primary" startIcon={<SaveIcon />}>
                            {t('server.apache.save_reload')}
                        </Button>
                    </DialogActions>
                </Dialog>

                <PhpExtensionManager
                    open={isPhpExtensionsOpen}
                    onClose={() => setIsPhpExtensionsOpen(false)}
                    phpVersion={selectedPhpVersion}
                />
            </Box >
        </>
    )
}

export default App
