import React, { useState, useEffect } 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 MariaDbImportWizard from './components/MariaDbImportWizard'
import MariaDbExportWizard from './components/MariaDbExportWizard'
import NginxCodeEditor from './components/NginxCodeEditor'
import PhpExtensionManager from './components/PhpExtensionManager'

declare global {
    interface Window {
        api: any
    }
}

const drawerWidth = 240

interface ServiceStatus {
    [key: string]: string
}

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: 'stopped',
        apache: 'stopped',
        php: 'stopped',
        mariadb: '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 [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] || 'stopped') === 'stopped'
        if (isStarting) {
            setStatus(prev => ({ ...prev, [service]: 'starting' }))
        }

        const result = (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: 'Hata!',
                text: result.message,
                icon: 'error',
                confirmButtonText: 'Tamam',
                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: 'Emin misiniz?',
            text: `${service} verilerini sıfırlamak istiyor musunuz? Bu işlem tüm verileri siler ve temiz kurulum yapar.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sıfırla',
            cancelButtonText: 'Vazgeç',
            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 ? 'Başarılı!' : 'Hata!',
                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: 'Ayarlar kaydedildi.', severity: 'success' })
            }
        }
    }

    const toggleLanguage = () => {
        const newLang = i18n.language === 'tr' ? 'en' : i18n.language === 'en' ? 'de' : 'tr'
        i18n.changeLanguage(newLang)
    }

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

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

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

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

        fetchStatus()
        setNotification({ open: true, message: 'Tüm servisler başlatıldı.', 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] === 'running' || status[s] === 'starting'))
        const mariaDbToStop = Object.keys(status).filter(s => (s.startsWith('mariadb:') || s.startsWith('mysql:')) && (status[s] === 'running' || status[s] === 'starting'))

        await Promise.all([
            ...criticalServices.filter(s => status[s] === 'running' || status[s] === '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üm servisler durduruldu.', severity: 'success' })
    }

    const getStatusChip = (s: string) => {
        if (s === 'starting') {
            return <Chip label="BAŞLATILIYOR..." color="warning" size="small" sx={{ fontWeight: 'bold' }} icon={<CircularProgress size={14} color="inherit" />} />
        }
        const color = s === 'running' ? 'success' : s === 'stopped' ? 'error' : 'warning'
        return <Chip label={s.toUpperCase()} color={color} size="small" sx={{ fontWeight: 'bold' }} />
    }

    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 ? 'Proje güncellendi.' : 'Proje başarıyla eklendi.', severity: 'success' })
        fetchProjects()
    }

    const handleRemoveProject = async (id: string) => {
        if (!window.api) return
        const result = await Swal.fire({
            title: 'Emin misiniz?',
            text: "Bu projeyi silmek istediğinize emin misiniz? Nginx ayarları otomatik olarak güncellenecektir.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ff4444',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Evet, sil!',
            cancelButtonText: 'İptal',
            background: '#1e1e1e',
            color: '#fff'
        })

        if (result.isConfirmed) {
            await window.api.removeProject(id)
            setNotification({ open: true, message: 'Proje silindi. Nginx yeniden yüklendi.', 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) {
                setNotification({ open: true, message: 'Nginx yapılandırması kaydedildi ve yeniden yüklendi.', severity: 'success' })
                setIsNginxConfigOpen(false)
            }
        }
    }

    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>Sorunlu Proje:</b> ${errorInfo.host} (Satır: ${errorInfo.line})
                            </p>
                        </div>
                    ` : ''}
                `,
                icon: result.success ? 'success' : 'error',
                showCancelButton: !result.success && !!errorInfo?.host,
                confirmButtonText: !result.success && errorInfo?.host ? 'Düzeltmeye Git' : 'Tamam',
                cancelButtonText: 'Kapat',
                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) {
                setNotification({ open: true, message: `${selectedProjectHost} için Nginx yapılandırması kaydedildi.`, severity: 'success' })
                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) {
                setPmaInstalled(true)
                setNotification({ open: true, message: 'phpMyAdmin başarıyla kuruldu.', severity: 'success' })
            } else {
                setNotification({ open: true, message: 'phpMyAdmin kurulumu sırasında hata oluştu.', 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={{ justifyContent: 'flex-end' }}>
                        <Tooltip title="Dil Değiştir">
                            <IconButton onClick={toggleLanguage} color="inherit">
                                <LanguageIcon />
                            </IconButton>
                        </Tooltip>
                        <IconButton color="inherit" onClick={() => setActiveTab('settings')}>
                            <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="Dashboard" />
                                </ListItemButton>
                            </ListItem>
                            <ListItem disablePadding>
                                <ListItemButton selected={activeTab === 'projects'} onClick={() => setActiveTab('projects')}>
                                    <ListItemIcon><ProjectIcon color={activeTab === 'projects' ? 'primary' : 'inherit'} /></ListItemIcon>
                                    <ListItemText primary="Projeler" />
                                </ListItemButton>
                            </ListItem>
                            <ListItem disablePadding>
                                <ListItemButton selected={activeTab === 'tools'} onClick={() => setActiveTab('tools')}>
                                    <ListItemIcon><ToolsIcon color={activeTab === 'tools' ? 'primary' : 'inherit'} /></ListItemIcon>
                                    <ListItemText primary="Araçlar" />
                                </ListItemButton>
                            </ListItem>
                        </List>
                        <Divider />
                        <List>
                            <ListItem disablePadding>
                                <ListItemButton selected={activeTab === 'settings'} onClick={() => setActiveTab('settings')}>
                                    <ListItemIcon><SettingsIcon color={activeTab === 'settings' ? 'primary' : 'inherit'} /></ListItemIcon>
                                    <ListItemText primary="Genel Ayarlar" />
                                </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="Sunucu Ayarları" 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' }}>PHP Sürümleri</Typography>
                                            <Typography variant="body2" color="text.secondary">Gereken PHP sürümlerini buradan indirebilir ve yönetebilirsiniz.</Typography>
                                        </Box>
                                        <List sx={{ maxHeight: 500, overflow: 'auto' }}>
                                            {phpVersions.length === 0 && (
                                                <ListItem><ListItemText primary="Yükleniyor veya liste boş..." /></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' ? `İndiriliyor... %${Math.round(v.progress)}` : v.status === 'installed' ? 'Kurulu' : 'İndirilebilir'}
                                                        sx={{ flexGrow: 1 }}
                                                    />
                                                    <Box sx={{ minWidth: 120, textAlign: 'right' }}>
                                                        {v.status === 'available' && (
                                                            <Button variant="outlined" size="small" startIcon={<DownloadIcon />} onClick={() => handleDownloadPhp(v.id)}>
                                                                İNDİR
                                                            </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)}>
                                                                    EKLENTİLER
                                                                </Button>
                                                                <Chip label="HAZIR" 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' }}>MariaDB Sürümleri</Typography>
                                            <Typography variant="body2" color="text.secondary">Farklı MariaDB sürümlerini indirebilir ve sunucunuzda kullanabilirsiniz.</Typography>
                                        </Box>
                                        <List sx={{ maxHeight: 500, overflow: 'auto' }}>
                                            {mariaDbVersions.length === 0 && (
                                                <ListItem><ListItemText primary="Yükleniyor veya liste boş..." /></ListItem>
                                            )}
                                            {mariaDbVersions.map((v) => (
                                                <ListItem key={v.id} sx={{ py: 2 }}>
                                                    <ListItemIcon>
                                                        {v.status === 'installed' ? <InstalledIcon color="success" /> : <AvailableIcon color="action" />}
                                                    </ListItemIcon>
                                                    <ListItemText
                                                        primary={
                                                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                                                {`MariaDB ${v.version} (${v.cycle})`}
                                                                {v.description && (
                                                                    <Chip label={v.description} size="small" variant="outlined" sx={{ fontSize: '0.7rem', height: 20 }} />
                                                                )}
                                                            </Box>
                                                        }
                                                        secondary={v.status === 'downloading' ? `İndiriliyor... %${Math.round(v.progress)}` : v.status === 'installed' ? 'Kurulu' : 'İndirilebilir'}
                                                        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)}>
                                                                    İNDİR
                                                                </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="HAZIR" 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' }}>Nginx Web Sunucusu</Typography>
                                            <Typography variant="body2" color="text.secondary">Sunucu için gerekli Nginx binary dosyalarını buradan indirebilirsiniz.</Typography>
                                        </Box>
                                        <List>
                                            {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} (Stable)`}
                                                        secondary={v.status === 'downloading' ? `İndiriliyor... %${Math.round(v.progress)}` : v.status === 'installed' ? 'Kurulu' : 'İndirilebilir'}
                                                        sx={{ flexGrow: 1 }}
                                                    />
                                                    <Box sx={{ minWidth: 120, textAlign: 'right' }}>
                                                        {v.status === 'available' && (
                                                            <Button variant="outlined" size="small" startIcon={<DownloadIcon />} onClick={() => handleDownloadNginx(v.id)}>
                                                                İNDİR
                                                            </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="HAZIR" 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' }}>Apache Web Sunucusu</Typography>
                                            <Typography variant="body2" color="text.secondary">Apache HTTP Server binary dosyalarını buradan yönetebilirsiniz.</Typography>
                                        </Box>
                                        <List>
                                            {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' ? `İndiriliyor... %${Math.round(v.progress)}` : v.status === 'installed' ? 'Kurulu' : 'İndirilebilir'}
                                                        sx={{ flexGrow: 1 }}
                                                    />
                                                    <Box sx={{ minWidth: 120, textAlign: 'right' }}>
                                                        {v.status === 'available' && (
                                                            <Button variant="outlined" size="small" startIcon={<DownloadIcon />} onClick={() => handleDownloadApache(v.id)}>
                                                                İNDİR
                                                            </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="HAZIR" color="success" variant="outlined" size="small" />
                                                        )}
                                                    </Box>
                                                </ListItem>
                                            ))}
                                        </List>
                                    </Paper>
                                )}

                                {settingsTab === 4 && (
                                    <Box component={Stack} spacing={3}>
                                        <Paper sx={{ p: 3, bgcolor: 'rgba(255, 255, 255, 0.03)', borderRadius: 2 }}>
                                            <Typography variant="h6" gutterBottom>Port Ayarları</Typography>
                                            <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 3, mt: 2 }}>
                                                <FormControl variant="filled" size="small" fullWidth>
                                                    <InputLabel>Varsayılan Web Sunucusu</InputLabel>
                                                    <Select
                                                        value={settings.serverType || 'nginx'}
                                                        onChange={(e) => setSettings({ ...settings, serverType: e.target.value as any })}
                                                    >
                                                        <MenuItem value="nginx">Nginx (Performans)</MenuItem>
                                                        <MenuItem value="apache">Apache (htaccess Desteği)</MenuItem>
                                                    </Select>
                                                </FormControl>
                                                <TextField
                                                    label="Nginx Portu"
                                                    value={settings.nginxPort}
                                                    onChange={(e) => setSettings({ ...settings, nginxPort: e.target.value })}
                                                    variant="filled"
                                                    size="small"
                                                    helperText="Varsayılan: 80"
                                                />
                                                <TextField
                                                    label="Apache Portu"
                                                    value={settings.apachePort}
                                                    onChange={(e) => setSettings({ ...settings, apachePort: e.target.value })}
                                                    variant="filled"
                                                    size="small"
                                                    helperText="Varsayılan: 8080"
                                                />
                                                <TextField
                                                    label="PHP FastCGI Portu"
                                                    value={settings.phpPort}
                                                    onChange={(e) => setSettings({ ...settings, phpPort: e.target.value })}
                                                    variant="filled"
                                                    size="small"
                                                    helperText="Varsayılan: 9001"
                                                />
                                                <TextField
                                                    label="MariaDB Portu"
                                                    value={settings.mariaDbPort}
                                                    onChange={(e) => setSettings({ ...settings, mariaDbPort: e.target.value })}
                                                    variant="filled"
                                                    size="small"
                                                    helperText="Varsayılan: 3306"
                                                />
                                            </Box>
                                            <Divider sx={{ my: 2, bgcolor: 'rgba(255,255,255,0.05)' }} />
                                            <FormControlLabel
                                                control={
                                                    <Switch
                                                        checked={settings.allowRemoteAccess}
                                                        onChange={(e) => {
                                                            const newSettings = { ...settings, allowRemoteAccess: e.target.checked }
                                                            setSettings(newSettings)
                                                        }}
                                                    />
                                                }
                                                label="Dış Erişime İzin Ver (0.0.0.0)"
                                            />
                                            <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
                                                {settings.allowRemoteAccess
                                                    ? "Sunucu yerel ağdaki diğer cihazlardan erişilebilir."
                                                    : "Sunucu sadece bu bilgisayardan (127.0.0.1) erişilebilir."}
                                            </Typography>
                                        </Paper>
                                        <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                                            <Button variant="contained" startIcon={<SaveIcon />} size="large" onClick={handleSaveSettings}>
                                                Ayarları Kaydet
                                            </Button>
                                        </Box>
                                    </Box>
                                )}
                            </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" sx={{ mb: 2 }}>Port: {settings.nginxPort}</Typography>
                                                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <Box sx={{ display: 'flex', gap: 1 }}>
                                                        <IconButton onClick={() => handleOpenLogs('nginx')} title="Hata Logları" size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)' }}>
                                                            <TerminalIcon fontSize="small" />
                                                        </IconButton>
                                                        <IconButton
                                                            onClick={handleOpenNginxConfig}
                                                            title="Nginx Yapılandırması"
                                                            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) => {
                                                                    setNotification({ open: true, message: res.message, severity: res.success ? 'success' : 'error' })
                                                                })
                                                            }}
                                                            title="Yapılandırmayı Yeniden Yükle"
                                                            size="small"
                                                            disabled={status.nginx !== 'running'}
                                                            sx={{ bgcolor: 'rgba(255,255,255,0.05)', '&:hover': { color: 'primary.main' } }}
                                                        >
                                                            <RefreshIcon fontSize="small" />
                                                        </IconButton>
                                                    </Box>
                                                    <Switch
                                                        checked={status.nginx === 'running' || status.nginx === 'starting'}
                                                        onChange={() => handleToggleService('nginx')}
                                                        disabled={status.nginx === '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" sx={{ mb: 2 }}>Port: {settings.apachePort}</Typography>
                                                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <Box sx={{ display: 'flex', gap: 1 }}>
                                                        <IconButton onClick={() => handleOpenLogs('apache')} title="Hata Logları" size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)' }}>
                                                            <TerminalIcon fontSize="small" />
                                                        </IconButton>
                                                    </Box>
                                                    <Switch
                                                        checked={status.apache === 'running' || status.apache === 'starting'}
                                                        onChange={() => handleToggleService('apache')}
                                                        disabled={status.apache === '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}`] || 'stopped')}
                                                </Box>
                                                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>PHP {v.version}</Typography>
                                                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>Port: {v.port || '?'}</Typography>
                                                <Box sx={{ 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}`] || 'stopped') === 'running' || status[`php:${v.version}`] === 'starting'}
                                                        onChange={() => handleToggleService(`php:${v.version}`)}
                                                        disabled={status[`php:${v.version}`] === '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}`] || 'stopped')}
                                                </Box>
                                                <Typography variant="h6" sx={{ fontWeight: 'bold' }}>MariaDB {v.version}</Typography>
                                                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>Port: {settings.mariaDbPorts?.[v.id] || v.port}</Typography>
                                                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                                    <Box sx={{ display: 'flex', gap: 1 }}>
                                                        <IconButton onClick={() => handleOpenLogs(`mariadb:${v.version}`)} title="Hata Logları" size="small" sx={{ bgcolor: 'rgba(255,255,255,0.05)' }}>
                                                            <TerminalIcon fontSize="small" />
                                                        </IconButton>
                                                        <IconButton onClick={() => handleResetData(`mariadb:${v.version}`)} title="Verileri Sıfırla" 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}`] || 'stopped') === 'running' || status[`mariadb:${v.version}`] === 'starting'}
                                                        onChange={() => handleToggleService(`mariadb:${v.version}`)}
                                                        disabled={status[`mariadb:${v.version}`] === 'starting'}
                                                    />
                                                </Box>
                                            </Paper>
                                        </Grid>
                                    ))}
                                </Grid>

                                <Box sx={{ display: 'flex', gap: 2 }}>
                                    <Button variant="contained" fullWidth startIcon={<StartIcon />} size="large" onClick={handleStartAll} sx={{ borderRadius: 2, padding: '12px', background: 'linear-gradient(45deg, #153E5E 30%, #4A7CA3 90%)', boxShadow: '0 3px 5px 2px rgba(21, 62, 94, .3)' }}>
                                        {t('common.start')}
                                    </Button>
                                    <Button variant="outlined" fullWidth startIcon={<StopIcon />} size="large" color="error" onClick={handleStopAll} sx={{ borderRadius: 2, padding: '12px', borderWidth: 2, '&:hover': { borderWidth: 2 } }}>
                                        {t('common.stop')}
                                    </Button>
                                </Box>
                            </>
                        )}

                        {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 ? 'Veritabanı yönetimi için phpMyAdmin hazır.' : 'Veritabanlarını web üzerinden yönetmek için phpMyAdmin kurun.'}
                                            </Typography>
                                        </Box>
                                        <Box>
                                            {!pmaInstalled ? (
                                                <Button
                                                    variant="contained"
                                                    size="large"
                                                    onClick={handleSetupPma}
                                                    disabled={pmaLoading}
                                                    startIcon={pmaLoading ? <CircularProgress size={20} /> : <DownloadIcon />}
                                                    sx={{ borderRadius: 2 }}
                                                >
                                                    {pmaLoading ? 'KURULUYOR...' : 'KURULUMU BAŞLAT'}
                                                </Button>
                                            ) : (
                                                <Button
                                                    variant="contained"
                                                    size="large"
                                                    onClick={handleOpenPma}
                                                    startIcon={<OpenIcon />}
                                                    sx={{ borderRadius: 2 }}
                                                >
                                                    AÇ
                                                </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' }}>
                                                İndiriliyor... %{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' }}>MariaDB Veri İçe Aktar</Typography>
                                            <Typography variant="body2" color="text.secondary">
                                                Seçtiğiniz bir .sql veya arşiv dosyasını hızlıca veritabanına yükleyin.
                                            </Typography>
                                        </Box>
                                        <Box>
                                            <Button
                                                variant="contained"
                                                size="large"
                                                onClick={() => setIsMariaDbWizardOpen(true)}
                                                startIcon={<DbIcon />}
                                                sx={{ borderRadius: 2 }}
                                            >
                                                İÇE AKTAR
                                            </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' }}>MariaDB Veri Dışa Aktar</Typography>
                                            <Typography variant="body2" color="text.secondary">
                                                Veritabanlarını .sql veya .sql.gz olarak güvenle yedekleyin.
                                            </Typography>
                                        </Box>
                                        <Box>
                                            <Button
                                                variant="contained"
                                                color="secondary"
                                                size="large"
                                                onClick={() => setIsMariaDbExportWizardOpen(true)}
                                                startIcon={<DbIcon />}
                                                sx={{ borderRadius: 2 }}
                                            >
                                                DIŞA AKTAR
                                            </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' }}>
                                        Projelerim
                                    </Typography>
                                    <Button variant="contained" startIcon={<ProjectIcon />} onClick={() => setIsProjectDialogOpen(true)}>
                                        Yeni Proje Ekle
                                    </Button>
                                </Box>

                                {projects.length === 0 ? (
                                    <Paper sx={{ p: 4, textAlign: 'center', bgcolor: 'rgba(255, 255, 255, 0.03)' }}>
                                        <Typography variant="body1" color="text.secondary">Henüz bir proje eklenmemiş.</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="Düzenle">
                                                                <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="Nginx Ayarları">
                                                                    <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>

                                                        <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)' }
                                                                }}
                                                            >
                                                                Gözat
                                                            </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 ? 'Proje Düzenle' : 'Yeni Proje Ekle'}</DialogTitle>
                    <DialogContent>
                        <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
                            <TextField
                                label="Proje Adı"
                                fullWidth
                                value={newProject.name}
                                onChange={(e) => setNewProject({ ...newProject, name: e.target.value })}
                            />
                            <TextField
                                label="Dosya Yolu"
                                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="Hostname (örn: local.test)"
                                fullWidth
                                value={newProject.host}
                                onChange={(e) => setNewProject({ ...newProject, host: e.target.value })}
                            />
                            <FormControl fullWidth disabled={installedPhpVersions.length === 0}>
                                <InputLabel id="php-version-label">PHP Sürümü</InputLabel>
                                <Select
                                    labelId="php-version-label"
                                    value={newProject.phpVersion}
                                    label="PHP Sürümü"
                                    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="">Önce PHP sürümü indirmelisiniz</MenuItem>
                                    )}
                                </Select>
                            </FormControl>
                            <FormControl fullWidth>
                                <InputLabel id="server-type-label">Web Sunucusu</InputLabel>
                                <Select
                                    labelId="server-type-label"
                                    value={newProject.serverType || 'nginx'}
                                    label="Web Sunucusu"
                                    onChange={(e) => setNewProject({ ...newProject, serverType: e.target.value as any })}
                                >
                                    <MenuItem value="nginx">Nginx</MenuItem>
                                    <MenuItem value="apache">Apache (htaccess desteği)</MenuItem>
                                </Select>
                            </FormControl>
                        </Box>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => {
                            setIsProjectDialogOpen(false)
                            setNewProject({ name: '', path: '', phpVersion: '', mariaDbVersion: '', host: 'localhost', serverType: 'nginx' })
                        }}>İptal</Button>
                        <Button
                            onClick={handleAddProject}
                            variant="contained"
                            disabled={!newProject.name || !newProject.path || installedPhpVersions.length === 0}
                        >
                            {newProject.id ? 'Güncelle' : 'Ekle'}
                        </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">Nginx Yapılandırması (nginx.conf)</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' }}>
                            Dikkat: Hatalı yapılandırma Nginx'in çalışmasını durdurabilir. Değişiklik yapmadan önce test edin.
                        </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)' }}
                        >
                            Yapılandırmayı Test Et
                        </Button>
                        <Button onClick={() => setIsNginxConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.6)' }}>
                            İptal
                        </Button>
                        <Button
                            onClick={handleSaveNginxConfig}
                            variant="contained"
                            startIcon={<SaveIcon />}
                        >
                            Kaydet ve Yeniden Yükle
                        </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">{selectedProjectHost} Nginx Yapılandırması</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' }}>
                            İpucu: Bu yapılandırma sadece {selectedProjectHost} projesi için geçerlidir.
                        </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 ? 'Başarılı' : 'Yapılandırma Hatası',
                                        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>Hata Satırı:</b> ${errorInfo.line}
                                                    </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)' }}
                        >
                            Yapılandırmayı Test Et
                        </Button>
                        <Button onClick={() => setIsProjectNginxConfigOpen(false)} sx={{ color: 'rgba(255,255,255,0.6)' }}>
                            İptal
                        </Button>
                        <Button
                            onClick={handleSaveProjectNginxConfig}
                            variant="contained"
                            startIcon={<SaveIcon />}
                        >
                            Kaydet ve Yeniden Yükle
                        </Button>
                    </DialogActions>
                </Dialog>
                <PhpExtensionManager
                    open={isPhpExtensionsOpen}
                    onClose={() => setIsPhpExtensionsOpen(false)}
                    phpVersion={selectedPhpVersion}
                />
            </Box >
        </>
    )
}

export default App
