<?php
$files = $themeFiles ?? [];
$selected = $selectedFile ?? '';
$content = $fileContent ?? '';
$slug = $themeSlug ?? '';

 
$groups = [];
foreach ($files as $f) {
    $dir = dirname($f);
    if ($dir === '.') $dir = '/';
    $groups[$dir][] = $f;
}
ksort($groups);

 
$ext = $selected ? strtolower(pathinfo($selected, PATHINFO_EXTENSION)) : '';
$modeMap = ['php' => 'php', 'css' => 'css', 'js' => 'javascript', 'json' => 'javascript', 'html' => 'htmlmixed'];
$cmMode = $modeMap[$ext] ?? 'php';
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/theme/dracula.min.css">
<style>
.CodeMirror { height: calc(100vh - 220px); min-height: 300px; font-size: 13px; border-radius: 0 0 8px 8px; }
.file-tree a { display: block; padding: 4px 12px; font-size: 13px; color: #6b7280; text-decoration: none; border-radius: 4px; transition: all .15s; }
.file-tree a:hover { background: #f3f4f6; color: #111827; }
.file-tree a.active { background: #eff6ff; color: #2563eb; font-weight: 500; }
.file-tree-group { margin-bottom: 8px; }
.file-tree-group-label { font-size: 11px; font-weight: 600; text-transform: uppercase; color: #9ca3af; padding: 4px 12px; letter-spacing: 0.05em; }
 
#fileTreeToggle { display: none; }
@media (max-width: 767px) {
    #fileTreeToggle { display: inline-flex; }
    #fileTreePanel { display: none; }
    #fileTreePanel.open { display: block; }
    .CodeMirror { height: calc(100vh - 260px); }
}
</style>


<div class="mb-3 md:hidden">
    <button type="button" id="fileTreeToggle" onclick="document.getElementById('fileTreePanel').classList.toggle('open')"
            class="inline-flex items-center gap-2 px-3 py-2 bg-white border border-gray-200 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 shadow-sm">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 7h18M3 12h18M3 17h18"/></svg>
        Files
        <span class="text-xs text-gray-400">(<?= count($files) ?>)</span>
    </button>
</div>

<div class="flex flex-col md:flex-row gap-4" style="min-height: calc(100vh - 160px);">
    
    <div id="fileTreePanel" class="w-full md:w-64 shrink-0 bg-white rounded-lg shadow-sm border border-gray-200 overflow-y-auto max-h-60 md:max-h-[calc(100vh_-_160px)]">
        <div class="px-4 py-3 border-b border-gray-200">
            <h3 class="text-sm font-semibold text-gray-900"><?= htmlspecialchars($slug) ?></h3>
            <p class="text-xs text-gray-400 mt-0.5"><?= count($files) ?> files</p>
        </div>
        <div class="p-2 file-tree">
            <?php foreach ($groups as $dir => $dirFiles): ?>
                <div class="file-tree-group">
                    <div class="file-tree-group-label"><?= htmlspecialchars($dir === '/' ? 'Root' : $dir) ?></div>
                    <?php foreach ($dirFiles as $f):
                        $basename = basename($f);
                        $isActive = ($f === $selected);
                    ?>
                        <a href="/admin/themes/editor?file=<?= urlencode($f) ?>" class="<?= $isActive ? 'active' : '' ?>" title="<?= htmlspecialchars($f) ?>">
                            <?= htmlspecialchars($basename) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    
    <div class="flex-1 bg-white rounded-lg shadow-sm border border-gray-200 flex flex-col overflow-hidden">
        <?php if ($selected): ?>
            
            <div class="px-3 sm:px-4 py-2.5 border-b border-gray-200 flex items-center justify-between gap-2 bg-gray-50">
                <div class="flex items-center gap-2 sm:gap-3 min-w-0">
                    <span class="text-sm font-medium text-gray-900 truncate"><?= htmlspecialchars($selected) ?></span>
                    <span id="unsavedBadge" class="hidden px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-700">Unsaved</span>
                    <span id="savedBadge" class="hidden px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-700">Saved!</span>
                </div>
                <button type="button" onclick="saveFile()" id="saveBtn"
                        class="shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                    Save
                </button>
            </div>
            
            <div class="flex-1">
                <textarea id="codeEditor"><?= htmlspecialchars($content) ?></textarea>
            </div>
        <?php else: ?>
            <div class="flex-1 flex items-center justify-center text-gray-400">
                <div class="text-center">
                    <svg class="w-12 h-12 mx-auto mb-3" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5"/>
                    </svg>
                    <p class="text-sm">Select a file from the tree to edit</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($selected): ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/css/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/htmlmixed/htmlmixed.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/clike/clike.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/php/php.min.js"></script>
<script>
(function() {
    var csrfToken = '<?= Router::csrfToken() ?>';
    var currentFile = <?= json_encode($selected) ?>;
    var isDirty = false;
    var savedTimeout = null;

    var editor = CodeMirror.fromTextArea(document.getElementById('codeEditor'), {
        mode: '<?= $cmMode === 'php' ? 'application/x-httpd-php' : $cmMode ?>',
        theme: 'dracula',
        lineNumbers: true,
        indentUnit: 4,
        tabSize: 4,
        indentWithTabs: false,
        lineWrapping: true,
        matchBrackets: true,
        autoCloseBrackets: true
    });

    editor.on('change', function() {
        if (!isDirty) {
            isDirty = true;
            document.getElementById('unsavedBadge').classList.remove('hidden');
            document.getElementById('savedBadge').classList.add('hidden');
        }
    });

    window.saveFile = function() {
        var btn = document.getElementById('saveBtn');
        btn.disabled = true;
        btn.textContent = 'Saving...';

        var formData = new FormData();
        formData.append('file', currentFile);
        formData.append('content', editor.getValue());
        formData.append('csrf_token', csrfToken);

        fetch('/admin/themes/editor/save', {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            btn.disabled = false;
            btn.innerHTML = '<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg> Save';
            if (data.success) {
                isDirty = false;
                document.getElementById('unsavedBadge').classList.add('hidden');
                document.getElementById('savedBadge').classList.remove('hidden');
                if (savedTimeout) clearTimeout(savedTimeout);
                savedTimeout = setTimeout(function() {
                    document.getElementById('savedBadge').classList.add('hidden');
                }, 3000);
            } else {
                alert('Error: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(function() {
            btn.disabled = false;
            btn.innerHTML = '<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg> Save';
            alert('Network error. Please try again.');
        });
    };

    
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            if (isDirty) saveFile();
        }
    });

    
    window.addEventListener('beforeunload', function(e) {
        if (isDirty) {
            e.preventDefault();
            e.returnValue = '';
        }
    });
})();
</script>
<?php endif; ?>
