<?php
session_start();
include 'config.php';
include 'rating_helpers.php';

// Category slug-to-data map (IDs 1-9)
$cat_map = [
    'why-sanitation-matters' => ['label' => 'Why Sanitation Matters', 'image' => 'images/ch1_why_matters.jpg', 'desc' => 'The Economic Opportunity: Unlocking billions in value through sanitation.'],
    'coverage-gaps' => ['label' => 'Coverage Gaps', 'image' => 'images/ch2_access_gaps.jpg', 'desc' => 'The Unfinished Agenda: Identifying underserved regions.'],
    'behavioral-barriers' => ['label' => 'Behavioral Barriers', 'image' => 'images/ch3_behavioral_change.jpg', 'desc' => 'Shifting the Sewer-Centric View: Cultural and social adoption.'],
    'technology-adoption' => ['label' => 'Technology Adoption', 'image' => 'images/ch4_tech_innovation.jpg', 'desc' => 'Systems & O&M Failures: Why tech fails and how to fix it.'],
    'chronic-underfunding' => ['label' => 'Chronic Underfunding', 'image' => 'images/ch5_financing.jpg', 'desc' => 'From Cost to Investment: Financing the revolution.'],
    'fragmented-governance' => ['label' => 'Fragmented Governance', 'image' => 'images/ch6_governance.jpg', 'desc' => 'Bridging the Divide: Policy and regulation alignment.'],
    'data-deficiencies' => ['label' => 'Data Deficiencies', 'image' => 'images/ch7_data_hub.jpg', 'desc' => 'The Invisible Crisis: We cannot fix what we cannot see.'],
    'unmet-aspirations' => ['label' => 'Unmet Aspirations', 'image' => 'images/ch8_frontline_heroes.jpg', 'desc' => 'Elevating the Frontline: Community voices and needs.'],
    'stakeholder-portal' => ['label' => 'Stakeholder Portal', 'image' => 'images/ch9_stakeholder_portal.jpg', 'desc' => 'Join the National Database: Register your organization.'],
];

// Slug → numeric ID map (matches thematic_categories in DB)
$slug_to_id = [
    'why-sanitation-matters' => 1,
    'coverage-gaps' => 2,
    'behavioral-barriers' => 3,
    'technology-adoption' => 4,
    'chronic-underfunding' => 5,
    'fragmented-governance' => 6,
    'data-deficiencies' => 7,
    'unmet-aspirations' => 8,
    'stakeholder-portal' => 9,
];

// Read filter / sort / page params
$active_sub = isset($_GET['sub']) && isset($cat_map[$_GET['sub']]) ? $_GET['sub'] : null;
$active_label = $active_sub ? $cat_map[$active_sub]['label'] : null;
$active_cat_id = $active_sub ? ($slug_to_id[$active_sub] ?? 0) : 0;
$is_logged_in = isset($_SESSION['user_id']);
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'most-viewed';
$page_num = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 12;
$offset = ($page_num - 1) * $per_page;

// Build query — filter by thematic_categories JSON field
$where = "is_verified = 1 AND thematic_categories IS NOT NULL AND thematic_categories != '' AND thematic_categories != '[]'";
$params = [];
$types = '';

if ($active_label) {
    $where .= " AND thematic_categories LIKE ?";
    $params[] = '%"' . $active_label . '"%';
    $types .= 's';
}

$f_org = trim($_GET['org'] ?? '');
if ($f_org !== '') {
    $where .= " AND org_name = ?";
    $params[] = $f_org;
    $types .= 's';
}

$order = match ($sort) {
    'oldest' => 'created_at ASC',
    'newest' => 'created_at DESC',
    'az' => 'org_name ASC',
    'top-rated' => 'avg_rat DESC, created_at DESC',
    default => 'view_count DESC, created_at DESC', // most-viewed
};

// Count total
$count_sql = "SELECT COUNT(*) as total FROM submissions WHERE $where";
$count_stmt = $conn->prepare($count_sql);
if ($types)
    $count_stmt->bind_param($types, ...$params);
$count_stmt->execute();
$total_count = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_count / $per_page);

// Fetch page
if ($sort === 'top-rated') {
    $sql = "SELECT s.id, s.org_name, s.title, s.story, s.created_at, s.service_chains, s.enabling_pillars, s.thematic_categories, IFNULL(s.view_count, 0) as view_count, IFNULL(AVG(r.rating), 0) as avg_rat FROM submissions s LEFT JOIN ratings r ON s.id = r.item_id AND r.item_type = 'submission' WHERE $where GROUP BY s.id ORDER BY $order LIMIT ? OFFSET ?";
} else {
    $sql = "SELECT id, org_name, title, story, created_at, service_chains, enabling_pillars, thematic_categories, IFNULL(view_count, 0) as view_count FROM submissions WHERE $where ORDER BY $order LIMIT ? OFFSET ?";
}

$fetch_stmt = $conn->prepare($sql);
$fetch_types = $types . 'ii';
$fetch_params = array_merge($params, [$per_page, $offset]);
$fetch_stmt->bind_param($fetch_types, ...$fetch_params);
$fetch_stmt->execute();
$submissions = $fetch_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch media indicators
$sub_ids = array_column($submissions, 'id');
$media_counts = [];
if (!empty($sub_ids)) {
    $in = implode(',', array_fill(0, count($sub_ids), '?'));
    $m_stmt = $conn->prepare("SELECT submission_id, media_type, COUNT(*) as cnt FROM media_uploads WHERE submission_id IN ($in) GROUP BY submission_id, media_type");
    $m_stmt->bind_param(str_repeat('i', count($sub_ids)), ...$sub_ids);
    $m_stmt->execute();
    $m_res = $m_stmt->get_result();
    while ($m_row = $m_res->fetch_assoc()) {
        $media_counts[$m_row['submission_id']][$m_row['media_type']] = $m_row['cnt'];
    }
}

// Fetch Admin "Thematic Content" (Barriers content)
$admin_content = [];
$content_sql = "SELECT c.id, c.title, c.body, c.created_at, cat.title as cat_title
                FROM content c 
                JOIN categories cat ON c.category_id = cat.id 
                WHERE c.status = 'approved' ";
if ($active_cat_id > 0) {
    $content_sql .= " AND c.category_id = " . intval($active_cat_id);
} else {
    // Only grab content for barriers (category ids 1-9)
    $content_sql .= " AND c.category_id BETWEEN 1 AND 9";
}
$content_sql .= " ORDER BY c.created_at DESC";
$content_res = $conn->query($content_sql);
if ($content_res) {
    $admin_content = $content_res->fetch_all(MYSQLI_ASSOC);
}

// Fetch batch ratings for submissions
$current_user_id = $_SESSION['user_id'] ?? 0;
$batch_ratings = get_batch_ratings($conn, 'submission', $sub_ids);
$batch_user_ratings = $is_logged_in ? get_batch_user_ratings($conn, (int) $current_user_id, 'submission', $sub_ids) : [];

// Fetch batch ratings for admin content
$content_ids = array_column($admin_content, 'id');
$content_ratings = get_batch_ratings($conn, 'content', $content_ids);
$content_user_ratings = $is_logged_in ? get_batch_user_ratings($conn, (int) $current_user_id, 'content', $content_ids) : [];

// Helpers
function tr_clean($text)
{
    return htmlspecialchars(html_entity_decode($text, ENT_QUOTES | ENT_HTML5), ENT_QUOTES | ENT_HTML5);
}

function tr_url($sub = null, $sort = 'most-viewed', $page = 1)
{
    $params = [];
    if ($sub)
        $params['sub'] = $sub;
    if ($sort !== 'most-viewed')
        $params['sort'] = $sort;
    if ($page > 1)
        $params['page'] = $page;
    $qs = http_build_query($params);
    return 'thematic-repositories.php' . ($qs ? '?' . $qs : '');
}
?>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barriers | SaniBook Kenya</title>
    <meta name="description" content="Key sanitation bottlenecks and opportunities.">
    <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=Inter:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brand: {
                            dark: '#023047',
                            teal: '#219EBC',
                            gold: '#D4AF37',
                            red: '#dc2626',
                            lime: '#65a30d',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        display: ['Space Grotesk', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="icon" href="images/saniBook logo.png" type="image/png">
    <style>
        .fade-up {
            opacity: 0;
            transform: translateY(24px);
            transition: opacity 0.6s ease, transform 0.6s ease;
        }

        .fade-up.visible {
            opacity: 1;
            transform: translateY(0);
        }

        .card-hover:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.1);
        }

        /* Star Rating Styles */
        .star-rating-widget {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-bottom: 8px;
        }

        .star-rating-stars {
            display: flex;
            gap: 2px;
        }

        .star-rating-stars .star {
            color: #cbd5e1;
            font-size: 14px;
            cursor: default;
            transition: color 0.15s, transform 0.15s;
        }

        .star-rating-stars .star.filled {
            color: #facc15;
        }

        .star-rating-stars .star.user-rated {
            color: #f59e0b;
        }

        .star-rating-stars .star.clickable {
            cursor: pointer;
        }

        .star-rating-stars .star.clickable:hover {
            color: #f59e0b;
            transform: scale(1.2);
        }

        .star-rating-info {
            font-size: 11px;
            color: #94a3b8;
            font-weight: 600;
        }
    </style>
</head>

<body class="antialiased text-slate-900 bg-slate-50">

    <!-- Navbar -->
    <?php include 'navbar.php'; ?>

    <!-- Title block above hero -->
    <div class="bg-white border-b border-slate-100 py-8 text-center">
        <div class="max-w-7xl mx-auto px-4 flex flex-col items-center">
            <?php if ($active_sub): ?>
                <a href="thematic-repositories.php" class="text-sm font-semibold text-teal-600 hover:underline uppercase tracking-wider mb-1">
                    &larr; Thematic Repositories
                </a>
                <h1 class="font-display text-2xl md:text-3xl font-bold text-slate-900 mb-2 text-center">
                    <?php echo tr_clean($cat_map[$active_sub]['label']); ?>
                </h1>
                <p class="text-lg text-slate-600 max-w-3xl text-center mx-auto">
                    <?php echo tr_clean($cat_map[$active_sub]['desc']); ?>
                </p>
            <?php else: ?>
                <h1 class="font-display text-2xl md:text-3xl font-bold text-slate-900 mb-4 text-center">Barriers</h1>
                <p class="text-xl text-slate-600 max-w-2xl text-center mx-auto">
                    Explore the key sanitation bottlenecks and opportunities identified during the Second Sanitation
                    Accountability Symposium.
                </p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Page Header -->
    <?php if ($active_sub): ?>
        <header class="relative overflow-hidden h-[75vh] bg-slate-50">
            <img src="<?php echo tr_clean($cat_map[$active_sub]['image']); ?>"
                alt="<?php echo tr_clean($cat_map[$active_sub]['label']); ?>"
                class="w-full h-full object-contain object-center">
        </header>
    <?php else: ?>
        <header class="relative overflow-hidden h-[75vh] bg-slate-50">
            <img src="images/ch3_behavioral_change.jpg" alt="Barriers" class="w-full h-full object-contain object-center">
        </header>
    <?php endif; ?>



    <?php if (!$active_sub): ?>
        <!-- Thematic Repositories Grid -->
        <section id="nexus" class="py-20">
            <div class="max-w-7xl mx-auto px-4">
                <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">

                    <?php
                    // Category card data
                    $cards = [
                        ['id' => 1, 'slug' => 'why-sanitation-matters', 'title' => 'Why Sanitation Matters', 'desc' => 'The Economic Opportunity: Unlocking billions in value through sanitation.', 'img' => 'ch1_why_matters.jpg'],
                        ['id' => 2, 'slug' => 'coverage-gaps', 'title' => 'Coverage Gaps', 'desc' => 'The Unfinished Agenda: Identifying underserved regions.', 'img' => 'ch2_access_gaps.jpg'],
                        ['id' => 3, 'slug' => 'behavioral-barriers', 'title' => 'Behavioral Barriers', 'desc' => 'Shifting the Sewer-Centric View: Cultural and social adoption.', 'img' => 'ch3_behavioral_change.jpg'],
                        ['id' => 4, 'slug' => 'technology-adoption', 'title' => 'Technology Adoption', 'desc' => 'Systems & O&M Failures: Why tech fails and how to fix it.', 'img' => 'ch4_tech_innovation.jpg'],
                        ['id' => 5, 'slug' => 'chronic-underfunding', 'title' => 'Chronic Underfunding', 'desc' => 'From Cost to Investment: Financing the revolution.', 'img' => 'ch5_financing.jpg'],
                        ['id' => 6, 'slug' => 'fragmented-governance', 'title' => 'Fragmented Governance', 'desc' => 'Bridging the Divide: Policy and regulation alignment.', 'img' => 'ch6_governance.jpg'],
                        ['id' => 7, 'slug' => 'data-deficiencies', 'title' => 'Data Deficiencies', 'desc' => 'The Invisible Crisis: We cannot fix what we cannot see.', 'img' => 'ch7_data_hub.jpg'],
                        ['id' => 8, 'slug' => 'unmet-aspirations', 'title' => 'Unmet Aspirations', 'desc' => 'Elevating the Frontline: Community voices and needs.', 'img' => 'ch8_frontline_heroes.jpg'],
                        ['id' => 9, 'slug' => 'stakeholder-portal', 'title' => 'Stakeholder Portal', 'desc' => 'Join the National Database: Register your organization.', 'img' => 'ch9_stakeholder_portal.jpg'],
                    ];

                    foreach ($cards as $card):
                        $stats = get_detailed_category_stats($card['id']);
                        $is_portal = ($card['id'] === 9);
                        ?>
                        <a href="<?php echo tr_url($card['slug'], $sort); ?>#official-content" <?php if ($is_portal)
                                echo 'id="portal"'; ?>
                            class="group bg-brand-teal rounded-2xl p-8 shadow-sm hover:shadow-xl transition-all border border-teal-600 card-hover <?php echo $is_portal ? 'relative overflow-hidden' : ''; ?>">
                            <?php if ($is_portal): ?>
                                <div class="absolute inset-0 bg-white/5 opacity-0 group-hover:opacity-100 transition-opacity"></div>
                            <?php endif; ?>
                            <div class="h-36 mb-6 overflow-hidden rounded-xl bg-brand-dark/20">
                                <img src="images/<?php echo $card['img']; ?>" alt="<?php echo tr_clean($card['title']); ?>"
                                    class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500 opacity-90 group-hover:opacity-100">
                            </div>
                            <h3 class="font-display text-2xl font-bold mb-2 text-white">
                                <?php echo tr_clean($card['title']); ?>
                            </h3>
                            <p class="text-lg text-white/80 mb-4 line-clamp-2"><?php echo tr_clean($card['desc']); ?></p>
                            <div class="flex items-center gap-2 text-sm font-medium text-white/90">
                                <i class="fa-solid fa-file-pen"></i>
                                <?php echo "{$stats['chronicles']} Chronicles, {$stats['story']} data"; ?>
                            </div>
                        </a>
                    <?php endforeach; ?>

                </div>
            </div>
        </section>
    <?php endif; ?>

    <!-- Admin Content Listing -->
    <?php if (!empty($admin_content)): ?>
        <section class="py-16 bg-slate-50 border-b border-slate-200" id="official-content">
            <?php if (!$active_sub): ?>
                <div class="max-w-7xl mx-auto px-4">
                    <h2
                        class="font-display font-bold text-3xl text-brand-dark mb-8 flex items-center justify-center gap-3 text-center">
                        <i class="fa-solid fa-file-contract text-brand-teal"></i>
                        Official <?php echo $active_label ? tr_clean($active_label) : 'Barriers'; ?> Content
                    </h2>

                    <!-- Filter Pills (Main Category Page) -->
                    <div class="flex flex-wrap gap-2 mb-8">
                        <a href="<?php echo tr_url(null, $sort); ?>#official-content"
                            class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo !$active_sub ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                            All
                        </a>
                        <?php foreach ($cat_map as $slug => $data): ?>
                            <a href="<?php echo tr_url($slug, $sort); ?>#official-content"
                                class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $active_sub === $slug ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                <?php echo tr_clean($data['label']); ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <!-- Sub Category Page: Sidebar for Desktop, Pills for Mobile -->
                    <div class="max-w-7xl mx-auto px-4 flex flex-col md:flex-row gap-8">
                        <!-- Sidebar -->
                        <div class="w-full md:w-1/4 hidden md:block">
                            <div class="sticky top-24 bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                                <h3 class="font-display font-bold text-lg text-slate-800 mb-4 border-b border-slate-100 pb-2">
                                    Categories</h3>
                                <nav class="space-y-2">
                                    <a href="<?php echo tr_url(null, $sort); ?>#official-content"
                                        class="block px-4 py-2 rounded-lg text-sm font-medium transition-all <?php echo !$active_sub ? 'bg-brand-teal text-white' : 'text-slate-600 hover:bg-slate-50 hover:text-brand-teal'; ?>">
                                        All Barriers
                                    </a>
                                    <?php foreach ($cat_map as $slug => $data): ?>
                                        <a href="<?php echo tr_url($slug, $sort); ?>#official-content"
                                            class="block px-4 py-2 rounded-lg text-sm font-medium transition-all <?php echo $active_sub === $slug ? 'bg-brand-teal text-white' : 'text-slate-600 hover:bg-slate-50 hover:text-brand-teal'; ?>">
                                            <?php echo tr_clean($data['label']); ?>
                                        </a>
                                    <?php endforeach; ?>
                                </nav>
                            </div>
                        </div>

                        <!-- Filter Pills (Mobile Only) -->
                        <div class="w-full md:hidden mb-8">
                            <div class="flex flex-wrap gap-2">
                                <a href="<?php echo tr_url(null, $sort); ?>#official-content"
                                    class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo !$active_sub ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                    All
                                </a>
                                <?php foreach ($cat_map as $slug => $data): ?>
                                    <a href="<?php echo tr_url($slug, $sort); ?>#official-content"
                                        class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $active_sub === $slug ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                        <?php echo tr_clean($data['label']); ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Main Content Area -->
                        <div class="w-full md:w-3/4">

                            <h2 class="font-display font-bold text-3xl text-brand-dark mb-8 flex items-center gap-3">
                                <i class="fa-solid fa-file-contract text-brand-teal"></i>
                                Official <?php echo $active_label ? tr_clean($active_label) : 'Barriers'; ?> Content
                            </h2>
                        <?php endif; ?>
                        <div class="grid md:grid-cols-2 gap-6 fade-up">
                            <?php foreach ($admin_content as $ac):
                                $date = date("M d, Y", strtotime($ac['created_at']));
                                $snippet = htmlspecialchars(mb_strimwidth(strip_tags($ac['body']), 0, 150, '...'));
                                ?>
                                <div
                                    class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 hover:shadow-md transition-all border-l-4 border-l-brand-teal flex flex-col h-full">
                                    <?php if (!$active_sub): ?>
                                        <div class="text-xs font-bold uppercase text-brand-gold tracking-wider mb-2">
                                            <i class="fa-solid fa-folder-open mr-1"></i> <?php echo tr_clean($ac['cat_title']); ?>
                                        </div>
                                    <?php endif; ?>
                                    <h3 class="font-bold text-lg text-slate-800 mb-2 line-clamp-2">
                                        <a href="view_content.php?id=<?php echo $ac['id']; ?>"
                                            class="hover:text-brand-teal transition-colors">
                                            <?php echo tr_clean($ac['title']); ?>
                                        </a>
                                    </h3>
                                    <div class="text-slate-600 text-sm mb-4 line-clamp-3">
                                        <?php echo $snippet; ?>
                                    </div>
                                    <!-- Star Rating -->
                                    <?php
                                    $cr_avg = $content_ratings[$ac['id']]['avg'] ?? 0;
                                    $cr_cnt = $content_ratings[$ac['id']]['count'] ?? 0;
                                    $cr_user = $content_user_ratings[$ac['id']] ?? 0;
                                    echo render_stars($cr_avg, $cr_cnt, 'content', $ac['id'], $cr_user, $is_logged_in);
                                    ?>
                                    <div class="flex items-center justify-between mt-auto pt-4 border-t border-slate-100">
                                        <span class="text-xs font-medium text-slate-400"><i
                                                class="fa-solid fa-calendar-day mr-1"></i><?php echo $date; ?></span>
                                        <a href="view_content.php?id=<?php echo $ac['id']; ?>"
                                            class="text-brand-teal font-bold text-sm hover:underline">Read More <i
                                                class="fa-solid fa-arrow-right ml-1"></i></a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <!-- Pagination -->
                        <?php if ($active_sub): ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </section>
    <?php endif; ?>

    <!-- Share Your Story CTA (on sub-category pages) -->
    <?php if ($active_sub && $active_cat_id > 0): ?>
        <section class="py-12 bg-white" id="submissions">
            <div class="max-w-7xl mx-auto px-4 text-center">
                <div class="bg-gradient-to-r from-brand-teal/5 to-brand-dark/5 rounded-2xl p-10 border border-slate-200">
                    <i class="fa-solid fa-pen-to-square text-4xl text-brand-teal mb-4"></i>
                    <h2 class="font-display font-bold text-2xl text-slate-800 mb-3">Have a Story to Share?</h2>
                    <p class="text-slate-500 max-w-xl mx-auto mb-6">
                        Share your experience on <strong><?php echo tr_clean($active_label); ?></strong> — it's free for all
                        registered users and helps drive change.
                    </p>
                    <a href="#share-story"
                        class="inline-flex items-center gap-2 px-8 py-3 bg-brand-teal text-white rounded-lg font-bold hover:bg-brand-teal/90 transition-all shadow-lg">
                        <i class="fa-solid fa-pen-fancy"></i> Share Your Story
                    </a>
                </div>
            </div>
        </section>
    <?php endif; ?>

    <!-- Share Your Story Form (only on sub-category pages) -->
    <?php if ($active_sub && $active_cat_id > 0): ?>
        <section class="py-16 bg-gradient-to-br from-brand-teal/5 to-brand-dark/5" id="share-story">
            <div class="max-w-3xl mx-auto px-4">
                <div class="bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
                    <!-- Header -->
                    <div class="bg-gradient-to-r from-brand-teal to-brand-dark p-8 text-white text-center">
                        <div
                            class="w-16 h-16 mx-auto bg-white/20 backdrop-blur-sm rounded-2xl flex items-center justify-center mb-4">
                            <i class="fa-solid fa-pen-fancy text-3xl"></i>
                        </div>
                        <h2 class="text-2xl font-display font-bold">Share Your Story</h2>
                        <p class="text-white/80 mt-2">Share your experience on
                            <strong><?php echo tr_clean($active_label); ?></strong> — it's free and helps drive change.
                        </p>
                    </div>

                    <?php if ($is_logged_in): ?>
                        <div class="p-8">
                            <!-- Status messages -->
                            <div id="story-success"
                                class="hidden bg-green-50 border border-green-200 text-green-800 px-4 py-3 rounded-lg mb-6">
                                <i class="fa-solid fa-check-circle mr-2"></i><span id="story-success-msg"></span>
                            </div>
                            <div id="story-error"
                                class="hidden bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg mb-6">
                                <i class="fa-solid fa-triangle-exclamation mr-2"></i><span id="story-error-msg"></span>
                            </div>

                            <form id="story-form">
                                <input type="hidden" name="barrier_category_id" value="<?php echo $active_cat_id; ?>">

                                <!-- Title -->
                                <div class="mb-6">
                                    <label class="block text-sm font-bold text-slate-700 mb-2">Story Title <span
                                            class="text-red-500">*</span></label>
                                    <input type="text" name="story_title" id="story-title" required minlength="5"
                                        maxlength="200"
                                        class="w-full px-4 py-3 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-teal focus:border-brand-teal text-slate-800"
                                        placeholder="Give your story a meaningful title...">
                                </div>

                                <!-- Rich Text Editor -->
                                <div class="mb-6">
                                    <label class="block text-sm font-bold text-slate-700 mb-2">Your Story <span
                                            class="text-red-500">*</span></label>
                                    <div id="story-editor" style="min-height:200px; background:#f8fafc;"></div>
                                    <div class="flex justify-between mt-1">
                                        <p class="text-xs text-slate-400">Min 20 characters, max 10,000</p>
                                        <p class="text-xs text-slate-400" id="story-char-count">0 characters</p>
                                    </div>
                                </div>

                                <!-- County -->
                                <div class="mb-8">
                                    <label class="block text-sm font-bold text-slate-700 mb-2">County (optional)</label>
                                    <select name="story_county"
                                        class="w-full px-4 py-3 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-teal focus:border-brand-teal bg-white text-slate-800">
                                        <option value="">Select county...</option>
                                        <?php
                                        $counties = ['Baringo', 'Bomet', 'Bungoma', 'Busia', 'Elgeyo-Marakwet', 'Embu', 'Garissa', 'Homa Bay', 'Isiolo', 'Kajiado', 'Kakamega', 'Kericho', 'Kiambu', 'Kilifi', 'Kirinyaga', 'Kisii', 'Kisumu', 'Kitui', 'Kwale', 'Laikipia', 'Lamu', 'Machakos', 'Makueni', 'Mandera', 'Marsabit', 'Meru', 'Migori', 'Mombasa', 'Murang\'a', 'Nairobi', 'Nakuru', 'Nandi', 'Narok', 'Nyamira', 'Nyandarua', 'Nyeri', 'Samburu', 'Siaya', 'Taita-Taveta', 'Tana River', 'Tharaka-Nithi', 'Trans-Nzoia', 'Turkana', 'Uasin Gishu', 'Vihiga', 'Wajir', 'West Pokot'];
                                        foreach ($counties as $c):
                                            ?>
                                            <option value="<?php echo $c; ?>"><?php echo $c; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <!-- Submit -->
                                <button type="submit" id="story-submit-btn"
                                    class="w-full py-4 bg-brand-teal text-white rounded-lg font-bold text-lg hover:bg-brand-teal/90 transition-all shadow-lg flex items-center justify-center gap-2">
                                    <i class="fa-solid fa-paper-plane"></i> Submit Story for Review
                                </button>
                                <p class="text-xs text-slate-400 text-center mt-3">
                                    <i class="fa-solid fa-shield-halved mr-1"></i>
                                    Free submission — no tokens required. Your story will be published after admin approval.
                                </p>
                            </form>
                        </div>
                    <?php else: ?>
                        <!-- Login CTA -->
                        <div class="p-10 text-center">
                            <div class="w-16 h-16 mx-auto bg-amber-100 rounded-full flex items-center justify-center mb-4">
                                <i class="fa-solid fa-lock text-amber-600 text-2xl"></i>
                            </div>
                            <h3 class="text-lg font-bold text-slate-800 mb-2">Login to Share Your Story</h3>
                            <p class="text-slate-500 text-sm mb-6">Create a free account or log in to share your sanitation
                                experience.</p>
                            <a href="login.php?redirect=<?php echo urlencode('thematic-repositories.php?sub=' . $active_sub . '#share-story'); ?>"
                                class="inline-flex items-center gap-2 px-8 py-3 bg-brand-teal text-white rounded-lg font-bold hover:bg-brand-teal/90 transition-all">
                                <i class="fa-solid fa-right-to-bracket"></i> Login / Register
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
    <?php endif; ?>

    <!-- Submissions Listing -->
    <?php if (!empty($submissions)): ?>
        <section class="py-16 bg-slate-50 border-b border-slate-200" id="submissions">
            <?php if (!$active_sub): ?>
                <div class="max-w-7xl mx-auto px-4">
                    <h2
                        class="font-display font-bold text-3xl text-brand-dark mb-8 flex items-center justify-center gap-3 text-center">
                        <i class="fa-solid fa-pen-to-square text-brand-teal"></i>
                        Community Stories on <?php echo tr_clean($active_label); ?>
                    </h2>

                    <!-- Filter Pills (Main Category Page) -->
                    <div class="flex flex-wrap items-center justify-center gap-2 mb-8 text-center">
                        <a href="<?php echo tr_url($active_sub, 'most-viewed'); ?>#submissions"
                            class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $sort === 'most-viewed' ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                            <i class="fa-solid fa-fire mr-2"></i> Most Viewed
                        </a>
                        <a href="<?php echo tr_url($active_sub, 'top-rated'); ?>#submissions"
                            class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $sort === 'top-rated' ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                            <i class="fa-solid fa-star mr-2"></i> Highest Rated
                        </a>
                        <a href="<?php echo tr_url($active_sub, 'newest'); ?>#submissions"
                            class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $sort === 'newest' ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                            <i class="fa-solid fa-arrow-down-wide-short mr-2"></i> Newest First
                        </a>
                    </div>
                <?php else: ?>
                    <!-- Sub Category Page: Sidebar for Desktop, Pills for Mobile -->
                    <div class="max-w-7xl mx-auto px-4 flex flex-col md:flex-row gap-8">
                        <!-- Sidebar -->
                        <div class="w-full md:w-1/4 hidden md:block">
                            <div class="sticky top-24 bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                                <h3 class="font-display font-bold text-lg text-slate-800 mb-4 border-b border-slate-100 pb-2">
                                    Filter Submissions</h3>
                                <nav class="space-y-2">
                                    <a href="<?php echo tr_url($active_sub, 'most-viewed'); ?>#submissions"
                                        class="block px-4 py-2 rounded-lg text-sm font-medium transition-all <?php echo $sort === 'most-viewed' ? 'bg-brand-teal text-white' : 'text-slate-600 hover:bg-slate-50 hover:text-brand-teal'; ?>">
                                        <i class="fa-solid fa-fire mr-2"></i> Most Viewed
                                    </a>
                                    <a href="<?php echo tr_url($active_sub, 'top-rated'); ?>#submissions"
                                        class="block px-4 py-2 rounded-lg text-sm font-medium transition-all <?php echo $sort === 'top-rated' ? 'bg-brand-teal text-white' : 'text-slate-600 hover:bg-slate-50 hover:text-brand-teal'; ?>">
                                        <i class="fa-solid fa-star mr-2"></i> Highest Rated
                                    </a>
                                    <a href="<?php echo tr_url($active_sub, 'newest'); ?>#submissions"
                                        class="block px-4 py-2 rounded-lg text-sm font-medium transition-all <?php echo $sort === 'newest' ? 'bg-brand-teal text-white' : 'text-slate-600 hover:bg-slate-50 hover:text-brand-teal'; ?>">
                                        <i class="fa-solid fa-arrow-down-wide-short mr-2"></i> Newest First
                                    </a>
                                </nav>
                            </div>
                        </div>

                        <!-- Filter Pills (Mobile Only) -->
                        <div class="w-full md:hidden mb-8">
                            <div class="flex flex-wrap gap-2">
                                <a href="<?php echo tr_url($active_sub, 'most-viewed'); ?>#submissions"
                                    class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $sort === 'most-viewed' ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                    <i class="fa-solid fa-fire mr-2"></i> Most Viewed
                                </a>
                                <a href="<?php echo tr_url($active_sub, 'top-rated'); ?>#submissions"
                                    class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $sort === 'top-rated' ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                    <i class="fa-solid fa-star mr-2"></i> Highest Rated
                                </a>
                                <a href="<?php echo tr_url($active_sub, 'newest'); ?>#submissions"
                                    class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $sort === 'newest' ? 'bg-brand-teal text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                    <i class="fa-solid fa-arrow-down-wide-short mr-2"></i> Newest First
                                </a>
                            </div>
                        </div>

                        <!-- Main Content Area -->
                        <div class="w-full md:w-3/4">
                            <div class="mb-8">
                                <h2 class="font-heading font-bold text-xl text-slate-800">Submitted Data</h2>
                                <p class="text-xs text-slate-500">
                                    Community submissions related to <?php echo tr_clean($active_label); ?>
                                </p>
                            </div>
                        <?php endif; ?>
                        <div class="grid md:grid-cols-2 gap-6 fade-up">
                            <?php foreach ($submissions as $sub):
                                $date = date("M d, Y", strtotime($sub['created_at']));
                                $snippet = htmlspecialchars(mb_strimwidth(strip_tags($sub['body']), 0, 150, '...'));
                                ?>
                                <div
                                    class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 hover:shadow-md transition-all border-l-4 border-l-brand-teal flex flex-col h-full">
                                    <div class="flex items-center justify-between mb-2">
                                        <h3 class="font-bold text-lg text-slate-800 line-clamp-2">
                                            <a href="view_submission.php?id=<?php echo $sub['id']; ?>"
                                                class="hover:text-brand-teal transition-colors">
                                                <?php echo tr_clean($sub['title']); ?>
                                            </a>
                                        </h3>
                                        <div class="text-xs text-slate-400 shrink-0 ml-2"
                                            title="<?php echo number_format((int) $sub['view_count']); ?> views">
                                            <i
                                                class="fa-regular fa-eye mr-1"></i><?php echo number_format((int) $sub['view_count']); ?>
                                        </div>
                                    </div>
                                    <div class="text-slate-600 text-sm mb-4 line-clamp-3">
                                        <?php echo $snippet; ?>
                                    </div>
                                    <!-- Star Rating -->
                                    <?php
                                    $sr_avg = $batch_ratings[$sub['id']]['avg'] ?? 0;
                                    $sr_cnt = $batch_ratings[$sub['id']]['count'] ?? 0;
                                    $sr_user = $batch_user_ratings[$sub['id']] ?? 0;
                                    echo render_stars($sr_avg, $sr_cnt, 'submission', $sub['id'], $sr_user, $is_logged_in);
                                    ?>
                                    <div class="flex items-center justify-between mt-auto pt-4 border-t border-slate-100">
                                        <span class="text-xs font-medium text-slate-400"><i
                                                class="fa-solid fa-calendar-day mr-1"></i><?php echo $date; ?></span>
                                        <a href="view_submission.php?id=<?php echo $sub['id']; ?>"
                                            class="text-brand-teal font-bold text-sm hover:underline">Read More <i
                                                class="fa-solid fa-arrow-right ml-1"></i></a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <div class="flex items-center justify-center gap-2 mt-12">
                                <?php if ($page_num > 1): ?>
                                    <a href="<?php echo tr_url($active_sub, $sort, $page_num - 1); ?>#submissions"
                                        class="px-4 py-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 font-semibold text-slate-700">
                                        <i class="fa-solid fa-chevron-left mr-1"></i> Previous
                                    </a>
                                <?php endif; ?>

                                <span class="px-4 py-2 text-slate-600 font-semibold">
                                    Page <?php echo $page_num; ?> of <?php echo $total_pages; ?>
                                </span>

                                <?php if ($page_num < $total_pages): ?>
                                    <a href="<?php echo tr_url($active_sub, $sort, $page_num + 1); ?>#submissions"
                                        class="px-4 py-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 font-semibold text-slate-700">
                                        Next <i class="fa-solid fa-chevron-right ml-1"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        <?php if ($active_sub): ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </section>
    <?php endif; ?>

    <!-- Footer -->
    <?php include 'footer.php'; ?>

    <script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
    <script>
        // Fade-up observer
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) entry.target.classList.add('visible');
            });
        }, { threshold: 0.1 });
        document.querySelectorAll('.fade-up').forEach(el => observer.observe(el));

        // Star rating click handler
        document.querySelectorAll('.star-rating-widget .star.clickable').forEach(star => {
            star.addEventListener('click', function () {
                const widget = this.closest('.star-rating-widget');
                const itemType = widget.dataset.itemType;
                const itemId = widget.dataset.itemId;
                const rating = this.dataset.value;

                fetch('rate_item.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `item_type=${encodeURIComponent(itemType)}&item_id=${encodeURIComponent(itemId)}&rating=${encodeURIComponent(rating)}`
                })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            const stars = widget.querySelectorAll('.star');
                            stars.forEach(s => {
                                const v = parseInt(s.dataset.value);
                                const icon = s.querySelector('i');
                                s.classList.toggle('user-rated', v <= data.user_rating);
                                s.classList.toggle('filled', v <= Math.round(data.avg_rating));
                                icon.className = v <= data.user_rating ? 'fas fa-star' : (v <= Math.round(data.avg_rating) ? 'fas fa-star' : 'far fa-star');
                            });
                            widget.querySelector('.star-rating-info').textContent = data.avg_rating + ' (' + data.total_ratings + ')';
                        }
                    })
                    .catch(() => { });
            });
        });

        // Quill editor for story form
        const editorEl = document.getElementById('story-editor');
        if (editorEl) {
            const quill = new Quill('#story-editor', {
                theme: 'snow',
                modules: {
                    toolbar: [
                        [{ 'header': [2, 3, false] }],
                        ['bold', 'italic', 'underline'],
                        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                        ['blockquote', 'link'],
                        ['clean']
                    ]
                },
                placeholder: 'Write your story here...'
            });

            // Character counter
            const charCounter = document.getElementById('story-char-count');
            quill.on('text-change', function () {
                const len = quill.getText().trim().length;
                charCounter.textContent = len.toLocaleString() + ' characters';
                charCounter.className = len > 10000 ? 'text-xs text-red-500 font-bold' : 'text-xs text-slate-400';
            });

            // Submit handler
            document.getElementById('story-form').addEventListener('submit', function (e) {
                e.preventDefault();
                const btn = document.getElementById('story-submit-btn');
                const successEl = document.getElementById('story-success');
                const errorEl = document.getElementById('story-error');

                successEl.classList.add('hidden');
                errorEl.classList.add('hidden');

                const formData = new FormData(this);
                formData.set('story_content', quill.root.innerHTML);

                btn.disabled = true;
                btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> Submitting...';

                fetch('submit-story.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(r => r.json())
                    .then(data => {
                        if (data.status === 'success') {
                            document.getElementById('story-success-msg').textContent = data.message;
                            successEl.classList.remove('hidden');
                            // Reset form
                            document.getElementById('story-title').value = '';
                            quill.setText('');
                            charCounter.textContent = '0 characters';
                        } else {
                            document.getElementById('story-error-msg').textContent = data.message;
                            errorEl.classList.remove('hidden');
                        }
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fa-solid fa-paper-plane"></i> Submit Story for Review';
                        successEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    })
                    .catch(err => {
                        document.getElementById('story-error-msg').textContent = 'Connection error. Please try again.';
                        errorEl.classList.remove('hidden');
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fa-solid fa-paper-plane"></i> Submit Story for Review';
                    });
            });
        }
    </script>
    <!-- Auto-scroll to results when filters are active -->
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const params = new URLSearchParams(window.location.search);
            if (params.get('org') || params.get('q')) {
                const target = document.getElementById('submissions');
                if (target) {
                    setTimeout(function () {
                        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }, 300);
                }
            }
        });
    </script>
</body>

</html>