<?php
// admin/styles.php
include __DIR__ . '/../includes/header.php'; // $lang_admin, $lang_alerts should be available

if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ADMIN_NO_PERMISSION'], 'danger');
  redirectTo(getCleanUrl('index'));
}

// Function to scan for CSS files dynamically
function getCSSFiles($directory) {
    $cssFiles = [];
    $rootDir = $directory;
    if (is_dir($rootDir)) {
        $files = glob($rootDir . '/style_*.css');
        foreach ($files as $file) {
            $fileName = basename($file);
            $cssFiles[$fileName] = $fileName;
        }
    }
    return $cssFiles;
}

$available_css_files = getCSSFiles(__DIR__ . '/..');
$selected_file = isset($_GET['file']) ? $_GET['file'] : '';
$success_message = '';
$error_message = '';

if (empty($selected_file) && !empty($available_css_files)) {
    $selected_file = array_keys($available_css_files)[0];
}

if (!empty($selected_file) && !array_key_exists($selected_file, $available_css_files)) {
    $error_message = $lang_alerts['ALERT_STYLES_INVALID_CSS_FILE'];
    $selected_file = '';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_new_css'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $error_message = $lang_alerts['ALERT_INVALID_CSRF_TRY_AGAIN'];
    } else {
        $template_file = $_POST['template_file'];
        $new_file_name = sanitizeInput($_POST['new_file_name']);
        
        if (!array_key_exists($template_file, $available_css_files)) {
            $error_message = $lang_alerts['ALERT_STYLES_INVALID_TEMPLATE_FILE'];
        } elseif (empty($new_file_name)) {
            $error_message = $lang_alerts['ALERT_STYLES_NEW_FILE_NAME_REQUIRED'];
        } elseif (!preg_match('/^[a-zA-Z0-9_-]+$/', $new_file_name)) {
            $error_message = $lang_alerts['ALERT_STYLES_INVALID_FILE_NAME_CHARS'];
        } else {
            if (!str_starts_with($new_file_name, 'style_')) {
                $new_file_name = 'style_' . $new_file_name;
            }
            if (!str_ends_with($new_file_name, '.css')) {
                $new_file_name .= '.css';
            }
            $template_path = __DIR__ . '/../' . $template_file;
            $new_file_path = __DIR__ . '/../' . $new_file_name;
            
            if (file_exists($new_file_path)) {
                $error_message = $lang_alerts['ALERT_STYLES_FILE_EXISTS'];
            } else {
                try {
                    if (file_exists($template_path)) {
                        $template_content = file_get_contents($template_path);
                        $header_comment = "/* \n";
                        $header_comment .= " * Custom CSS File: " . $new_file_name . "\n";
                        $header_comment .= " * Created: " . date('Y-m-d H:i:s') . "\n";
                        $header_comment .= " * Based on: " . basename($template_file) . "\n";
                        $header_comment .= " * \n";
                        $header_comment .= " * Add your custom styles below:\n";
                        $header_comment .= " */\n\n";
                        $new_content = $header_comment . $template_content;
                        
                        if (file_put_contents($new_file_path, $new_content) !== false) {
                            $_SESSION['alert'] = displayAlert(sprintf($lang_alerts['ALERT_STYLES_FILE_CREATED_SUCCESS'], $new_file_name), 'success');
                            redirectTo('admin/styles?file=' . urlencode($new_file_name));
                        } else {
                            $error_message = $lang_alerts['ALERT_STYLES_FILE_CREATE_FAILED_PERMISSIONS'];
                        }
                    } else {
                        $error_message = $lang_alerts['ALERT_STYLES_TEMPLATE_NOT_FOUND'];
                    }
                } catch (Exception $e) {
                    $error_message = sprintf($lang_alerts['ALERT_STYLES_FILE_CREATE_ERROR'], $e->getMessage());
                }
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_css'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $error_message = $lang_alerts['ALERT_INVALID_CSRF_TRY_AGAIN'];
    } else {
        $file_to_save = $_POST['css_file'];
        $content = $_POST['css_content'];
        
        if (!array_key_exists($file_to_save, $available_css_files)) {
            $error_message = $lang_alerts['ALERT_STYLES_INVALID_CSS_FILE'];
        } else {
            $file_path = __DIR__ . '/../' . $file_to_save;
            $backup_path = __DIR__ . '/../backups/css/';
            if (!is_dir($backup_path)) {
                mkdir($backup_path, 0755, true);
            }
            $backup_file = $backup_path . basename($file_to_save) . '_' . date('Y-m-d_H-i-s') . '.backup';
            
            try {
                if (file_exists($file_path)) {
                    copy($file_path, $backup_file);
                }
                if (file_put_contents($file_path, $content) !== false) {
                    $success_message = sprintf($lang_alerts['ALERT_STYLES_FILE_SAVED_SUCCESS_BACKUP'], basename($backup_file));
                } else {
                    $error_message = $lang_alerts['ALERT_STYLES_FILE_SAVE_FAILED_PERMISSIONS'];
                }
            } catch (Exception $e) {
                $error_message = sprintf($lang_alerts['ALERT_STYLES_FILE_SAVE_ERROR'], $e->getMessage());
            }
        }
    }
}

$current_content = '';
if (!empty($selected_file)) {
    $file_path = __DIR__ . '/../' . $selected_file;
    if (file_exists($file_path)) {
        $current_content = file_get_contents($file_path);
    } else {
        $error_message = sprintf($lang_alerts['ALERT_STYLES_FILE_NOT_FOUND_ERROR'], $selected_file);
    }
}

// For JS messages
$js_lang = [
    'confirm_unsaved_switch' => addslashes($lang_admin['ADMIN_STYLES_JS_CONFIRM_UNSAVED_SWITCH']),
    'confirm_reset_changes' => addslashes($lang_admin['ADMIN_STYLES_JS_CONFIRM_RESET_CHANGES']),
    'alert_no_changes_to_save' => addslashes($lang_admin['ADMIN_STYLES_JS_ALERT_NO_CHANGES_TO_SAVE']),
    'confirm_save_with_backup' => addslashes($lang_admin['ADMIN_STYLES_JS_CONFIRM_SAVE_WITH_BACKUP']),
    'search_no_matches' => addslashes($lang_admin['ADMIN_STYLES_JS_SEARCH_NO_MATCHES']),
    'search_match_count' => addslashes($lang_admin['ADMIN_STYLES_JS_SEARCH_MATCH_COUNT']),
    'search_error' => addslashes($lang_admin['ADMIN_STYLES_JS_SEARCH_ERROR']),
    'editor_info_line_col' => addslashes($lang_admin['ADMIN_STYLES_EDITOR_INFO_LINE_COL']),
    'editor_info_chars' => addslashes($lang_admin['ADMIN_STYLES_EDITOR_INFO_CHARS']),
];

?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/styles/atom-one-dark.min.css">
<style>
.css-editor-container{position:relative}.search-overlay{position:absolute;top:10px;right:10px;z-index:1000;background:rgba(255,255,255,.95);border:1px solid #ddd;border-radius:6px;padding:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);display:none;visibility:hidden;opacity:0;transition:opacity .2s ease-in-out}.search-overlay.visible{display:block!important;visibility:visible!important;opacity:1!important;z-index:1001!important}.search-overlay[style*="display: block"]{visibility:visible!important;opacity:1!important}.search-controls{display:flex;gap:5px;align-items:center}.search-input{width:200px;padding:4px 8px;border:1px solid #ccc;border-radius:4px;font-size:12px}.search-buttons{display:flex;gap:2px}.search-btn{padding:4px 8px;border:1px solid #ccc;background:white;border-radius:3px;cursor:pointer;font-size:11px}.search-btn:hover{background:#f0f0f0}.search-results{font-size:11px;color:#666;margin-left:5px}.editor-container{position:relative;border:1px solid #ddd;border-radius:6px;overflow:hidden}.editor-toolbar{background:#f8f9fa;border-bottom:1px solid #ddd;padding:8px 12px;display:flex;justify-content:space-between;align-items:center;gap:10px}.editor-actions{display:flex;gap:5px}.editor-btn{padding:4px 8px;border:1px solid #ccc;background:white;border-radius:3px;cursor:pointer;font-size:12px;display:flex;align-items:center;gap:4px}.editor-btn:hover{background:#e9ecef}.editor-info{font-size:12px;color:#666;margin-left:auto}.code-editor-wrapper{position:relative;background:#282c34;min-height:500px}.code-editor{font-family:'Consolas','Monaco','Courier New',monospace;font-size:14px;line-height:1.5;border:none;resize:vertical;min-height:500px;background:transparent;position:absolute;top:0;left:0;width:100%;height:100%;z-index:2;color:transparent;caret-color:#fff;padding:1em;outline:none}.syntax-highlight{position:absolute;top:0;left:0;width:100%;height:100%;z-index:1;pointer-events:none;overflow:hidden}.syntax-highlight pre{margin:0;border:none;border-radius:0;font-family:'Consolas','Monaco','Courier New',monospace;font-size:14px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word;height:100%;min-height:500px;padding:1em;overflow:hidden}.syntax-highlight pre code.hljs,.syntax-highlight pre code.language-css,.syntax-highlight pre code{padding:0;display:block;background:transparent;font-family:'Consolas','Monaco','Courier New',monospace;font-size:14px;line-height:1.5}.syntax-highlight pre code.hljs{color:#abb2bf}.search-highlight{background-color:#ffeb3b!important;color:#000!important;padding:1px 2px;border-radius:2px;font-weight:700!important}.search-highlight.current{background-color:#ff9800!important;color:#fff!important;box-shadow:0 0 3px rgba(255,152,0,.8)}.modal-backdrop{background-color:rgba(0,0,0,.5)}.new-css-form{background:white;border-radius:8px;padding:20px;max-width:500px;margin:0 auto}
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2><i class="bi bi-palette me-2"></i><?php echo $lang_admin['ADMIN_STYLES_PAGE_TITLE']; ?></h2>
        <p class="text-muted mb-0"><?php echo $lang_admin['ADMIN_STYLES_PAGE_DESCRIPTION']; ?></p>
    </div>
    <a href="<?php echo getCleanUrl('admin/dashboard'); ?>" class="btn btn-outline-primary">
        <i class="bi bi-arrow-left"></i> <?php echo $lang_admin['ADMIN_SETTINGS_BTN_BACK_TO_DASHBOARD']; ?>
    </a>
</div>

<?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill me-2"></i><?php echo htmlspecialchars($success_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; // General close text ?>"></button>
    </div>
<?php endif; ?>
<?php if ($error_message): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo htmlspecialchars($error_message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?>"></button>
    </div>
<?php endif; ?>

<div class="alert alert-warning" role="alert">
    <h6 class="alert-heading"><i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo $lang_admin['ADMIN_STYLES_CAUTION_ADVANCED_TITLE']; ?></h6>
    <p class="mb-0"><?php echo $lang_admin['ADMIN_STYLES_CAUTION_ADVANCED_TEXT']; ?>
        <br><small class="text-muted"><?php echo $lang_admin['ADMIN_STYLES_CAUTION_ADVANCED_BACKUP_NOTE']; ?></small>
    </p>
</div>

<?php if (empty($available_css_files)): ?>
    <div class="alert alert-info" role="alert">
        <h6 class="alert-heading"><i class="bi bi-info-circle-fill me-2"></i><?php echo $lang_admin['ADMIN_STYLES_NO_FILES_FOUND_TITLE']; ?></h6>
        <p class="mb-0"><?php echo $lang_admin['ADMIN_STYLES_NO_FILES_FOUND_TEXT']; ?></p>
    </div>
<?php endif; ?>

<form method="post" id="cssForm">
    <?php echo get_csrf_input_field(); ?>
    <input type="hidden" name="css_file" value="<?php echo htmlspecialchars($selected_file); ?>">
    <div class="card">
        <div class="card-header">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <label for="file_selector" class="form-label mb-0"><i class="bi bi-file-earmark-code me-2"></i><?php echo $lang_admin['ADMIN_STYLES_LABEL_SELECT_CSS_FILE']; ?></label>
                    <?php if (!empty($available_css_files)): ?>
                        <select id="file_selector" class="form-select mt-2" onchange="changeCSSFile()">
                            <option value=""><?php echo $lang_admin['ADMIN_STYLES_SELECT_CSS_FILE_PLACEHOLDER']; ?></option>
                            <?php foreach ($available_css_files as $file => $name): ?>
                                <option value="<?php echo htmlspecialchars($file); ?>" <?php echo $file === $selected_file ? 'selected' : ''; ?>><?php echo htmlspecialchars($name); ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php else: ?>
                        <p class="text-muted mt-2"><?php echo $lang_admin['ADMIN_STYLES_NO_CSS_FILES_AVAILABLE']; ?></p>
                    <?php endif; ?>
                </div>
                <div class="col-md-6 text-end">
                    <?php if (!empty($selected_file)): ?>
                        <small class="text-muted"><?php echo sprintf($lang_admin['ADMIN_STYLES_CURRENT_FILE_LABEL'], htmlspecialchars($selected_file)); ?></small>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <?php if (!empty($selected_file)): ?>
        <div class="card-body p-0">
            <div class="css-editor-container">
                <div class="search-overlay" id="searchOverlay">
                    <div class="search-controls">
                        <input type="text" class="search-input" id="searchInput" placeholder="<?php echo $lang_admin['ADMIN_STYLES_SEARCH_PLACEHOLDER']; ?>" />
                        <div class="search-buttons">
                            <button type="button" class="search-btn" id="searchPrev" title="<?php echo $lang_admin['ADMIN_STYLES_SEARCH_BTN_PREVIOUS_TITLE']; ?>">↑</button>
                            <button type="button" class="search-btn" id="searchNext" title="<?php echo $lang_admin['ADMIN_STYLES_SEARCH_BTN_NEXT_TITLE']; ?>">↓</button>
                            <button type="button" class="search-btn" id="searchClose" title="<?php echo $lang_admin['ADMIN_STYLES_SEARCH_BTN_CLOSE_TITLE']; ?>">×</button>
                        </div>
                        <span class="search-results" id="searchResults"></span>
                    </div>
                </div>
                <div class="editor-toolbar">
                    <div class="editor-actions">
                        <button type="button" class="editor-btn" id="searchToggle" title="<?php echo $lang_admin['ADMIN_STYLES_EDITOR_BTN_SEARCH']; ?> (Ctrl+F)"><i class="bi bi-search"></i> <?php echo $lang_admin['ADMIN_STYLES_EDITOR_BTN_SEARCH']; ?></button>
                        <button type="button" class="editor-btn" id="fullscreenToggle" title="<?php echo $lang_admin['ADMIN_STYLES_EDITOR_BTN_FULLSCREEN']; ?> (F11)"><i class="bi bi-arrows-fullscreen"></i> <?php echo $lang_admin['ADMIN_STYLES_EDITOR_BTN_FULLSCREEN']; ?></button>
                    </div>
                    <div class="editor-info">
                        <span id="cursorPosition"><?php echo sprintf($lang_admin['ADMIN_STYLES_EDITOR_INFO_LINE_COL'], 1, 1); ?></span> |
                        <span id="charCount"><?php echo sprintf($lang_admin['ADMIN_STYLES_EDITOR_INFO_CHARS'], number_format(strlen($current_content))); ?></span>
                    </div>
                </div>
                <div class="code-editor-wrapper">
                    <div class="syntax-highlight" id="syntaxHighlight"><pre><code id="highlightedCode"><?php echo htmlspecialchars($current_content); ?></code></pre></div>
                    <textarea name="css_content" id="css_content" class="code-editor" oninput="updateSyntaxHighlighting()" onscroll="syncScroll()" spellcheck="false"><?php echo htmlspecialchars($current_content); ?></textarea>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="card-footer">
            <div class="d-flex justify-content-between align-items-center">
                <small class="text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    <?php echo sprintf($lang_admin['ADMIN_STYLES_FOOTER_AUTOSAVE_STATUS'], '<span id="autoSaveStatus">' . $lang_admin['ADMIN_STYLES_AUTOSAVE_STATUS_DISABLED'] . '</span>'); ?> |
                    <?php echo sprintf($lang_admin['ADMIN_STYLES_FOOTER_LAST_SAVED'], '<span id="lastSaved">' . $lang_admin['ADMIN_STYLES_LAST_SAVED_NEVER'] . '</span>'); ?>
                </small>
                <div>
                    <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#newCSSModal">
                        <i class="bi bi-plus-circle"></i> <?php echo $lang_admin['ADMIN_STYLES_BTN_NEW_CSS_FILE']; ?>
                    </button>
                    <?php if (!empty($selected_file)): ?>
                        <button type="button" class="btn btn-outline-secondary me-2" onclick="resetContent()">
                            <i class="bi bi-arrow-clockwise"></i> <?php echo $lang_admin['ADMIN_STYLES_BTN_RESET_CONTENT']; ?>
                        </button>
                        <button type="submit" name="save_css" id="save_button" class="btn btn-primary" disabled>
                            <i class="bi bi-floppy"></i> <?php echo $lang_admin['ADMIN_STYLES_BTN_SAVE_CHANGES']; ?>
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</form>

<div class="modal fade" id="newCSSModal" tabindex="-1" aria-labelledby="newCSSModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="newCSSModalLabel"><i class="bi bi-plus-circle me-2"></i><?php echo $lang_admin['ADMIN_STYLES_MODAL_CREATE_TITLE']; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?>"></button>
            </div>
            <form method="post">
                <?php echo get_csrf_input_field(); ?>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="new_file_name" class="form-label"><?php echo $lang_admin['ADMIN_STYLES_MODAL_NEW_FILE_NAME_LABEL']; ?></label>
                        <div class="input-group">
                            <span class="input-group-text">style_</span>
                            <input type="text" class="form-control" id="new_file_name" name="new_file_name" placeholder="<?php echo $lang_admin['ADMIN_STYLES_MODAL_NEW_FILE_NAME_PLACEHOLDER']; ?>" required>
                            <span class="input-group-text">.css</span>
                        </div>
                        <div class="form-text"><?php echo $lang_admin['ADMIN_STYLES_MODAL_NEW_FILE_NAME_HELP']; ?><br><strong><?php echo $lang_admin['ADMIN_STYLES_MODAL_NEW_FILE_NAME_EXAMPLE']; ?></strong></div>
                    </div>
                    <div class="mb-3">
                        <label for="template_file" class="form-label"><?php echo $lang_admin['ADMIN_STYLES_MODAL_BASE_TEMPLATE_LABEL']; ?></label>
                        <select class="form-select" id="template_file" name="template_file" required>
                            <option value=""><?php echo $lang_admin['ADMIN_STYLES_MODAL_SELECT_TEMPLATE_PLACEHOLDER']; ?></option>
                            <?php foreach ($available_css_files as $file => $name): ?>
                                <option value="<?php echo htmlspecialchars($file); ?>"><?php echo htmlspecialchars($name); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text"><?php echo $lang_admin['ADMIN_STYLES_MODAL_TEMPLATE_HELP']; ?></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo $lang_admin['ADMIN_USERS_MODAL_BTN_CANCEL']; ?></button>
                    <button type="submit" name="create_new_css" class="btn btn-success"><i class="bi bi-plus-circle"></i> <?php echo $lang_admin['ADMIN_STYLES_MODAL_BTN_CREATE_CSS_FILE']; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="card mt-4">
    <div class="card-header">
        <h6 class="mb-0"><i class="bi bi-archive me-2"></i><?php echo $lang_admin['ADMIN_STYLES_BACKUP_INFO_TITLE']; ?></h6>
    </div>
    <div class="card-body">
        <p class="mb-2"><?php echo sprintf($lang_admin['ADMIN_STYLES_BACKUP_INFO_PATH'], '<code>/backups/css/</code>'); ?></p>
        <small class="text-muted"><?php echo $lang_admin['ADMIN_STYLES_BACKUP_INFO_DETAILS']; ?></small>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js"></script>
<script>
const lang = <?php echo json_encode($js_lang); ?>;

let cssEditor;
let originalContent = '';
let currentSelectedFile = '<?php echo htmlspecialchars($selected_file); ?>';

document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        initializeHighlightJS();
        cssEditor = new CSSEditor();
        originalContent = document.getElementById('css_content') ? document.getElementById('css_content').value : '';
        updateSyntaxHighlighting();
    }, 100);
});

function initializeHighlightJS() {
    if (typeof hljs !== 'undefined') {
        hljs.configure({ ignoreUnescapedHTML: true, languages: ['css', 'scss', 'less'] });
        return true;
    }
    return false;
}

function updateSyntaxHighlighting() {
    const textarea = document.getElementById('css_content');
    const highlightedCode = document.getElementById('highlightedCode');
    if (!textarea || !highlightedCode || typeof hljs === 'undefined') return;
    const content = textarea.value;
    highlightedCode.removeAttribute('data-highlighted');
    highlightedCode.className = '';
    highlightedCode.textContent = content;
    try {
        const result = hljs.highlight(content, { language: 'css' });
        highlightedCode.innerHTML = result.value;
        highlightedCode.className = 'hljs language-css';
    } catch (error) {
        highlightedCode.textContent = content;
        highlightedCode.className = 'hljs';
    }
    if (cssEditor) {
        cssEditor.updateEditorInfo();
        cssEditor.detectChanges();
    }
}

function syncScroll() {
    const textarea = document.getElementById('css_content');
    const syntaxHighlight = document.getElementById('syntaxHighlight');
    const syntaxPre = syntaxHighlight.querySelector('pre');
    if (syntaxPre) {
        syntaxPre.scrollTop = textarea.scrollTop;
        syntaxPre.scrollLeft = textarea.scrollLeft;
    }
}

function changeCSSFile() {
    const selector = document.getElementById('file_selector');
    const selectedFile = selector.value;
    if (cssEditor && cssEditor.hasUnsavedChanges()) {
        if (!confirm(lang.confirm_unsaved_switch)) {
            selector.value = currentSelectedFile;
            return;
        }
    }
    window.location.href = selectedFile ? 'styles?file=' + encodeURIComponent(selectedFile) : 'styles';
}

function resetContent() {
    if (confirm(lang.confirm_reset_changes)) {
        const textarea = document.getElementById('css_content');
        textarea.value = originalContent;
        updateSyntaxHighlighting();
    }
}

class CSSEditor {
    constructor() {
        this.textarea = document.getElementById('css_content');
        this.searchOverlay = document.getElementById('searchOverlay');
        this.searchInput = document.getElementById('searchInput');
        this.searchResults = document.getElementById('searchResults');
        this.cursorPosition = document.getElementById('cursorPosition');
        this.charCount = document.getElementById('charCount');
        this.searchMatches = [];
        this.currentMatchIndex = -1;
        this.searchTimeout = null;
        if (this.textarea) {
            this.bindEvents();
            this.updateEditorInfo();
        }
    }
    bindEvents() {
        document.getElementById('searchToggle').addEventListener('click', () => this.toggleSearch());
        document.getElementById('fullscreenToggle').addEventListener('click', () => this.toggleFullscreen());
        document.getElementById('searchClose').addEventListener('click', () => this.closeSearch());
        document.getElementById('searchPrev').addEventListener('click', () => this.searchPrevious());
        document.getElementById('searchNext').addEventListener('click', () => this.searchNext());
        this.searchInput.addEventListener('input', () => this.performSearch());
        this.searchInput.addEventListener('keydown', (e) => this.handleSearchKeydown(e));
        this.textarea.addEventListener('keydown', (e) => this.handleKeydown(e));
        this.textarea.addEventListener('click', () => { this.updateCursorPosition(); if (this.searchMatches.length > 0) this.closeSearch(); });
        this.textarea.addEventListener('keyup', () => this.updateCursorPosition());
        document.addEventListener('keydown', (e) => this.handleGlobalKeydown(e));
    }
    toggleSearch() {
        const isVisible = this.searchOverlay.classList.contains('visible');
        if (!isVisible) {
            this.searchOverlay.style.display = 'block';
            this.searchOverlay.style.visibility = 'visible';
            this.searchOverlay.style.opacity = '1';
            this.searchOverlay.style.zIndex = '1001';
            this.searchOverlay.classList.add('visible');
            setTimeout(() => { this.searchInput.focus(); this.searchInput.select(); }, 50);
        } else { this.closeSearch(); }
    }
    closeSearch() {
        this.searchOverlay.classList.remove('visible');
        this.searchOverlay.style.visibility = 'hidden';
        this.searchOverlay.style.opacity = '0';
        setTimeout(() => { this.searchOverlay.style.display = 'none'; }, 200);
        this.clearSearchHighlights();
        this.textarea.focus();
    }
    performSearch() {
        const query = this.searchInput.value;
        if (!query || query.length < 2) { this.clearSearchHighlights(); this.searchResults.textContent = ''; return; }
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(() => { this.doSearch(query); }, 300);
    }
    doSearch(query) {
        try {
            const content = this.textarea.value;
            const regex = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
            this.searchMatches = []; let match; let matchCount = 0; const maxMatches = 100;
            while ((match = regex.exec(content)) !== null && matchCount < maxMatches) {
                this.searchMatches.push({ start: match.index, end: match.index + match[0].length, text: match[0] });
                matchCount++; if (match[0].length === 0) regex.lastIndex++;
            }
            this.currentMatchIndex = this.searchMatches.length > 0 ? 0 : -1;
            this.updateSearchResults();
            if (this.currentMatchIndex >= 0) this.highlightCurrentMatch();
        } catch (error) { this.searchResults.textContent = lang.search_error; }
    }
    searchNext() { if (this.searchMatches.length === 0) return; this.currentMatchIndex = (this.currentMatchIndex + 1) % this.searchMatches.length; this.highlightCurrentMatch(); this.updateSearchResults(); }
    searchPrevious() { if (this.searchMatches.length === 0) return; this.currentMatchIndex = this.currentMatchIndex <= 0 ? this.searchMatches.length - 1 : this.currentMatchIndex - 1; this.highlightCurrentMatch(); this.updateSearchResults(); }
    highlightCurrentMatch() {
        if (this.currentMatchIndex >= 0 && this.currentMatchIndex < this.searchMatches.length) {
            const match = this.searchMatches[this.currentMatchIndex];
            const textBeforeMatch = this.textarea.value.substring(0, match.start);
            const lineNumber = textBeforeMatch.split('\n').length;
            const lineHeight = parseInt(window.getComputedStyle(this.textarea).lineHeight) || 20;
            const scrollTop = Math.max(0, (lineNumber - 1) * lineHeight - this.textarea.clientHeight / 2);
            this.textarea.scrollTop = scrollTop;
            syncScroll(); this.addVisualHighlight(match);
        }
    }
    addVisualHighlight(match) {
        try {
            const highlightedCode = document.getElementById('highlightedCode'); if (!highlightedCode) return;
            this.removeVisualHighlights(); const content = this.textarea.value; const matchText = content.substring(match.start, match.end);
            let html = highlightedCode.innerHTML; const escapedMatch = matchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const regex = new RegExp(`(${escapedMatch})`, 'gi'); let currentOccurrence = 0;
            html = html.replace(regex, (matchStr) => {
                if (currentOccurrence === this.currentMatchIndex) { currentOccurrence++; return `<span class="search-highlight current" data-search-highlight="true">${matchStr}</span>`; }
                currentOccurrence++; return matchStr;
            });
            highlightedCode.innerHTML = html;
        } catch (error) {}
    }
    removeVisualHighlights() {
        const highlightedCode = document.getElementById('highlightedCode');
        if (highlightedCode) { let html = highlightedCode.innerHTML; html = html.replace(/<span class="search-highlight[^"]*"[^>]*>(.*?)<\/span>/g, '$1'); highlightedCode.innerHTML = html; }
    }
    updateSearchResults() {
        if (this.searchMatches.length === 0) { this.searchResults.textContent = lang.search_no_matches; }
        else { this.searchResults.textContent = lang.search_match_count.replace('%s', this.currentMatchIndex + 1).replace('%s', this.searchMatches.length); }
    }
    clearSearchHighlights() { this.searchMatches = []; this.currentMatchIndex = -1; this.searchResults.textContent = ''; this.removeVisualHighlights(); if (this.textarea) this.textarea.setSelectionRange(0, 0); }
    handleSearchKeydown(e) { if (e.key === 'Enter') { e.preventDefault(); if (this.searchMatches.length > 0) { if (e.shiftKey) this.searchPrevious(); else this.searchNext(); } } else if (e.key === 'Escape') this.closeSearch(); }
    toggleFullscreen() { const container = document.querySelector('.css-editor-container'); if (!document.fullscreenElement) { if (container.requestFullscreen) container.requestFullscreen().catch(err => {}); } else { if (document.exitFullscreen) document.exitFullscreen(); } }
    updateCursorPosition() { const start = this.textarea.selectionStart; const content = this.textarea.value.substring(0, start); const lines = content.split('\n'); this.cursorPosition.textContent = lang.editor_info_line_col.replace('%s', lines.length).replace('%s', lines[lines.length - 1].length + 1); }
    updateEditorInfo() { this.charCount.textContent = lang.editor_info_chars.replace('%s', this.textarea.value.length.toLocaleString()); this.updateCursorPosition(); }
    handleKeydown(e) { if (e.key === 'Tab') { e.preventDefault(); const start = this.textarea.selectionStart; const end = this.textarea.selectionEnd; const value = this.textarea.value; if (e.shiftKey) { const lineStart = value.lastIndexOf('\n', start - 1) + 1; const lineContent = value.substring(lineStart, start); if (lineContent.startsWith('    ')) { this.textarea.value = value.substring(0, lineStart) + lineContent.substring(4) + value.substring(start); this.textarea.setSelectionRange(start - 4, end - 4); } } else { this.textarea.value = value.substring(0, start) + '    ' + value.substring(end); this.textarea.setSelectionRange(start + 4, start + 4); } updateSyntaxHighlighting(); } }
    handleGlobalKeydown(e) { if (e.ctrlKey && e.key === 'f') { e.preventDefault(); this.toggleSearch(); } if (e.key === 'F11') { e.preventDefault(); this.toggleFullscreen(); } if (e.key === 'Escape' && this.searchOverlay.style.display === 'block') this.closeSearch(); }
    detectChanges() { const currentContent = this.textarea.value; const saveButton = document.getElementById('save_button'); if (saveButton) { const hasChanges = currentContent !== originalContent; saveButton.disabled = !hasChanges; } }
    hasUnsavedChanges() { return this.textarea.value !== originalContent; }
}
window.addEventListener('beforeunload', function(e) { if (cssEditor && cssEditor.hasUnsavedChanges()) { e.preventDefault(); e.returnValue = ''; } });
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('cssForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            if (cssEditor && !cssEditor.hasUnsavedChanges()) { e.preventDefault(); alert(lang.alert_no_changes_to_save); return; }
            if (!confirm(lang.confirm_save_with_backup)) { e.preventDefault(); return; }
        });
    }
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?> 