<?php
/**
 * Kennispagina's router – overzicht en individuele pagina's met Liva-chat.
 * Geen SiteChat v2. Originele kennispagina's met content uit kennis-content.json.
 *
 * /kennis/ → overzicht van alle kennispagina's
 * /kennis/{slug} → individuele pagina (via .htaccess ?p=slug)
 */
require_once __DIR__ . '/../includes/itlive-50-pagina-ideeen.php';

/**
 * Laadt het volledige kennis-content object uit data/kennis-content.json.
 * Ondersteunt bestanden die met een PHP-wrapper beginnen (alleen server-side inlezen).
 */
function itlive_kennis_load_content_json_file(string $path): array {
    if (!is_file($path)) {
        return [];
    }
    $raw = @file_get_contents($path);
    if ($raw === false || $raw === '') {
        return [];
    }
    $raw = trim($raw);
    if (strncmp($raw, '<?php', 5) === 0) {
        $close = strpos($raw, '?>');
        if ($close !== false) {
            $raw = trim(substr($raw, $close + 2));
        } else {
            $brace = strpos($raw, '{');
            $end = strrpos($raw, '}');
            if ($brace !== false && $end !== false && $end > $brace) {
                $raw = substr($raw, $brace, $end - $brace + 1);
            }
        }
    }
    $decoded = @json_decode($raw, true);
    return is_array($decoded) ? $decoded : [];
}

$slug = isset($_GET['p']) ? trim((string) $_GET['p']) : '';
$slug = preg_match('/^[a-z0-9-]+$/', $slug) ? $slug : '';

$pages = itlive_kennis_paginas();
$page = null;
if ($slug !== '') {
    foreach ($pages as $p) {
        if (($p['slug'] ?? '') === $slug) {
            $page = $p;
            break;
        }
    }
}

// Content uit kennis-content.json (per slug: body_sections, faq, cta_strip, related_slugs, …)
$content = [];
$json_file = dirname(__DIR__) . '/data/kennis-content.json';
if ($slug !== '') {
    $decoded = itlive_kennis_load_content_json_file($json_file);
    if (isset($decoded[$slug]) && is_array($decoded[$slug])) {
        $content = $decoded[$slug];
    }
}

$page_title = $page ? ($content['meta_title'] ?? $page['title'] . ' – IT Live') : 'Kennispagina\'s – IT Live';
$page_description = $page ? ($content['meta_description'] ?? $page['description'] ?? '') : 'Uitleg over websites, SaaS, SEO, hosting en meer. Kies een onderwerp.';
$portal_base = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'account.itlive.nl');
if (in_array(strtolower($_SERVER['HTTP_HOST'] ?? ''), ['www.itlive.nl', 'itlive.nl'], true)) {
    $portal_base = 'https://account.itlive.nl';
}

$extra_head = '
<meta name="description" content="' . htmlspecialchars($page_description) . '">
<link rel="canonical" href="https://itlive.nl/kennis/' . ($slug ? htmlspecialchars($slug) . '/' : '') . '">
<style>
/* Kennisbank: IT Live huisstijl, cards met kleur per hoofdcategorie (8–9), dan subs + honderden items */
.kennis-page { background: var(--itlive-light, #f8fafc); min-height: 60vh; padding: 2rem 1rem 3rem; }
.kennis-inner { max-width: 1200px; margin: 0 auto; }
.kennis-page h1 { font-size: 1.85rem; margin-bottom: 0.5rem; color: var(--itlive-dark, #1e293b); font-weight: 700; }
.kennis-page h2 { font-size: 1.35rem; margin: 2rem 0 0.75rem; color: var(--itlive-dark); }
.kennis-page p { font-size: 1.05rem; line-height: 1.7; color: var(--itlive-gray, #64748b); margin-bottom: 1rem; }
.kennis-page a { color: var(--itlive-primary, #0d9488); text-decoration: none; }
.kennis-page a:hover { text-decoration: underline; }
/* Hoofdcategorie-cards (8–9) */
.kennis-main-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 1rem; margin: 2rem 0 2.5rem; }
.kennis-main-card { display: block; padding: 1.25rem 1rem; border-radius: var(--itlive-radius-lg, 12px); text-decoration: none; color: #fff; font-weight: 600; font-size: 1rem; text-align: center; box-shadow: var(--itlive-shadow, 0 4px 14px rgba(0,0,0,.08)); transition: transform .2s, box-shadow .2s; }
.kennis-main-card:hover { transform: translateY(-2px); box-shadow: var(--itlive-shadow-lg, 0 12px 40px rgba(0,0,0,.12)); color: #fff; }
.kennis-main-card .kennis-main-icon { font-size: 1.75rem; margin-bottom: 0.35rem; display: block; }
.kennis-main-card .kennis-main-count { font-size: 0.8rem; opacity: .9; font-weight: 500; }
/* Sectie per hoofdcategorie */
.kennis-main-section { margin-bottom: 2.5rem; }
.kennis-main-section h2 { display: flex; align-items: center; gap: 0.5rem; padding-bottom: 0.5rem; border-bottom: 3px solid; }
.kennis-sub-title { font-size: 1rem; color: var(--itlive-gray); margin: 1.25rem 0 0.5rem; font-weight: 600; }
.kennis-overview-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 0.75rem; margin-top: 0.75rem; }
.kennis-overview-item { border-radius: var(--itlive-radius-md, 8px); padding: 0.9rem 1rem; border-left: 4px solid; background: #fff; border-color: var(--item-color); box-shadow: var(--itlive-shadow-sm, 0 1px 3px rgba(0,0,0,.1)); transition: box-shadow .2s; }
.kennis-overview-item:hover { box-shadow: var(--itlive-shadow, 0 4px 14px rgba(0,0,0,.08)); }
.kennis-overview-item a { display: block; color: var(--itlive-dark); font-weight: 500; font-size: 0.95rem; }
.kennis-overview-item a:hover { color: var(--itlive-primary); }
.kennis-overview-item .cat { font-size: 0.7rem; color: var(--itlive-gray); margin-bottom: 0.25rem; text-transform: uppercase; letter-spacing: .04em; }
.kennis-card { background: #fff; border: 1px solid var(--itlive-border, #e2e8f0); border-radius: var(--itlive-radius-lg); padding: 1.25rem 1.5rem; margin-bottom: 1rem; box-shadow: var(--itlive-shadow-sm); }
.kennis-chat { background: #fff; border: 2px solid #e2e8f0; border-radius: 20px; padding: 1.25rem 1.5rem; margin-top: 2rem; box-shadow: 0 12px 48px rgba(0,0,0,.08); color: #1e293b; display: flex; flex-direction: column; max-height: min(75vh, 720px); }
.kennis-chat h3 { font-size: 1rem; margin: 0 0 0.75rem 0; color: #0f172a; }
.kennis-messages { min-height: 80px; max-height: 38vh; overflow-y: auto; margin-bottom: 0; }
.kennis-msg { margin-bottom: 0.75rem; padding: 0.9rem 1.15rem; border-radius: 14px; font-size: 1rem; max-width: 92%; line-height: 1.5; }
.kennis-msg.user { background: rgba(29,78,216,.12); color: #1e293b; margin-left: auto; border: 1px solid rgba(29,78,216,.25); }
.kennis-msg.assistant { background: #f1f5f9; color: #1e293b; border: 1px solid #e2e8f0; }
.kennis-typing { display: flex; align-items: center; gap: 4px; padding: 1rem 1.2rem; }
.kennis-typing span { width: 8px; height: 8px; border-radius: 50%; background: #1d4ed8; animation: kb-bounce 1.4s ease-in-out infinite both; }
.kennis-typing span:nth-child(1){ animation-delay: -.32s; }
.kennis-typing span:nth-child(2){ animation-delay: -.16s; }
@keyframes kb-bounce { 0%,80%,100%{ transform: scale(0); } 40%{ transform: scale(1); } }
.kennis-chips { display: flex; flex-wrap: wrap; gap: .45rem; margin-bottom: .75rem; }
.kennis-chip { padding: .5rem .9rem; border-radius: 10px; font-size: .95rem; background: #f1f5f9; color: #1e293b; border: 2px solid #e2e8f0; cursor: pointer; text-decoration: none; transition: background .2s, border-color .2s; }
.kennis-chip:hover { background: rgba(13,148,136,.1); border-color: var(--itlive-primary); }
.kennis-ctas { margin-top: 1rem; padding-top: 1rem; border-top: 2px solid #e2e8f0; display: none; flex-wrap: wrap; gap: .5rem; }
.kennis-ctas.show { display: flex; }
.kennis-cta-btn { display: inline-block; padding: .6rem 1rem; border-radius: 8px; font-size: .9rem; font-weight: 600; text-decoration: none; }
.kennis-cta-btn.offerte { background: #1e293b; color: #fff; }
.kennis-cta-btn.kennismaking { background: #0d9488; color: #fff; }
.kennis-input-row { margin-top: 1rem; padding-top: 1rem; border-top: 2px solid #e2e8f0; }
.kennis-input-wrap { display: flex; gap: .6rem; align-items: center; }
.kennis-input { flex: 1; min-height: 50px; padding: .85rem 1.1rem; border-radius: 12px; border: 2px solid #cbd5e1; background: #fff; color: #1e293b; font-size: 1rem; }
.kennis-send { width: 50px; height: 50px; border-radius: 12px; background: #1d4ed8; color: #fff; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; }
.kennis-footer-links { margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--itlive-border); color: var(--itlive-gray); font-size: 0.95rem; }
.kennis-footer-links a { margin-right: 0.75rem; }
</style>';

require_once __DIR__ . '/../includes/enhanced-header-final.php';
if (function_exists('getEnhancedHeader')) echo getEnhancedHeader($pageTitle ?? $page_title ?? $seo_title ?? 'IT Live', $pageDescription ?? $page_description ?? $seo_description ?? '', '', []);
?>

<section class="kennis-page" id="main-content">
    <div class="kennis-inner">
        <?php if (!$page): ?>
        <!-- Overzicht: 8–9 hoofdcategorieën (cards met kleur), dan subs + honderden items -->
        <span class="kennis-category" style="font-size:0.8rem;color:var(--itlive-gray);text-transform:uppercase;letter-spacing:0.08em;margin-bottom:0.75rem;display:block;">Kennisbank</span>
        <h1>Kennispagina's</h1>
        <p>Uitleg over websites, SaaS, SEO, hosting en meer. Kies een hoofdcategorie of gebruik <a href="/kennis/zoeken-met-ai">Zoeken met AI</a> om snel te vinden wat je zoekt.</p>
        <div class="kennis-svc-strip" style="display:flex;flex-wrap:wrap;gap:.75rem;margin:1.25rem 0 1.75rem">
          <a href="/seo-bureau/" style="padding:.65rem 1rem;background:#0f172a;color:#fff;border-radius:8px;text-decoration:none;font-weight:600">SEO bureau</a>
          <a href="/google-ads-bureau/" style="padding:.65rem 1rem;background:#1d4ed8;color:#fff;border-radius:8px;text-decoration:none;font-weight:600">Google Ads bureau</a>
          <a href="/website-quickscan/" style="padding:.65rem 1rem;border:1px solid #cbd5e1;border-radius:8px;text-decoration:none;font-weight:600;color:#0f172a">Gratis website-scan</a>
        </div>

        <?php
        $main_cats = function_exists('itlive_kennis_main_categories') ? itlive_kennis_main_categories() : [];
        $by_main = [];
        foreach ($pages as $p) {
            $sub = $p['category'] ?? 'Overig';
            $main_key = function_exists('itlive_kennis_main_for_category') ? itlive_kennis_main_for_category($sub) : $sub;
            if (!isset($by_main[$main_key])) $by_main[$main_key] = [];
            if (!isset($by_main[$main_key][$sub])) $by_main[$main_key][$sub] = [];
            $by_main[$main_key][$sub][] = $p;
        }
        $main_order = array_keys($main_cats);
        if (empty($main_order) && !empty($by_main)) {
            $main_order = array_keys($by_main);
            ksort($main_order);
        }
        ?>

        <div class="kennis-main-cards" role="navigation" aria-label="Hoofdcategorieën">
            <?php foreach ($main_order as $main_key):
                if (!isset($by_main[$main_key])) continue;
                $def = $main_cats[$main_key] ?? ['title' => $main_key, 'icon' => '<i class="fas fa-file-lines"></i>', 'color' => '#64748b'];
                $count = 0;
                foreach ($by_main[$main_key] as $sub_items) { $count += count($sub_items); }
                $id = 'kennis-main-' . preg_replace('/[^a-z0-9]/i', '-', $main_key);
            ?>
            <a class="kennis-main-card" href="#<?php echo $id; ?>" style="background:<?php echo htmlspecialchars($def['color'] ?? '#64748b'); ?>">
                <span class="kennis-main-icon"><?php echo $def['icon'] ?? '<i class="fas fa-file-lines"></i>'; ?></span>
                <?php echo htmlspecialchars($def['title']); ?>
                <span class="kennis-main-count"><?php echo $count; ?> onderwerpen</span>
            </a>
            <?php endforeach; ?>
        </div>

        <?php foreach ($main_order as $main_key):
            if (!isset($by_main[$main_key])) continue;
            $def = $main_cats[$main_key] ?? ['title' => $main_key, 'icon' => '<i class="fas fa-file-lines"></i>', 'color' => '#64748b'];
            $main_color = $def['color'] ?? '#64748b';
            $id = 'kennis-main-' . preg_replace('/[^a-z0-9]/i', '-', $main_key);
        ?>
        <section class="kennis-main-section" id="<?php echo $id; ?>">
            <h2 style="border-color:<?php echo htmlspecialchars($main_color); ?>">
                <?php echo $def['icon'] ?? '<i class="fas fa-file-lines"></i>'; ?> <?php echo htmlspecialchars($def['title']); ?>
            </h2>
            <?php
            ksort($by_main[$main_key]);
            foreach ($by_main[$main_key] as $sub => $items):
                $sub_icon = function_exists('itlive_kennis_category_icon') ? itlive_kennis_category_icon($sub) : '';
            ?>
            <div class="kennis-sub-title"><?php echo $sub_icon; ?> <?php echo htmlspecialchars($sub); ?></div>
            <div class="kennis-overview-grid">
                <?php foreach ($items as $it): ?>
                <div class="kennis-overview-item" style="--item-color: <?php echo htmlspecialchars($main_color); ?>">
                    <span class="cat"><?php echo htmlspecialchars($it['category'] ?? ''); ?></span>
                    <a href="/kennis/<?php echo htmlspecialchars($it['slug']); ?>"><?php echo htmlspecialchars($it['title']); ?></a>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endforeach; ?>
        </section>
        <?php endforeach; ?>

        <p class="kennis-footer-links"><a href="/kennis/zoeken-met-ai">Zoeken met AI</a> · <a href="/sitemap">Sitemap</a> · <a href="/offerte">Offerte</a> · <a href="/gratis-kennismaking">Gratis kennismaking</a></p>

        <?php else: ?>
        <!-- Individuele pagina -->
        <?php
        $intro = function_exists('itlive_kennis_page_intro') ? itlive_kennis_page_intro($page) : ($page['description'] ?? '');
        $hero_title = $content['hero_title'] ?? $content['meta_title'] ?? $page['title'];
        ?>
        <span class="kennis-category" style="font-size:0.8rem;color:#94a3b8;text-transform:uppercase;letter-spacing:0.08em;margin-bottom:0.75rem;display:block;"><?php echo htmlspecialchars($page['category'] ?? 'Kennis'); ?></span>
        <h1><?php echo htmlspecialchars($hero_title); ?></h1>
        <p><?php echo nl2br(htmlspecialchars($intro)); ?></p>

        <?php if (!empty($content['body_sections']) && is_array($content['body_sections'])): ?>
        <?php foreach ($content['body_sections'] as $sec): ?>
        <div class="kennis-card">
            <?php if (!empty($sec['title'])): ?><h2><?php echo htmlspecialchars($sec['title']); ?></h2><?php endif; ?>
            <?php echo $sec['content'] ?? ''; ?>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!empty($content['faq']) && is_array($content['faq'])): ?>
        <h2>Veelgestelde vragen</h2>
        <?php foreach ($content['faq'] as $f): ?>
        <div class="kennis-card">
            <strong><?php echo htmlspecialchars($f['question'] ?? ''); ?></strong>
            <p style="margin:0.5rem 0 0 0;"><?php echo nl2br(htmlspecialchars($f['answer'] ?? '')); ?></p>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php
        $related_pages = [];
        if (!empty($content['related_slugs']) && is_array($content['related_slugs'])) {
            $by_slug = [];
            foreach ($pages as $p) {
                if (!empty($p['slug'])) {
                    $by_slug[$p['slug']] = $p;
                }
            }
            foreach ($content['related_slugs'] as $rs) {
                $rs = is_string($rs) ? trim($rs) : '';
                if ($rs !== '' && isset($by_slug[$rs])) {
                    $related_pages[] = $by_slug[$rs];
                }
            }
        }
        if (empty($related_pages) && function_exists('itlive_kennis_related_slugs')) {
            $related_pages = itlive_kennis_related_slugs($slug, 6);
        }
        ?>
        <?php if (!empty($related_pages)): ?>
        <h2>Gerelateerde onderwerpen</h2>
        <div class="kennis-overview-grid" style="margin-bottom:1rem;">
            <?php foreach ($related_pages as $rp): ?>
            <div class="kennis-overview-item" style="--item-color: #0d9488;">
                <span class="cat"><?php echo htmlspecialchars($rp['category'] ?? ''); ?></span>
                <a href="/kennis/<?php echo htmlspecialchars($rp['slug'] ?? ''); ?>"><?php echo htmlspecialchars($rp['title'] ?? ''); ?></a>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <?php
        $tools = function_exists('itlive_kennis_tools_block') ? itlive_kennis_tools_block($slug) : null;
        if (!$tools && function_exists('itlive_kennis_tools_default_by_category')) {
            $tools = itlive_kennis_tools_default_by_category($page['category'] ?? '');
        }
        if (!empty($content['tools_override'])) $tools = $content['tools_override'];
        if ($tools && !empty($tools['tools'])):
        ?>
        <h2><?php echo htmlspecialchars($tools['title'] ?? 'Werk met deze tools'); ?></h2>
        <p><?php echo htmlspecialchars($tools['intro'] ?? ''); ?></p>
        <ul>
            <?php foreach ($tools['tools'] as $t): ?>
            <li><a href="<?php echo htmlspecialchars($t['url'] ?? '#'); ?>"><?php echo htmlspecialchars($t['label'] ?? ''); ?></a><?php if (!empty($t['desc'])): ?> – <?php echo htmlspecialchars($t['desc']); ?><?php endif; ?></li>
            <?php endforeach; ?>
        </ul>
        <?php endif; ?>

        <?php if (!empty($content['cta_strip']) && (!empty($content['cta_strip']['title']) || !empty($content['cta_strip']['buttons']))): ?>
        <div class="kennis-card" style="border-left:4px solid #0d9488;">
            <?php if (!empty($content['cta_strip']['title'])): ?><h2><?php echo htmlspecialchars($content['cta_strip']['title']); ?></h2><?php endif; ?>
            <?php if (!empty($content['cta_strip']['buttons'])): ?>
            <p>
                <?php foreach ($content['cta_strip']['buttons'] as $b): ?>
                <a href="<?php echo htmlspecialchars($b['url'] ?? '#'); ?>" class="kennis-cta-btn <?php echo (strpos($b['url'] ?? '', 'kennismaking') !== false) ? 'kennismaking' : 'offerte'; ?>" style="margin-right:0.5rem;margin-bottom:0.5rem;"><?php echo htmlspecialchars($b['label'] ?? ''); ?></a>
                <?php endforeach; ?>
            </p>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="kennis-card" style="border-left:4px solid #0d9488;">
            <h2>Plan of offerte nodig?</h2>
            <p><a href="/offerte" class="kennis-cta-btn offerte" style="margin-right:0.5rem;">Plan of offerte aanvragen</a> <a href="/gratis-kennismaking" class="kennis-cta-btn kennismaking">Gratis kennismaking (20 min)</a></p>
        </div>
        <?php endif; ?>

        <h2>Vraag het in de chat</h2>
        <p>Stel je vraag hieronder. Liva helpt je met antwoorden en kan je doorverwijzen naar een offerte of gratis kennismaking.</p>

        <?php
        $chat_title = $page['title'] ?? '';
        $chat_desc = $page['description'] ?? $content['meta_description'] ?? '';
        $welcome = function_exists('itlive_kennis_chat_welcome') ? itlive_kennis_chat_welcome($page) : 'Waar kunnen we je mee helpen? Typ hieronder of kies een knop.';
        ?>
        <div class="kennis-chat" id="kennis-chat" data-page-title="<?php echo htmlspecialchars($chat_title); ?>" data-page-description="<?php echo htmlspecialchars($chat_desc); ?>" data-chat-label="Typ je vraag of vraag een offerte aan">
            <h3><i class="fas fa-comments"></i> Chat – <?php echo htmlspecialchars($chat_title); ?></h3>
            <div class="kennis-messages" id="kennis-messages" role="log" aria-live="polite"></div>
            <div class="kennis-chips" id="kennis-chips">
                <a href="/offerte" class="kennis-chip">Offerte aanvragen</a>
                <a href="/gratis-kennismaking" class="kennis-chip">Gratis kennismaking</a>
                <a href="/kennis/zoeken-met-ai" class="kennis-chip">Zoeken met AI</a>
                <a href="/sitemap" class="kennis-chip">Sitemap</a>
                <a href="<?php echo htmlspecialchars(rtrim($portal_base, '/') . '/customer_portal/'); ?>" class="kennis-chip">Klantportaal</a>
            </div>
            <div class="kennis-ctas" id="kennis-ctas">
                <p>Plan of offerte nodig?</p>
                <a href="/offerte" class="kennis-cta-btn offerte" id="kennis-cta-offerte">Plan of offerte aanvragen</a>
                <a href="/gratis-kennismaking" class="kennis-cta-btn kennismaking">Gratis kennismaking (20 min)</a>
            </div>
            <div class="kennis-input-row">
                <div class="kennis-input-wrap">
                    <input type="text" class="kennis-input" id="kennis-input" placeholder="Bijv. wat kost een website, hoe werkt het…" aria-label="Typ je vraag" autocomplete="off">
                    <button type="button" class="kennis-send" id="kennis-send" aria-label="Verstuur"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="22" height="22"><path d="M5 12h14M12 5l7 7-7 7"/></svg></button>
                </div>
            </div>
        </div>
        <script>
        (function(){
            var chat = document.getElementById('kennis-chat');
            var messagesEl = document.getElementById('kennis-messages');
            var inputEl = document.getElementById('kennis-input');
            var sendBtn = document.getElementById('kennis-send');
            var ctasEl = document.getElementById('kennis-ctas');
            var ctaOfferte = document.getElementById('kennis-cta-offerte');
            if (!chat || !messagesEl || !inputEl || !sendBtn) return;
            var pageTitle = (chat.getAttribute('data-page-title') || '').trim();
            var pageDescription = (chat.getAttribute('data-page-description') || '').trim();
            var userMessages = [];
            var isItlive = (window.location.hostname === 'www.itlive.nl' || window.location.hostname === 'itlive.nl');
            var baseUrl = isItlive ? 'https://itlive.nl' : window.location.origin;
            var kennisApiUrl = isItlive ? 'https://itlive.nl/api/kennis-chat.php' : (window.location.origin + '/api/kennis-chat.php');
            function addMsg(role, text) {
                var d = document.createElement('div');
                d.className = 'kennis-msg ' + role;
                d.textContent = text;
                messagesEl.appendChild(d);
                messagesEl.scrollTop = messagesEl.scrollHeight;
            }
            function addTyping() {
                var d = document.createElement('div');
                d.className = 'kennis-msg assistant kennis-typing';
                d.setAttribute('data-typing', '1');
                d.innerHTML = '<span></span><span></span><span></span>';
                messagesEl.appendChild(d);
                messagesEl.scrollTop = messagesEl.scrollHeight;
                return d;
            }
            function removeTyping() {
                var el = messagesEl.querySelector('[data-typing="1"]');
                if (el) el.remove();
            }
            if (messagesEl.children.length === 0) addMsg('assistant', '<?php echo addslashes($welcome); ?>');
            function send() {
                var msg = (inputEl.value || '').trim();
                if (!msg) return;
                addMsg('user', msg);
                userMessages.push(msg);
                inputEl.value = '';
                sendBtn.disabled = true;
                addTyping();
                fetch(kennisApiUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message: msg, page_title: pageTitle, page_description: pageDescription, conversation_summary: userMessages.join(' ').trim().slice(0, 800) })
                }).then(function(r) { return r.json(); }).then(function(data) {
                    removeTyping();
                    addMsg('assistant', data.reply || data.message || 'Probeer het later of vraag een offerte aan.');
                    if (data.show_ctas && ctasEl) ctasEl.classList.add('show');
                    sendBtn.disabled = false;
                }).catch(function() {
                    removeTyping();
                    addMsg('assistant', 'Verbinding mislukt. Vraag een offerte aan via de knop.');
                    sendBtn.disabled = false;
                });
            }
            sendBtn.addEventListener('click', send);
            inputEl.addEventListener('keydown', function(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } });
        })();
        </script>

        <nav style="margin-top:2rem;padding-top:1.5rem;border-top:1px solid rgba(148,163,184,0.2);">
            <a href="/kennis/">← Alle kennispagina's</a> · <a href="/sitemap">Sitemap</a> · <a href="/offerte">Offerte</a> · <a href="/contact">Contact</a>
        </nav>
        <?php endif; ?>
    </div>
</section>

<?php echo '</body></html>'; ?>
