<?php defined('BASEPATH') or exit('No direct script access allowed');

$pageTitle = !empty($title) ? $title : lang('knowledgebase');
$activeCategory = (int) ($selected_category ?? 0);
$totalResults = !empty($articles) ? count($articles) : 0;
$totalCategories = !empty($categories) ? count($categories) : 0;

$buildKbUrl = function ($categoryId = 0) use ($search) {
    $params = array();
    if (!empty($search)) {
        $params['q'] = $search;
    }
    if (!empty($categoryId)) {
        $params['category'] = (int) $categoryId;
    }
    $query = http_build_query($params);
    return base_url('knowledgebase') . (!empty($query) ? '?' . $query : '');
};

$buildExcerpt = function ($description, $limit = 180) {
    $text = trim(preg_replace('/\s+/', ' ', strip_tags((string) $description)));
    if ($text === '') {
        return '';
    }
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        return mb_strlen($text) > $limit ? mb_substr($text, 0, $limit) . '...' : $text;
    }
    return strlen($text) > $limit ? substr($text, 0, $limit) . '...' : $text;
};
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= html_escape($pageTitle) ?></title>
    <script>
        (function() {
            try {
                var stored = localStorage.getItem('theme');
                var preferred = stored || (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
                document.documentElement.classList.toggle('dark', preferred === 'dark');
            } catch (e) {
                document.documentElement.classList.remove('dark');
            }
        })();
    </script>
    <link rel="stylesheet" href="<?= base_url('assets/css/tailwind.generated.css') ?>">
    <link rel="stylesheet" href="<?= base_url('assets/css/app.css') ?>">
    <script src="<?= base_url('assets/vendor/lucide/lucide.min.js') ?>" defer></script>
    <style>
        .kb-hero-grid {
            background-image:
                linear-gradient(to right, rgba(148, 163, 184, 0.08) 1px, transparent 1px),
                linear-gradient(to bottom, rgba(148, 163, 184, 0.08) 1px, transparent 1px);
            background-size: 24px 24px;
        }

        .dark .kb-hero-grid {
            background-image:
                linear-gradient(to right, rgba(148, 163, 184, 0.05) 1px, transparent 1px),
                linear-gradient(to bottom, rgba(148, 163, 184, 0.05) 1px, transparent 1px);
        }
    </style>
</head>

<body class="min-h-screen bg-background text-foreground">
    <header class="relative overflow-hidden border-b border-border bg-card">
        <div class="kb-hero-grid pointer-events-none absolute inset-0"></div>
        <div class="pointer-events-none absolute -left-20 -top-20 h-72 w-72 rounded-full bg-sky-500/15 blur-3xl"></div>
        <div class="pointer-events-none absolute -right-20 top-8 h-72 w-72 rounded-full bg-indigo-500/15 blur-3xl"></div>

        <div class="relative mx-auto w-full max-w-7xl px-4 pb-10 pt-6 sm:px-6 lg:px-8">
            <div class="mb-7 flex items-center justify-between gap-3">
                <a href="<?= base_url() ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card/90 px-3 py-2 text-sm font-semibold text-foreground shadow-sm hover:bg-muted">
                    <i data-lucide="arrow-left" class="h-4 w-4"></i>
                    <?= lang('back') ?>
                </a>
                <div class="flex items-center gap-2">
                    <a href="<?= base_url('login') ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card/90 px-3 py-2 text-sm font-semibold text-foreground shadow-sm hover:bg-muted">
                        <i data-lucide="log-in" class="h-4 w-4"></i>
                        <?= lang('login') ?>
                    </a>
                    <button type="button" data-theme-toggle class="inline-flex items-center gap-2 rounded-lg border border-border bg-card/90 px-3 py-2 text-sm font-semibold text-foreground shadow-sm hover:bg-muted" aria-pressed="false">
                        <i data-lucide="moon-star" class="h-4 w-4"></i>
                    </button>
                </div>
            </div>

            <div class="mx-auto max-w-4xl text-center">
                <span class="inline-flex items-center rounded-full border border-border bg-card/90 px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] text-muted-foreground shadow-sm">
                    <?= lang('knowledgebase') ?>
                </span>
                <h1 class="mt-4 text-3xl font-bold tracking-tight text-foreground sm:text-5xl">
                    <?= lang('how_can_we_help') ?>
                </h1>
                <p class="mx-auto mt-3 max-w-2xl text-sm text-muted-foreground sm:text-base">
                    Find answers, browse topics, and discover detailed guides built for clients.
                </p>
            </div>

            <form method="get" action="<?= base_url('knowledgebase') ?>" class="mx-auto mt-8 max-w-3xl">
                <?php if (!empty($activeCategory)) { ?>
                    <input type="hidden" name="category" value="<?= (int) $activeCategory ?>">
                <?php } ?>
                <label class="relative block">
                    <span class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-4 text-muted-foreground">
                        <i data-lucide="search" class="h-4 w-4"></i>
                    </span>
                    <input type="search" name="q" value="<?= html_escape((string) $search) ?>"
                        placeholder="<?= lang('search_your_question') ?>"
                        class="h-12 w-full rounded-xl border border-border bg-card/95 pl-11 pr-4 text-sm text-foreground shadow-sm outline-none transition focus:border-sky-500 focus:ring-2 focus:ring-sky-500/25">
                </label>
            </form>

            <div class="mx-auto mt-6 grid max-w-3xl grid-cols-2 gap-3 sm:grid-cols-4">
                <div class="rounded-xl border border-border bg-card/85 px-3 py-2 text-center shadow-sm">
                    <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('categories') ?></p>
                    <p class="mt-1 text-lg font-bold text-foreground"><?= $totalCategories ?></p>
                </div>
                <div class="rounded-xl border border-border bg-card/85 px-3 py-2 text-center shadow-sm">
                    <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('articles') ?></p>
                    <p class="mt-1 text-lg font-bold text-foreground"><?= $totalResults ?></p>
                </div>
                <div class="rounded-xl border border-border bg-card/85 px-3 py-2 text-center shadow-sm">
                    <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('view') ?></p>
                    <p class="mt-1 text-lg font-bold text-foreground"><?= !empty($articles) ? array_sum(array_map(function ($a) { return (int) $a->total_view; }, $articles)) : 0 ?></p>
                </div>
                <div class="rounded-xl border border-border bg-card/85 px-3 py-2 text-center shadow-sm">
                    <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('all') ?></p>
                    <p class="mt-1 text-lg font-bold text-foreground"><?= empty($activeCategory) ? 'Active' : 'Filtered' ?></p>
                </div>
            </div>
        </div>
    </header>

    <main class="mx-auto w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
        <div class="grid grid-cols-1 gap-6 lg:grid-cols-12">
            <aside class="lg:col-span-3">
                <div class="sticky top-6 rounded-2xl border border-border bg-card p-4 shadow-sm">
                    <div class="mb-4 flex items-center justify-between">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('categories') ?></p>
                        <span class="rounded-full bg-muted px-2 py-0.5 text-[11px] font-semibold text-muted-foreground"><?= $totalCategories ?></span>
                    </div>
                    <div class="space-y-1">
                        <a href="<?= $buildKbUrl(0) ?>" class="flex items-center justify-between rounded-xl px-3 py-2.5 text-sm font-semibold transition <?= empty($activeCategory) ? 'bg-indigo-600 text-white' : 'text-foreground hover:bg-muted' ?>">
                            <span class="flex items-center gap-2"><i data-lucide="layout-grid" class="h-4 w-4"></i><?= lang('all') ?></span>
                            <span class="rounded-full px-2 py-0.5 text-[11px] <?= empty($activeCategory) ? 'bg-white/20 text-white' : 'bg-muted text-muted-foreground' ?>"><?= $totalResults ?></span>
                        </a>
                        <?php if (!empty($categories)) {
                            foreach ($categories as $category) {
                                $cid = (int) $category->kb_category_id;
                                $count = (int) ($category_counts[$cid] ?? 0);
                                $isActive = $activeCategory === $cid;
                                ?>
                                <a href="<?= $buildKbUrl($cid) ?>" class="flex items-center justify-between rounded-xl px-3 py-2.5 text-sm font-semibold transition <?= $isActive ? 'bg-indigo-600 text-white' : 'text-foreground hover:bg-muted' ?>">
                                    <span class="truncate"><?= html_escape($category->category) ?></span>
                                    <span class="ml-2 rounded-full px-2 py-0.5 text-[11px] <?= $isActive ? 'bg-white/20 text-white' : 'bg-muted text-muted-foreground' ?>"><?= $count ?></span>
                                </a>
                            <?php }
                        } ?>
                    </div>
                </div>
            </aside>

            <section class="space-y-5 lg:col-span-9">
                <?php if (empty($grouped_articles)) { ?>
                    <div class="rounded-2xl border border-border bg-card p-10 text-center shadow-sm">
                        <div class="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
                            <i data-lucide="file-search" class="h-5 w-5"></i>
                        </div>
                        <p class="text-lg font-semibold text-foreground"><?= lang('nothing_to_display') ?></p>
                        <p class="mt-1 text-sm text-muted-foreground">Please adjust your search or category filter.</p>
                    </div>
                <?php } else { ?>
                    <?php foreach ($categories as $category) {
                        $cid = (int) $category->kb_category_id;
                        if (empty($grouped_articles[$cid])) {
                            continue;
                        }
                        ?>
                        <article class="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
                            <header class="border-b border-border px-5 py-4">
                                <div class="flex items-center justify-between gap-3">
                                    <div>
                                        <h2 class="text-lg font-semibold text-foreground"><?= html_escape($category->category) ?></h2>
                                        <p class="text-sm text-muted-foreground"><?= html_escape((string) $category->description) ?></p>
                                    </div>
                                    <span class="inline-flex items-center rounded-full border border-border bg-muted px-2.5 py-1 text-xs font-semibold text-muted-foreground">
                                        <?= count($grouped_articles[$cid]) ?> <?= lang('articles') ?>
                                    </span>
                                </div>
                            </header>
                            <div class="divide-y divide-border">
                                <?php foreach ($grouped_articles[$cid] as $article) { ?>
                                    <a href="<?= base_url('knowledgebase/article/' . (int) $article->kb_id) ?>" class="block px-5 py-4 transition hover:bg-muted/45">
                                        <div class="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                                            <div class="min-w-0">
                                                <h3 class="truncate text-base font-semibold text-foreground"><?= html_escape($article->title) ?></h3>
                                                <p class="mt-1 text-sm text-muted-foreground"><?= html_escape($buildExcerpt($article->description)) ?></p>
                                            </div>
                                            <div class="shrink-0 text-xs font-medium text-muted-foreground">
                                                <?= (int) $article->total_view ?> <?= lang('view') ?>
                                            </div>
                                        </div>
                                    </a>
                                <?php } ?>
                            </div>
                        </article>
                    <?php } ?>
                <?php } ?>
            </section>
        </div>
    </main>

    <script>
        (function() {
            const html = document.documentElement;
            const toggle = document.querySelector('[data-theme-toggle]');
            const label = document.querySelector('[data-theme-label]');

            function updateThemeLabel() {
                const isDark = html.classList.contains('dark');
                if (toggle) {
                    toggle.setAttribute('aria-pressed', isDark ? 'true' : 'false');
                }

            }

            if (toggle) {
                toggle.addEventListener('click', function() {
                    html.classList.toggle('dark');
                    try {
                        localStorage.setItem('theme', html.classList.contains('dark') ? 'dark' : 'light');
                    } catch (e) {}
                    updateThemeLabel();
                });
            }

            function renderIcons() {
                if (window.lucide && typeof window.lucide.createIcons === 'function') {
                    window.lucide.createIcons();
                }
            }

            updateThemeLabel();
            renderIcons();
            document.addEventListener('DOMContentLoaded', renderIcons);
            window.addEventListener('load', renderIcons);
        })();
    </script>
    <script>
        (function() {
            const form = document.querySelector('form[action$="knowledgebase"]');
            const input = form ? form.querySelector('input[name="q"]') : null;
            if (!form || !input) return;

            let lastValue = input.value || '';
            let timer = null;

            function submitSearch() {
                if (typeof form.requestSubmit === 'function') {
                    form.requestSubmit();
                } else {
                    form.submit();
                }
            }

            input.addEventListener('input', function() {
                const value = input.value || '';
                if (value === lastValue) return;
                lastValue = value;
                clearTimeout(timer);
                timer = setTimeout(submitSearch, 300);
            });
        })();
    </script>
</body>

</html>
