<?php
use function App\Core\{e, url};

$page = $page ?? [];
$title = (string) ($page['title'] ?? '');
$description = trim((string) ($page['seo_description'] ?? ''));
$language = (string) ($contentLanguage ?? $page['language'] ?? 'tr');
$updatedAt = (string) ($page['updated_at'] ?? $page['created_at'] ?? '');
$rawContent = trim((string) ($page['content'] ?? ''));

$slugify = static function (string $value): string {
    $value = html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $value = strtr($value, [
        'ı' => 'i', 'ğ' => 'g', 'ü' => 'u', 'ş' => 's', 'ö' => 'o', 'ç' => 'c',
        'İ' => 'i', 'Ğ' => 'g', 'Ü' => 'u', 'Ş' => 's', 'Ö' => 'o', 'Ç' => 'c',
    ]);
    if (function_exists('iconv')) {
        $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value);
        if (is_string($converted) && $converted !== '') {
            $value = $converted;
        }
    }
    $value = strtolower($value);
    $value = preg_replace('/[^a-z0-9]+/', '-', $value) ?: 'bolum';

    return trim($value, '-') ?: 'bolum';
};

$safeUrl = static function (string $value): string {
    $value = trim($value);
    if ($value === '') {
        return '#';
    }

    if (preg_match('~^(https?://|mailto:|/|#)~i', $value)) {
        return $value;
    }

    return '#';
};

$sanitizeHtml = static function (string $html) use ($safeUrl): string {
    $allowedTags = '<p><h2><h3><h4><ul><ol><li><strong><em><a><code><pre><blockquote><img><br>';
    $html = strip_tags($html, $allowedTags);
    $html = preg_replace('/\son[a-z]+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html) ?? $html;
    $html = preg_replace('/\sstyle\s*=\s*("[^"]*"|\'[^\']*\')/i', '', $html) ?? $html;

    $html = preg_replace_callback('/<a\b([^>]*)>/i', static function (array $match) use ($safeUrl): string {
        $href = '#';
        if (preg_match('/\shref\s*=\s*("([^"]*)"|\'([^\']*)\'|([^\s>]+))/i', $match[1], $hrefMatch)) {
            $href = $hrefMatch[2] ?? $hrefMatch[3] ?? $hrefMatch[4] ?? '#';
        }

        $href = $safeUrl($href);
        $rel = preg_match('~^https?://~i', $href) ? ' rel="noopener noreferrer"' : '';

        return '<a href="' . e($href) . '"' . $rel . '>';
    }, $html) ?? $html;

    $html = preg_replace_callback('/<img\b([^>]*)>/i', static function (array $match) use ($safeUrl): string {
        $src = '';
        $alt = '';
        if (preg_match('/\ssrc\s*=\s*("([^"]*)"|\'([^\']*)\'|([^\s>]+))/i', $match[1], $srcMatch)) {
            $src = $srcMatch[2] ?? $srcMatch[3] ?? $srcMatch[4] ?? '';
        }
        if (preg_match('/\salt\s*=\s*("([^"]*)"|\'([^\']*)\'|([^\s>]+))/i', $match[1], $altMatch)) {
            $alt = $altMatch[2] ?? $altMatch[3] ?? $altMatch[4] ?? '';
        }

        return '<img src="' . e($safeUrl($src)) . '" alt="' . e($alt) . '" loading="lazy">';
    }, $html) ?? $html;

    return $html;
};

if ($rawContent === '') {
    $rawContent = '<p>Bu sayfa icin henuz icerik eklenmedi.</p>';
} elseif (!preg_match('/<\s*(p|h2|h3|h4|ul|ol|blockquote|pre|img|br)\b/i', $rawContent)) {
    $paragraphs = preg_split('/\R{2,}/', $rawContent) ?: [$rawContent];
    $rawContent = implode('', array_map(static fn (string $paragraph): string => '<p>' . e(trim($paragraph)) . '</p>', $paragraphs));
}

$content = $sanitizeHtml($rawContent);
$toc = [];
$usedIds = [];
$content = preg_replace_callback('/<(h[23])([^>]*)>(.*?)<\/\1>/is', static function (array $match) use (&$toc, &$usedIds, $slugify): string {
    $tag = strtolower($match[1]);
    $inner = trim($match[3]);
    $text = trim(html_entity_decode(strip_tags($inner), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
    $baseId = $slugify($text);
    $id = $baseId;
    $index = 2;
    while (isset($usedIds[$id])) {
        $id = $baseId . '-' . $index;
        $index++;
    }
    $usedIds[$id] = true;
    $toc[] = ['id' => $id, 'text' => $text, 'level' => $tag];

    return '<' . $tag . ' id="' . e($id) . '">' . $inner . '<a class="heading-anchor" href="#' . e($id) . '" aria-label="Basliga baglanti">#</a></' . $tag . '>';
}, $content) ?? $content;
?>
<section class="docs-page">
    <nav class="container docs-breadcrumb" aria-label="Breadcrumb">
        <a href="<?= e(url('/')) ?>">Ana Sayfa</a>
        <span>/</span>
        <a href="<?= e(url('/sayfa/hakkimizda')) ?>">Dokumanlar</a>
        <span>/</span>
        <strong><?= e($title) ?></strong>
    </nav>

    <div class="container docs-shell <?= $toc === [] ? 'docs-shell-no-toc' : '' ?>">
        <?php if ($toc !== []): ?>
            <aside class="docs-toc" aria-label="Bu Sayfada">
                <details open>
                    <summary>Bu Sayfada</summary>
                    <div class="docs-toc-links">
                        <?php foreach ($toc as $item): ?>
                            <a class="<?= $item['level'] === 'h3' ? 'is-child' : '' ?>" href="#<?= e($item['id']) ?>"><?= e($item['text']) ?></a>
                        <?php endforeach; ?>
                    </div>
                </details>
            </aside>
        <?php endif; ?>

        <article class="docs-content">
            <?php if (!empty($translationNote)): ?>
                <p class="translation-note"><?= e($translationNote) ?></p>
            <?php endif; ?>

            <header class="docs-article-head">
                <p class="eyebrow"><?= e(strtoupper($language)) ?> Dokuman</p>
                <h1><?= e($title) ?></h1>
                <?php if ($description !== ''): ?><p class="docs-lead"><?= e($description) ?></p><?php endif; ?>
                <div class="docs-meta">
                    <span>Dil: <?= e($language) ?></span>
                    <span>Son guncelleme: <?= e($updatedAt !== '' ? $updatedAt : 'TODO') ?></span>
                    <span>Geri bildirim TODO</span>
                </div>
            </header>

            <div class="docs-body">
                <?= $content ?>
            </div>

            <footer class="docs-feedback">
                <strong>Bu sayfa yardimci oldu mu?</strong>
                <span>Geri bildirim sistemi sonraki iterasyon icin TODO.</span>
            </footer>
        </article>
    </div>
</section>
