<?php
session_start();
require_once 'config.php';
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Join Us | SaniBook Kenya</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=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" />

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brand: {
                            dark: '#0f172a',
                            blue: '#2563eb',
                            cyan: '#0891b2',
                            red: '#dc2626',
                            lime: '#65a30d',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        display: ['Space Grotesk', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style>
        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #ffffff;
        }

        .nav-scrolled {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid #e5e7eb;
        }

        .fade-up {
            opacity: 0;
            transform: translateY(24px);
            transition: opacity 0.6s ease, transform 0.6s ease;
        }

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

        .menu-open {
            transform: translateX(0);
        }

        .menu-closed {
            transform: translateX(100%);
        }

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

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

    <?php include 'navbar.php'; ?>

    <main class="pt-20">
        <!-- Hero -->
        <header class="relative bg-slate-50 py-20 lg:py-28 text-center overflow-hidden">
            <!-- Background Accents -->
            <div
                class="absolute top-0 left-1/2 -translate-x-1/2 w-[800px] h-[800px] bg-brand-lime/5 rounded-full blur-[120px] -z-10 pointer-events-none">
            </div>

            <div class="max-w-4xl mx-auto px-4 fade-up">
                <h1 class="text-3xl md:text-4xl font-display font-bold text-slate-900 mb-6">
                    Join The <span class="text-brand-lime">Sanitationists.</span>
                </h1>
                <p class="text-xl text-slate-600 leading-relaxed mb-6">
                    SaniBook is more than a platform; it's a movement. Whether you are an organization with data or
                    an individual with expertise, your contribution builds the national blueprint.
                </p>
                <?php if (!$is_logged_in): ?>
                    <p class="text-lg text-brand-blue font-bold mb-10">
                        Please register or login below to submit your data.
                    </p>
                <?php else: ?>
                    <div class="inline-block bg-blue-100 text-brand-blue px-6 py-2 rounded-full font-bold mb-10">
                        Welcome, <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'User'); ?>
                    </div>
                <?php endif; ?>
            </div>
        </header>

        <!-- Main Interaction Section -->
        <section id="action-portal" class="py-12 bg-white relative z-10">
            <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">

                <?php if (!$is_logged_in): ?>
                    <!-- Registration / Login Container -->
                    <div
                        class="bg-white rounded-[2.5rem] shadow-2xl border border-slate-100 overflow-hidden max-w-xl mx-auto">
                        <!-- Custom Inline Auth Logic derived from auth_modal.php but inline -->
                        <div class="p-8 md:p-12">
                            <!-- Tabs -->
                            <div class="flex border-b border-slate-200 mb-8">
                                <button onclick="switchInlineAuth('signup')" id="inlineSignupTab"
                                    class="flex-1 py-4 font-bold text-slate-900 border-b-2 border-brand-lime transition-all">
                                    Register
                                </button>
                                <button onclick="switchInlineAuth('login')" id="inlineLoginTab"
                                    class="flex-1 py-4 font-bold text-slate-400 border-b-2 border-transparent hover:text-slate-600 transition-all">
                                    Login
                                </button>
                            </div>

                            <!-- Signup Form -->
                            <div id="inlineSignupForm">
                                <div class="text-center mb-6">
                                    <h2 class="text-2xl font-bold text-slate-900">Create Account</h2>
                                    <p class="text-slate-500 text-sm mt-1">Join the sanitation movement to submit data.</p>
                                </div>
                                <div id="inlineSignupError"
                                    class="hidden bg-red-50 border-l-4 border-red-500 text-red-700 p-3 mb-4 rounded text-sm">
                                </div>
                                <div id="inlineSignupSuccess"
                                    class="hidden bg-green-50 border-l-4 border-green-500 text-green-700 p-3 mb-4 rounded text-sm">
                                </div>

                                <form id="inlineSignupFormElement" class="space-y-6" onsubmit="handleInlineSignup(event)">
                                    <!-- User Type Toggle -->
                                    <div class="flex justify-center mb-6">
                                        <div class="inline-flex bg-slate-100 p-1 rounded-lg border border-slate-200">
                                            <button type="button" onclick="setSignupType('organization')" id="type-org"
                                                class="px-4 py-2 rounded-md text-sm font-bold transition-all bg-brand-dark text-white shadow-sm">Organization</button>
                                            <button type="button" onclick="setSignupType('individual')" id="type-ind"
                                                class="px-4 py-2 rounded-md text-sm font-bold transition-all text-slate-500 hover:text-brand-dark">Individual</button>
                                        </div>
                                        <input type="hidden" name="user_type" id="signup_user_type" value="organization">
                                    </div>

                                    <!-- Personal Details Section -->
                                    <div class="space-y-4">
                                        <h3
                                            class="text-xs font-bold text-slate-400 uppercase tracking-widest border-b pb-2">
                                            Personal Representative Details</h3>
                                        <div class="grid grid-cols-3 gap-3">
                                            <div class="col-span-1">
                                                <label
                                                    class="block text-sm font-semibold text-slate-700 mb-1">Salutation</label>
                                                <select name="salutation" autocomplete="honorific-prefix"
                                                    class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all">
                                                    <option value="Mr.">Mr.</option>
                                                    <option value="Ms.">Ms.</option>
                                                    <option value="Dr.">Dr.</option>
                                                    <option value="Prof.">Prof.</option>
                                                    <option value="Eng.">Eng.</option>
                                                </select>
                                            </div>
                                            <div class="col-span-2">
                                                <label class="block text-sm font-semibold text-slate-700 mb-1">Full
                                                    Name</label>
                                                <input type="text" name="personal_name" required autocomplete="name"
                                                    class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all placeholder:text-slate-400"
                                                    placeholder="e.g. John Doe">
                                            </div>
                                        </div>
                                        <div class="grid grid-cols-2 gap-3">
                                            <div>
                                                <label
                                                    class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Personal
                                                    Email</label>
                                                <input type="email" name="personal_email" autocomplete="email"
                                                    class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all text-sm"
                                                    placeholder="john@personal.com">
                                            </div>
                                            <div>
                                                <label
                                                    class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Personal
                                                    Phone</label>
                                                <input type="tel" name="personal_phone" autocomplete="tel"
                                                    class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all text-sm"
                                                    placeholder="+254...">
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Company Details Section (Toggled) -->
                                    <div id="company-section" class="space-y-4 pt-4 border-t">
                                        <h3
                                            class="text-xs font-bold text-slate-400 uppercase tracking-widest border-b pb-2">
                                            Organization Details</h3>
                                        <div>
                                            <label class="block text-sm font-semibold text-slate-700 mb-1">Organization
                                                Name</label>
                                            <input type="text" id="signup_org_name" name="org_name"
                                                autocomplete="organization"
                                                class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all"
                                                placeholder="Company or Entity Name">
                                        </div>
                                        <div class="grid grid-cols-2 gap-3">
                                            <div>
                                                <label
                                                    class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Company
                                                    Email</label>
                                                <input type="email" name="company_email" autocomplete="organization email"
                                                    class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all text-sm"
                                                    placeholder="info@company.com">
                                            </div>
                                            <div>
                                                <label
                                                    class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Company
                                                    Phone</label>
                                                <input type="tel" name="company_phone" autocomplete="organization tel"
                                                    class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all text-sm"
                                                    placeholder="Tel: +254...">
                                            </div>
                                        </div>
                                        <div>
                                            <label
                                                class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Designation
                                                / Role</label>
                                            <input type="text" name="designation" autocomplete="organization-title"
                                                class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all text-sm"
                                                placeholder="e.g. Managing Director">
                                        </div>
                                        <div>
                                            <label
                                                class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Website</label>
                                            <input type="text" name="website" autocomplete="url"
                                                class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all text-sm"
                                                placeholder="e.g. www.organization.org">
                                        </div>

                                        <!-- Counties of Operation (Multi-Select) -->
                                        <div>
                                            <label class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Counties
                                                of Operation</label>
                                            <div class="relative" id="county-multi-select">
                                                <div
                                                    class="flex flex-wrap gap-2 p-2 border border-slate-300 rounded-lg bg-white min-h-[42px] focus-within:ring-2 focus-within:ring-brand-lime focus-within:border-brand-lime transition-all">
                                                    <div id="selected-counties-container" class="flex flex-wrap gap-2">
                                                    </div>
                                                    <input type="text" id="county-search"
                                                        class="flex-1 min-w-[120px] outline-none text-sm bg-transparent border-none focus:ring-0 p-0"
                                                        placeholder="Type to search counties...">
                                                </div>
                                                <div id="county-dropdown"
                                                    class="hidden absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-xl max-h-48 overflow-y-auto">
                                                    <!-- Options will be injected here -->
                                                </div>
                                                <input type="hidden" name="counties[]" id="counties-hidden-input">
                                            </div>
                                            <p class="text-[10px] text-slate-500 mt-1">Select all counties where you have
                                                offered services.</p>
                                        </div>
                                    </div>

                                    <!-- Account Credentials -->
                                    <div class="space-y-4 pt-4 border-t">
                                        <h3
                                            class="text-xs font-bold text-slate-400 uppercase tracking-widest border-b pb-2">
                                            Account Login Credentials</h3>
                                        <div>
                                            <label class="block text-sm font-semibold text-slate-700 mb-1">Primary Login
                                                Email</label>
                                            <input type="email" name="email" required
                                                class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all"
                                                placeholder="Registration Email">
                                        </div>
                                        <div class="grid grid-cols-2 gap-3">
                                            <div>
                                                <label
                                                    class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Password</label>
                                                <input type="password" name="password" required minlength="6"
                                                    class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all"
                                                    placeholder="••••••••">
                                            </div>
                                            <div>
                                                <label
                                                    class="block text-sm font-semibold text-slate-700 mb-1 text-xs">Confirm</label>
                                                <input type="password" name="confirm_password" required minlength="6"
                                                    class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-lime focus:border-brand-lime outline-none transition-all"
                                                    placeholder="••••••••">
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Sector Involvement -->
                                    <div class="space-y-4 pt-4 border-t">
                                        <h3
                                            class="text-xs font-bold text-slate-400 uppercase tracking-widest border-b pb-2">
                                            Sector Involvement</h3>

                                        <div>
                                            <label class="block text-[10px] font-bold text-slate-500 uppercase mb-2">Service
                                                Chain(s)</label>
                                            <div
                                                class="grid grid-cols-2 gap-2 max-h-32 overflow-y-auto p-2 bg-slate-50 rounded border">
                                                <?php
                                                $chains = ["Capture & Containment", "Emptying & Transport", "Treatment & Disposal", "Reuse & Circular Economy"];
                                                foreach ($chains as $c): ?>
                                                    <label
                                                        class="flex items-center gap-2 text-[11px] cursor-pointer hover:bg-white p-1 rounded transition-colors">
                                                        <input type="checkbox" name="service_chains[]" value="<?php echo $c; ?>"
                                                            class="rounded border-slate-300 text-brand-lime focus:ring-brand-lime">
                                                        <span class="text-slate-600"><?php echo $c; ?></span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>

                                        <div>
                                            <label
                                                class="block text-[10px] font-bold text-slate-500 uppercase mb-2">Enabling
                                                Pillar(s)</label>
                                            <div
                                                class="grid grid-cols-2 gap-2 max-h-32 overflow-y-auto p-2 bg-slate-50 rounded border">
                                                <?php
                                                $pillars = ["Financing", "Governance", "Research & Learning", "Collaboration", "Menstrual Health Management", "Capacity Building"];
                                                foreach ($pillars as $p): ?>
                                                    <label
                                                        class="flex items-center gap-2 text-[11px] cursor-pointer hover:bg-white p-1 rounded transition-colors">
                                                        <input type="checkbox" name="enabling_pillars[]"
                                                            value="<?php echo $p; ?>"
                                                            class="rounded border-slate-300 text-brand-lime focus:ring-brand-lime">
                                                        <span class="text-slate-600"><?php echo $p; ?></span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>

                                        <div>
                                            <label
                                                class="block text-[10px] font-bold text-slate-500 uppercase mb-2">Challenges
                                                Sector</label>
                                            <div
                                                class="grid grid-cols-2 gap-2 max-h-32 overflow-y-auto p-2 bg-slate-50 rounded border">
                                                <?php
                                                $sectors = ["Access", "Funding", "Technology", "Governance", "Behavioral", "Environmental"];
                                                foreach ($sectors as $s): ?>
                                                    <label
                                                        class="flex items-center gap-2 text-[11px] cursor-pointer hover:bg-white p-1 rounded transition-colors">
                                                        <input type="checkbox" name="challenges_sector[]"
                                                            value="<?php echo $s; ?>"
                                                            class="rounded border-slate-300 text-brand-lime focus:ring-brand-lime">
                                                        <span class="text-slate-600"><?php echo $s; ?></span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="flex justify-center my-4">
                                        <div class="g-recaptcha"
                                            data-sitekey="<?php echo defined('RECAPTCHA_SITE_KEY') ? RECAPTCHA_SITE_KEY : ''; ?>">
                                        </div>
                                    </div>
                                    <button type="submit"
                                        class="w-full bg-brand-lime hover:bg-lime-700 text-brand-dark font-bold py-4 rounded-xl transition-all shadow-lg active:scale-95">
                                        Create Account & Continue
                                    </button>
                                </form>
                            </div>

                            <!-- Login Form -->
                            <div id="inlineLoginForm" class="hidden">
                                <div class="text-center mb-6">
                                    <h2 class="text-2xl font-bold text-slate-900">Welcome Back</h2>
                                    <p class="text-slate-500 text-sm mt-1">Sign in to continue to submission.</p>
                                </div>
                                <div id="inlineLoginError"
                                    class="hidden bg-red-50 border-l-4 border-red-500 text-red-700 p-3 mb-4 rounded text-sm">
                                </div>

                                <form id="inlineLoginFormElement" class="space-y-4" onsubmit="handleInlineLogin(event)">
                                    <div>
                                        <label class="block text-sm font-semibold text-slate-700 mb-1">Email</label>
                                        <input type="email" name="email" required
                                            class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-brand-blue outline-none transition-all"
                                            placeholder="your@email.com">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-slate-700 mb-1">Password</label>
                                        <input type="password" name="password" required
                                            class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-brand-blue focus:border-brand-blue outline-none transition-all"
                                            placeholder="••••••••">
                                    </div>
                                    <button type="submit"
                                        class="w-full bg-brand-blue hover:bg-blue-700 text-white font-bold py-3 rounded-lg transition-all shadow-md">
                                        Sign In
                                    </button>
                                </form>
                            </div>

                        </div>
                    </div>
                <?php else: ?>
                    <!-- Submission Form (Visible only to logged in users) -->
                    <div class="bg-white rounded-[2.5rem] shadow-2xl border border-slate-100 overflow-hidden min-h-[800px]">

                        <!-- Toggle Org/Individual -->
                        <div class="bg-slate-50 p-6 border-b border-slate-100 text-center">
                            <p class="text-slate-600 mb-4 font-bold uppercase tracking-wide text-sm">Select Submission Type
                            </p>
                            <div class="inline-flex bg-white p-1.5 rounded-full border border-slate-200 shadow-sm relative">
                                <div id="switch-bg"
                                    class="absolute top-1.5 left-1.5 bottom-1.5 w-[calc(50%-6px)] bg-brand-dark rounded-full transition-all duration-300 ease-out">
                                </div>
                                <button onclick="switchForm('org')" id="btn-org"
                                    class="relative z-10 px-6 py-2 rounded-full text-sm font-bold uppercase tracking-widest text-white transition-colors duration-300 w-40">Organization</button>
                                <button onclick="switchForm('ind')" id="btn-ind"
                                    class="relative z-10 px-6 py-2 rounded-full text-sm font-bold uppercase tracking-widest text-slate-500 hover:text-brand-dark transition-colors duration-300 w-40">Individual</button>
                            </div>
                        </div>

                        <div class="p-8 md:p-12">
                            <form id="submission-form" action="submit.php" method="POST" enctype="multipart/form-data"
                                class="grid md:grid-cols-2 gap-8">
                                <input type="hidden" name="submission_type" id="submission_type" value="organization">

                                <!-- Basic Info -->
                                <div class="md:col-span-2 space-y-6">
                                    <h3 class="text-xl font-bold text-slate-800 border-l-4 border-brand-lime pl-3">1. Basic
                                        Details</h3>
                                    <div class="grid md:grid-cols-2 gap-6">
                                        <div>
                                            <label class="block text-slate-700 text-sm font-bold uppercase mb-2">Title of
                                                Data/Project</label>
                                            <input type="text" name="title" required
                                                class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:bg-white focus:border-brand-blue outline-none transition-colors">
                                        </div>
                                        <div>
                                            <label class="block text-slate-700 text-sm font-bold uppercase mb-2">Location
                                                (County/Region)</label>
                                            <input type="text" name="location" required
                                                class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-lg focus:bg-white focus:border-brand-blue outline-none transition-colors">
                                        </div>
                                    </div>
                                </div>

                                <!-- Classifications -->
                                <div class="md:col-span-2 space-y-6">
                                    <h3 class="text-xl font-bold text-slate-800 border-l-4 border-brand-lime pl-3">2.
                                        Classification</h3>

                                    <!-- Service Chain -->
                                    <div>
                                        <label class="block text-slate-700 text-sm font-bold uppercase mb-3">Service
                                            Chain(s)</label>
                                        <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                                            <?php
                                            $chains = ['Capture & Containment', 'Emptying', 'Transport', 'Treatment', 'Safe Reuse'];
                                            foreach ($chains as $chain) {
                                                echo '<label class="flex items-center gap-3 p-3 bg-slate-50 rounded-lg cursor-pointer hover:bg-slate-100 border border-transparent hover:border-slate-200 transition-all">
                                                        <input type="checkbox" name="service_chains[]" value="' . $chain . '" class="rounded text-brand-blue focus:ring-brand-blue">
                                                        <span class="text-sm text-slate-700">' . $chain . '</span>
                                                      </label>';
                                            }
                                            ?>
                                        </div>
                                    </div>

                                    <!-- Enabling Pillars -->
                                    <div>
                                        <label class="block text-slate-700 text-sm font-bold uppercase mb-3">Enabling
                                            Pillar(s)</label>
                                        <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                                            <?php
                                            $pillars = ['Financing', 'Governance', 'Research & Learning', 'Collaboration', 'Menstrual Health Management', 'Capacity Building'];
                                            foreach ($pillars as $pillar) {
                                                echo '<label class="flex items-center gap-3 p-3 bg-slate-50 rounded-lg cursor-pointer hover:bg-slate-100 border border-transparent hover:border-slate-200 transition-all">
                                                        <input type="checkbox" name="enabling_pillars[]" value="' . $pillar . '" class="rounded text-brand-lime focus:ring-brand-lime">
                                                        <span class="text-sm text-slate-700">' . $pillar . '</span>
                                                      </label>';
                                            }
                                            ?>
                                        </div>
                                    </div>

                                    <!-- Barriers (Formerly Challenge Areas/Thematic Repositories) -->
                                    <div>
                                        <label
                                            class="block text-slate-700 text-sm font-bold uppercase mb-3">Barriers</label>
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                            <?php
                                            $challenges = [
                                                "Access" => "Limited Sanitation Access and Coverage Gaps",
                                                "Socio-Cultural" => "Socio-Cultural Barriers & Conceptual Myopia",
                                                "Tech" => "Systemic Bottlenecks in Tech Adoption",
                                                "Funding" => "Underfunding & Low Prioritization",
                                                "Data" => "Data Deficiencies"
                                            ];
                                            foreach ($challenges as $val => $label) {
                                                echo '<label class="flex items-start gap-3 p-3 bg-slate-50 rounded-lg cursor-pointer hover:bg-slate-100 border border-transparent hover:border-slate-200 transition-all">
                                                        <input type="checkbox" name="challenge_areas[]" value="' . $val . '" class="rounded text-brand-cyan focus:ring-brand-cyan mt-1">
                                                        <span class="text-sm text-slate-700 leading-tight"><strong>' . $val . '</strong><br><span class="text-xs text-slate-500">' . $label . '</span></span>
                                                      </label>';
                                            }
                                            ?>
                                        </div>
                                        <p class="text-xs text-slate-500 mt-2">* Use checkboxes to select applicable areas
                                            in the Barriers.</p>
                                    </div>
                                </div>

                                <!-- Data Content -->
                                <div class="md:col-span-2 space-y-6">
                                    <h3 class="text-xl font-bold text-slate-800 border-l-4 border-brand-lime pl-3">3. Your
                                        Data</h3>
                                    <div>
                                        <label
                                            class="block text-slate-700 text-sm font-bold uppercase mb-2">Narrative</label>
                                        <!-- Quill Editor Container -->
                                        <div id="quill-editor" class="bg-white" style="height: 300px;"></div>
                                        <input type="hidden" name="Data" id="Data-content">
                                    </div>

                                    <div>
                                        <label class="block text-slate-700 text-sm font-bold uppercase mb-2">Upload
                                            Images/PDFs (Optional)</label>
                                        <input type="file" name="attachments[]" multiple accept=".jpg,.jpeg,.png,.pdf"
                                            class="block w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-brand-blue hover:file:bg-blue-100">
                                        <p class="text-xs text-slate-500 mt-1">Max 5MB per file.</p>
                                    </div>
                                </div>

                                <div class="md:col-span-2 pt-6 border-t border-slate-100">
                                    <button type="submit"
                                        class="w-full py-4 bg-brand-dark text-white rounded-xl font-bold uppercase tracking-widest hover:bg-brand-blue transition-all shadow-lg text-lg">
                                        Submit Entry
                                    </button>
                                </div>

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

            </div>
        </section>

    </main>

    <?php include 'footer.php'; ?>

    <script>
        // County Multi-Select Logic
        const kenyaCounties = ["National", "Mombasa", "Kwale", "Kilifi", "Tana River", "Lamu", "Taita Taveta", "Garissa", "Wajir", "Mandera", "Marsabit", "Isiolo", "Meru", "Tharaka-Nithi", "Embu", "Kitui", "Machakos", "Makueni", "Nyandarua", "Nyeri", "Kirinyaga", "Murang'a", "Kiambu", "Turkana", "West Pokot", "Samburu", "Trans-Nzoia", "Uasin Gishu", "Elgeyo-Marakwet", "Nandi", "Baringo", "Laikipia", "Nakuru", "Narok", "Kajiado", "Kericho", "Bomet", "Kakamega", "Vihiga", "Bungoma", "Busia", "Siaya", "Kisumu", "Homa Bay", "Migori", "Kisii", "Nyamira", "Nairobi"];
        let selectedCounties = [];

        const countySearch = document.getElementById('county-search');
        const countyDropdown = document.getElementById('county-dropdown');
        const selectedContainer = document.getElementById('selected-counties-container');

        function updateCountiesUI() {
            selectedContainer.innerHTML = '';
            selectedCounties.forEach(county => {
                const pill = document.createElement('div');
                pill.className = 'flex items-center gap-1 bg-brand-lime/10 text-brand-lime border border-brand-lime/20 px-2 py-1 rounded-md text-xs font-bold';
                pill.innerHTML = `
                    <span>${county}</span>
                    <button type="button" onclick="removeCounty('${county}')" class="hover:text-red-500 transition-colors">
                        <i class="fa-solid fa-xmark"></i>
                    </button>
                    <input type="hidden" name="counties[]" value="${county}">
                `;
                selectedContainer.appendChild(pill);
            });
        }

        function removeCounty(county) {
            selectedCounties = selectedCounties.filter(c => c !== county);
            updateCountiesUI();
        }

        function addCounty(county) {
            if (!selectedCounties.includes(county)) {
                selectedCounties.push(county);
                updateCountiesUI();
            }
            countySearch.value = '';
            countyDropdown.classList.add('hidden');
        }

        countySearch.addEventListener('input', (e) => {
            const val = e.target.value.toLowerCase();
            if (!val) {
                countyDropdown.classList.add('hidden');
                return;
            }

            const filtered = kenyaCounties.filter(c =>
                c.toLowerCase().includes(val) && !selectedCounties.includes(c)
            );

            if (filtered.length > 0) {
                countyDropdown.innerHTML = filtered.map(c => `
                    <div onclick="addCounty('${c}')" class="px-4 py-2 hover:bg-slate-50 cursor-pointer text-sm font-medium border-b border-slate-50 last:border-0">
                        ${c}
                    </div>
                `).join('');
                countyDropdown.classList.remove('hidden');
            } else {
                countyDropdown.classList.add('hidden');
            }
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!document.getElementById('county-multi-select').contains(e.target)) {
                countyDropdown.classList.add('hidden');
            }
        });

        // Inline Auth Switcher
        function switchInlineAuth(tab) {
            const signupTab = document.getElementById('inlineSignupTab');
            const loginTab = document.getElementById('inlineLoginTab');
            const signupForm = document.getElementById('inlineSignupForm');
            const loginForm = document.getElementById('inlineLoginForm');

            if (tab === 'signup') {
                signupTab.classList.add('border-brand-lime', 'text-slate-900');
                signupTab.classList.remove('border-transparent', 'text-slate-400');
                loginTab.classList.remove('border-brand-lime', 'text-slate-900', 'border-blue-600'); // Clean up login style
                loginTab.classList.add('border-transparent', 'text-slate-400');

                signupForm.classList.remove('hidden');
                loginForm.classList.add('hidden');
            } else {
                loginTab.classList.add('border-blue-600', 'text-slate-900');
                loginTab.classList.remove('border-transparent', 'text-slate-400');
                signupTab.classList.remove('border-brand-lime', 'text-slate-900');
                signupTab.classList.add('border-transparent', 'text-slate-400');

                loginForm.classList.remove('hidden');
                signupForm.classList.add('hidden');
            }
        }

        function setSignupType(type) {
            document.getElementById('signup_user_type').value = type;
            const btnOrg = document.getElementById('type-org');
            const btnInd = document.getElementById('type-ind');
            const companySection = document.getElementById('company-section');

            if (type === 'organization') {
                btnOrg.className = "px-4 py-2 rounded-md text-sm font-bold transition-all bg-brand-dark text-white shadow-sm";
                btnInd.className = "px-4 py-2 rounded-md text-sm font-bold transition-all text-slate-500 hover:text-brand-dark";
                companySection.classList.remove('hidden');
                document.getElementById('signup_org_name').required = true;
            } else {
                btnInd.className = "px-4 py-2 rounded-md text-sm font-bold transition-all bg-brand-dark text-white shadow-sm";
                btnOrg.className = "px-4 py-2 rounded-md text-sm font-bold transition-all text-slate-500 hover:text-brand-dark";
                companySection.classList.add('hidden');
                document.getElementById('signup_org_name').required = false;
            }
        }

        // Handle Signup
        async function handleInlineSignup(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);
            const errorDiv = document.getElementById('inlineSignupError');
            const successDiv = document.getElementById('inlineSignupSuccess');
            const btn = form.querySelector('button[type="submit"]');

            // Client-side validation
            if (formData.get('password') !== formData.get('confirm_password')) {
                errorDiv.textContent = 'Passwords do not match.';
                errorDiv.classList.remove('hidden');
                return;
            }

            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i> Creating account...';

            try {
                const response = await fetch('signup.php', { method: 'POST', body: formData });
                const result = await response.text();

                if (result.includes('success') || result.includes('Account created')) {
                    successDiv.textContent = 'Account created! Logging you in...';
                    successDiv.classList.remove('hidden');
                    errorDiv.classList.add('hidden');
                    setTimeout(() => window.location.reload(), 1500);
                } else {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(result, 'text/html');
                    const errorMsg = doc.querySelector('.bg-red-50')?.textContent?.trim() || 'Signup failed. Please try again.';
                    errorDiv.textContent = errorMsg;
                    errorDiv.classList.remove('hidden');
                    btn.disabled = false;
                    btn.innerText = 'Create Account & Continue';
                }
            } catch (err) {
                errorDiv.textContent = 'Connection error.';
                errorDiv.classList.remove('hidden');
                btn.disabled = false;
                btn.innerText = 'Create Account & Continue';
            }
        }

        // Handle Login
        async function handleInlineLogin(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);
            const errorDiv = document.getElementById('inlineLoginError');

            try {
                const response = await fetch('login.php', { method: 'POST', body: formData });
                const result = await response.text();
                if (result.includes('window.location') || response.redirected || result.trim() === '') {
                    window.location.reload();
                } else {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(result, 'text/html');
                    const errorMsg = doc.querySelector('.bg-red-50')?.textContent?.trim() || 'Invalid credentials.';
                    errorDiv.textContent = errorMsg;
                    errorDiv.classList.remove('hidden');
                }
            } catch (err) {
                errorDiv.textContent = 'Connection error.';
                errorDiv.classList.remove('hidden');
            }
        }

        // Form Type Switcher (Org vs Ind)
        function switchForm(type) {
            const btnOrg = document.getElementById('btn-org');
            const btnInd = document.getElementById('btn-ind');
            const bg = document.getElementById('switch-bg');
            const input = document.getElementById('submission_type');

            if (type === 'org') {
                bg.style.left = '6px';
                btnOrg.classList.remove('text-slate-500');
                btnOrg.classList.add('text-white');
                btnInd.classList.add('text-slate-500');
                btnInd.classList.remove('text-white');
                input.value = 'organization';
            } else {
                bg.style.left = 'calc(50% + 6px)';
                btnInd.classList.remove('text-slate-500');
                btnInd.classList.add('text-white');
                btnOrg.classList.add('text-slate-500');
                btnOrg.classList.remove('text-white');
                input.value = 'individual';
            }
        }

        // Initialize Quill
        <?php if ($is_logged_in): ?>         var quill = new Quill('#quill-editor', { theme: 'snow', placeholder: 'Tell us about your project or expertise...', modules: { toolbar: [[{ 'header': [2, 3, false] }], ['bold', 'italic', 'underline'], ['link', 'blockquote'], [{ 'list': 'ordered' }, { 'list': 'bullet' }]] } });
            document.getElementById('submission-form').onsubmit = function () { document.getElementById('Data-content').value = quill.root.innerHTML; };
        <?php endif; ?>

        const navbar = document.getElementById('navbar');
        if (navbar) {
            window.addEventListener('scroll', () => { navbar.classList.toggle('nav-scrolled', window.scrollY > 20); });
        }

        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));
    </script>
</body>

</html>