<?php
$docsDir = __DIR__ . '/docs/ar';
if (!is_dir($docsDir)) {
    $docsDir = __DIR__ . '/../docs/ar';
}

$files = glob($docsDir . '/*.md');
usort($files, fn($a, $b) => basename($a) <=> basename($b));

// Handle API requests FIRST before any other processing
if (isset($_GET['api'])) {
    error_reporting(0);
    ini_set('display_errors', '0');
    while (ob_get_level()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');

    if ($_GET['api'] === 'search') {
        $q = $_GET['q'] ?? '';
        $q = trim($q);
        $results = [];
        if (strlen($q) > 0) {
            foreach ($files as $f) {
                $raw = @file_get_contents($f);
                if (!$raw) continue;
                $bname = basename($f, '.md');
                preg_match('/^#\s+(.+)$/mu', $raw, $m);
                $fTitle = isset($m[1]) ? preg_replace('/^\d+\s*(?:—|–|-)\s*/u', '', $m[1]) : $bname;
                $lines = explode("\n", $raw);
                $hits = [];
                foreach ($lines as $line) {
                    if (strpos($line, $q) !== false) {
                        $hits[] = trim($line);
                        if (count($hits) >= 4) break;
                    }
                }
                if (!empty($hits)) {
                    $results[] = ['slug' => $bname, 'title' => $fTitle, 'matches' => $hits, 'count' => count($hits)];
                }
            }
        }
        echo json_encode($results, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
        exit;
    }

    if ($_GET['api'] === 'content') {
        $slug = $_GET['slug'] ?? '';
        foreach ($files as $f) {
            $bname = basename($f, '.md');
            if ($bname === $slug) {
                $raw = file_get_contents($f);
                preg_match('/^#\s+(.+)$/mu', $raw, $m);
                $title = preg_replace('/^\d+\s*(?:—|–|-)\s*/u', '', $m[1] ?? $bname);
                echo json_encode(['content' => $raw, 'title' => $title], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
                exit;
            }
        }
        echo json_encode(['content' => '', 'title' => '']);
        exit;
    }

    echo json_encode(['error' => 'unknown api']);
    exit;
}

// Build navigation (only for HTML page rendering)
$nav = [];
foreach ($files as $file) {
    $basename = basename($file, '.md');
    $content = file_get_contents($file);
    preg_match('/^#\s+(.+)$/mu', $content, $matches);
    $title = $matches[1] ?? $basename;
    $title = preg_replace('/^\d+\s*(?:—|–|-)\s*/u', '', $title);
    $nav[] = ['slug' => $basename, 'title' => $title];
}

$navJson = json_encode($nav, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
$defaultSlug = $nav[0]['slug'] ?? '';
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EL-Captain Docs</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
    <style>
:root {
    --bg-base: #050506;
    --bg-elevated: #0c0c0e;
    --bg-surface: #121215;
    --bg-card: #18181b;
    --bg-hover: #1f1f23;
    --bg-active: #27272a;
    --border: rgba(255,255,255,0.06);
    --border-hover: rgba(255,255,255,0.12);
    --text-primary: #EDEDEF;
    --text-secondary: #a1a1aa;
    --text-tertiary: #71717a;
    --text-muted: #52525b;
    --accent: #5E6AD2;
    --accent-hover: #6E7AE2;
    --accent-glow: rgba(94,106,210,0.15);
    --accent-subtle: rgba(94,106,210,0.08);
    --orange: #F59E0B;
    --green: #10b981;
    --red: #ef4444;
    --radius-sm: 6px;
    --radius: 10px;
    --radius-lg: 14px;
    --sidebar-w: 280px;
    --content-max: 820px;
    --font: 'Cairo', system-ui, -apple-system, sans-serif;
    --mono: 'JetBrains Mono', ui-monospace, monospace;
    --transition: 200ms cubic-bezier(0.16, 1, 0.3, 1);
}

*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }

html { scroll-behavior: smooth; }

body {
    font-family: var(--font);
    background: var(--bg-base);
    color: var(--text-primary);
    line-height: 1.7;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    overflow-x: hidden;
}

/* ===== LAYOUT ===== */
.app {
    display: flex;
    min-height: 100vh;
}

/* ===== SIDEBAR ===== */
.sidebar {
    position: fixed;
    inset-inline-end: 0;
    top: 0;
    width: var(--sidebar-w);
    height: 100vh;
    background: var(--bg-elevated);
    border-inline-start: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    z-index: 100;
    overflow: hidden;
}

.sidebar-brand {
    padding: 20px;
    border-bottom: 1px solid var(--border);
}

.sidebar-brand h1 {
    font-size: 15px;
    font-weight: 700;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 10px;
}

.sidebar-brand h1 svg {
    width: 22px;
    height: 22px;
    color: var(--accent);
}

.sidebar-brand p {
    font-size: 12px;
    color: var(--text-tertiary);
    margin-top: 4px;
    padding-inline-start: 32px;
}

/* Search */
.sidebar-search {
    padding: 12px 16px;
    border-bottom: 1px solid var(--border);
}

.search-wrap {
    position: relative;
}

.search-wrap svg {
    position: absolute;
    inset-inline-end: 10px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    color: var(--text-muted);
    pointer-events: none;
}

.search-wrap input {
    width: 100%;
    padding: 9px 36px 9px 10px;
    background: var(--bg-surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    color: var(--text-primary);
    font-family: var(--font);
    font-size: 13px;
    outline: none;
    transition: border-color var(--transition);
}

.search-wrap input:focus {
    border-color: var(--accent);
    box-shadow: 0 0 0 3px var(--accent-glow);
}

.search-wrap input::placeholder { color: var(--text-muted); }

.search-kbd {
    position: absolute;
    inset-inline-start: 10px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 11px;
    color: var(--text-muted);
    background: var(--bg-hover);
    border: 1px solid var(--border);
    padding: 1px 5px;
    border-radius: 3px;
    font-family: var(--mono);
    pointer-events: none;
}

/* Nav */
.sidebar-nav {
    flex: 1;
    overflow-y: auto;
    padding: 8px 0;
}

.nav-link {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 8px 16px;
    margin: 1px 8px;
    border-radius: var(--radius-sm);
    color: var(--text-secondary);
    text-decoration: none;
    font-size: 13px;
    font-weight: 500;
    transition: all var(--transition);
    cursor: pointer;
}

.nav-link:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
}

.nav-link.active {
    background: var(--accent-subtle);
    color: var(--accent-hover);
}

.nav-num {
    min-width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    font-weight: 700;
    color: var(--text-muted);
    background: var(--bg-surface);
    border-radius: 5px;
    font-family: var(--mono);
}

.nav-link.active .nav-num {
    background: var(--accent);
    color: #fff;
}

/* ===== MAIN ===== */
.main {
    flex: 1;
    margin-inline-end: var(--sidebar-w);
    min-height: 100vh;
}

/* ===== ARTICLE ===== */
.article {
    max-width: var(--content-max);
    margin: 0 auto;
    padding: 48px 40px 80px;
}

/* Typography */
.article h1 {
    font-size: 28px;
    font-weight: 800;
    color: var(--text-primary);
    margin-bottom: 8px;
    letter-spacing: -0.02em;
}

.article h1 + hr { margin-top: 16px; }

.article h2 {
    font-size: 21px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 40px 0 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--border);
}

.article h3 {
    font-size: 17px;
    font-weight: 600;
    color: var(--orange);
    margin: 28px 0 8px;
}

.article h4 {
    font-size: 15px;
    font-weight: 600;
    color: var(--text-secondary);
    margin: 20px 0 6px;
}

.article p {
    font-size: 15px;
    color: var(--text-secondary);
    margin-bottom: 12px;
    line-height: 1.8;
}

.article strong { color: var(--text-primary); font-weight: 600; }
.article em { color: var(--text-secondary); font-style: italic; }

.article a {
    color: var(--accent-hover);
    text-decoration: none;
    border-bottom: 1px solid transparent;
    transition: border-color var(--transition);
}
.article a:hover { border-bottom-color: var(--accent); }

.article hr {
    border: none;
    border-top: 1px solid var(--border);
    margin: 32px 0;
}

/* Lists */
.article ul, .article ol {
    margin: 8px 0 16px;
    padding-inline-start: 22px;
}

.article li {
    font-size: 15px;
    color: var(--text-secondary);
    margin-bottom: 4px;
    line-height: 1.7;
}

.article li::marker { color: var(--accent); }

/* Blockquotes */
.article blockquote {
    border-inline-start: 3px solid var(--accent);
    padding: 12px 16px;
    margin: 16px 0;
    background: var(--accent-subtle);
    border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
    font-size: 14px;
    color: var(--text-secondary);
}

.article blockquote p { margin: 4px 0; color: var(--text-secondary); }

/* Tables */
.article table {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;
    font-size: 13.5px;
    border: 1px solid var(--border);
    border-radius: var(--radius);
    overflow: hidden;
}

.article thead th {
    background: var(--bg-hover);
    padding: 10px 14px;
    text-align: start;
    font-weight: 600;
    color: var(--text-primary);
    font-size: 12.5px;
    text-transform: none;
    border-bottom: 1px solid var(--border);
}

.article tbody td {
    padding: 9px 14px;
    color: var(--text-secondary);
    border-bottom: 1px solid var(--border);
}

.article tbody tr:last-child td { border-bottom: none; }
.article tbody tr:hover td { background: var(--bg-surface); }

/* Code */
.article code {
    font-family: var(--mono);
    font-size: 12.5px;
    background: var(--bg-surface);
    border: 1px solid var(--border);
    padding: 2px 6px;
    border-radius: 4px;
    color: var(--orange);
}

.article pre {
    background: var(--bg-surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px 20px;
    margin: 16px 0;
    overflow-x: auto;
    direction: ltr;
    text-align: left;
}

.article pre code {
    background: none;
    border: none;
    padding: 0;
    color: var(--text-secondary);
    font-size: 13px;
    line-height: 1.6;
}

/* Mermaid */
.mermaid-wrapper {
    background: var(--bg-surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 28px 20px;
    margin: 24px 0;
    overflow-x: auto;
    direction: ltr;
    text-align: center;
}

/* ===== SEARCH RESULTS ===== */
.search-view {
    max-width: var(--content-max);
    margin: 0 auto;
    padding: 48px 40px;
}

.search-view h2 {
    font-size: 20px;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: 24px;
}

.search-view h2 span {
    font-size: 13px;
    color: var(--text-tertiary);
    font-weight: 500;
    background: var(--bg-surface);
    padding: 3px 10px;
    border-radius: 20px;
    margin-inline-start: 8px;
}

.sr-item {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px 20px;
    margin-bottom: 12px;
    cursor: pointer;
    transition: all var(--transition);
}

.sr-item:hover {
    border-color: var(--accent);
    transform: translateY(-1px);
}

.sr-item h3 {
    font-size: 15px;
    font-weight: 600;
    color: var(--accent-hover);
    margin-bottom: 8px;
}

.sr-match {
    font-size: 13px;
    color: var(--text-tertiary);
    padding: 4px 10px;
    background: var(--bg-base);
    border-radius: var(--radius-sm);
    margin-top: 6px;
    border-inline-start: 2px solid var(--orange);
    line-height: 1.6;
}

.sr-match mark {
    background: rgba(245,158,11,0.2);
    color: var(--orange);
    padding: 0 2px;
    border-radius: 2px;
}

/* ===== LOADING ===== */
.loading {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;
    color: var(--text-muted);
    font-size: 14px;
}

.loading::after {
    content: '';
    width: 20px;
    height: 20px;
    border: 2px solid var(--border);
    border-top-color: var(--accent);
    border-radius: 50%;
    margin-inline-start: 10px;
    animation: spin 0.6s linear infinite;
}

@keyframes spin { to { transform: rotate(360deg); } }

/* ===== MOBILE ===== */
.mobile-btn {
    display: none;
    position: fixed;
    top: 12px;
    inset-inline-end: 12px;
    z-index: 200;
    width: 40px;
    height: 40px;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    color: var(--text-primary);
    cursor: pointer;
    align-items: center;
    justify-content: center;
}

.mobile-btn svg { width: 20px; height: 20px; }

.backdrop {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.6);
    backdrop-filter: blur(4px);
    z-index: 90;
}

@media (max-width: 860px) {
    .sidebar {
        transform: translateX(100%);
        transition: transform 0.3s cubic-bezier(0.16,1,0.3,1);
    }
    .sidebar.open { transform: translateX(0); }
    .main { margin-inline-end: 0; }
    .article, .search-view { padding: 24px 16px 60px; }
    .mobile-btn { display: flex; }
    .backdrop.visible { display: block; }
    .article h1 { font-size: 22px; }
    .article h2 { font-size: 18px; }
}

/* Scrollbar */
::-webkit-scrollbar { width: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--bg-active); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }

/* Print */
@media print {
    .sidebar, .mobile-btn, .backdrop { display: none !important; }
    .main { margin: 0 !important; }
    body { background: #fff; color: #000; }
    .article { max-width: 100%; }
}
    </style>
</head>
<body>

<button class="mobile-btn" id="menuBtn" aria-label="القائمة">
    <svg fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/></svg>
</button>
<div class="backdrop" id="backdrop"></div>

<div class="app">
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-brand">
            <h1>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
                EL-Captain Docs
            </h1>
            <p>دليل نظام الكابتن الشامل</p>
        </div>

        <div class="sidebar-search">
            <div class="search-wrap">
                <svg fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                <input type="text" id="searchInput" placeholder="بحث..." autocomplete="off">
                <span class="search-kbd">/</span>
            </div>
        </div>

        <nav class="sidebar-nav" id="navList">
            <?php foreach ($nav as $i => $item): ?>
            <a class="nav-link" data-slug="<?= htmlspecialchars($item['slug']) ?>">
                <span class="nav-num"><?= str_pad($i, 2, '0', STR_PAD_LEFT) ?></span>
                <?= htmlspecialchars($item['title']) ?>
            </a>
            <?php endforeach; ?>
        </nav>
    </aside>

    <main class="main" id="main">
        <div class="loading" id="loader">جارٍ التحميل</div>
    </main>
</div>

<script src="https://cdn.jsdelivr.net/npm/marked@12/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
<script>
const NAV = <?= $navJson ?>;
const DEFAULT_SLUG = <?= json_encode($defaultSlug) ?>;
let currentSlug = '';

mermaid.initialize({
    startOnLoad: false,
    theme: 'dark',
    themeVariables: {
        primaryColor: '#5E6AD2',
        primaryTextColor: '#EDEDEF',
        primaryBorderColor: '#27272a',
        lineColor: '#71717a',
        secondaryColor: '#18181b',
        tertiaryColor: '#0c0c0e',
        background: '#121215',
        mainBkg: '#18181b',
        nodeBorder: '#27272a',
        clusterBkg: '#0c0c0e',
        clusterBorder: '#27272a',
        titleColor: '#EDEDEF',
        edgeLabelBackground: '#18181b',
        fontFamily: 'Cairo, system-ui, sans-serif'
    },
    flowchart: { curve: 'basis', useMaxWidth: true, htmlLabels: true },
    sequence: { useMaxWidth: true },
});

// Custom marked renderer
const renderer = new marked.Renderer();
renderer.code = function(obj) {
    const code = typeof obj === 'object' ? obj.text : obj;
    const lang = typeof obj === 'object' ? obj.lang : arguments[1];
    if (lang === 'mermaid') {
        return `<div class="mermaid-wrapper"><pre class="mermaid">${code}</pre></div>`;
    }
    return `<pre><code class="language-${lang || ''}">${escapeHtml(code)}</code></pre>`;
};

marked.setOptions({
    renderer,
    gfm: true,
    breaks: false,
    headerIds: true,
});

function escapeHtml(s) {
    return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

// Load page
async function loadPage(slug, pushState = true) {
    if (!slug) slug = DEFAULT_SLUG;
    currentSlug = slug;

    document.getElementById('main').innerHTML = '<div class="loading" id="loader">جارٍ التحميل</div>';

    // Update active nav
    document.querySelectorAll('.nav-link').forEach(el => {
        el.classList.toggle('active', el.dataset.slug === slug);
    });

    const res = await fetch(`?api=content&slug=${encodeURIComponent(slug)}`);
    const data = await res.json();

    if (!data.content) {
        document.getElementById('main').innerHTML = '<div class="article"><h1>الصفحة غير موجودة</h1></div>';
        return;
    }

    const html = marked.parse(data.content);
    document.getElementById('main').innerHTML = `<div class="article">${html}</div>`;
    document.title = `${data.title} — EL-Captain Docs`;

    if (pushState) {
        history.pushState({ slug }, '', `?page=${encodeURIComponent(slug)}`);
    }

    // Render mermaid diagrams
    await mermaid.run({ querySelector: '.mermaid' });

    // Scroll to top
    window.scrollTo(0, 0);
}

// Search
let searchTimeout;
const searchInput = document.getElementById('searchInput');

searchInput.addEventListener('input', () => {
    clearTimeout(searchTimeout);
    const q = searchInput.value.trim();
    if (!q) {
        loadPage(currentSlug || DEFAULT_SLUG, false);
        return;
    }
    searchTimeout = setTimeout(async () => {
        const res = await fetch(`?api=search&q=${encodeURIComponent(q)}`);
        const results = await res.json();
        renderSearch(q, results);
    }, 250);
});

function renderSearch(q, results) {
    let html = `<div class="search-view"><h2>نتائج البحث: "${escapeHtml(q)}" <span>${results.length} ملف</span></h2>`;
    if (!results.length) {
        html += '<p style="color:var(--text-tertiary)">لا توجد نتائج. حاول كلمات أخرى.</p>';
    } else {
        results.forEach(r => {
            html += `<div class="sr-item" onclick="loadPage('${r.slug}'); searchInput.value='';">`;
            html += `<h3>${escapeHtml(r.title)}</h3>`;
            r.matches.slice(0, 3).forEach(m => {
                const highlighted = escapeHtml(m).replace(new RegExp(escapeHtml(q), 'gi'), '<mark>$&</mark>');
                html += `<div class="sr-match">${highlighted}</div>`;
            });
            html += '</div>';
        });
    }
    html += '</div>';
    document.getElementById('main').innerHTML = html;
}

// Nav clicks
document.querySelectorAll('.nav-link').forEach(el => {
    el.addEventListener('click', (e) => {
        e.preventDefault();
        searchInput.value = '';
        loadPage(el.dataset.slug);
        closeMobile();
    });
});

// History
window.addEventListener('popstate', (e) => {
    if (e.state?.slug) loadPage(e.state.slug, false);
});

// Keyboard
document.addEventListener('keydown', (e) => {
    if (e.key === '/' && document.activeElement !== searchInput) {
        e.preventDefault();
        searchInput.focus();
    }
    if (e.key === 'Escape') {
        searchInput.blur();
        searchInput.value = '';
        if (currentSlug) loadPage(currentSlug, false);
        closeMobile();
    }
});

// Mobile
const sidebar = document.getElementById('sidebar');
const backdrop = document.getElementById('backdrop');
const menuBtn = document.getElementById('menuBtn');

menuBtn.addEventListener('click', () => {
    sidebar.classList.toggle('open');
    backdrop.classList.toggle('visible');
});
backdrop.addEventListener('click', closeMobile);

function closeMobile() {
    sidebar.classList.remove('open');
    backdrop.classList.remove('visible');
}

// Init
const params = new URLSearchParams(location.search);
const initSlug = params.get('page') || DEFAULT_SLUG;
loadPage(initSlug, false);
</script>
</body>
</html>
