import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import SiteLayout from "@/components/SiteLayout";
import AnimateIn from "@/components/AnimateIn";
import FeedbackWidget from "@/components/kb/FeedbackWidget";
import {
  BookOpen,
  Rocket,
  Server,
  Globe,
  Mail,
  ShieldCheck,
  LayoutDashboard,
  MessageSquare,
  Wrench,
  Search,
  ArrowRight,
  ChevronRight,
  Bot,
  Activity,
  Network,
  Lightbulb,
  FileText,
  Users,
  KeyRound,
  Bell,
  Terminal as TerminalIcon,
  CheckCircle2,
  AlertTriangle,
  ExternalLink,
  Sparkles,
  ArrowUpRight,
  type LucideIcon,
} from "lucide-react";

/**
 * DoItEasy Knowledge Base
 * -----------------------
 *
 * A searchable, categorized knowledge base landing page that exposes the
 * documentation structure described in the content plan:
 *   1. Getting Started
 *   2. Web Hosting & VPS
 *   3. Domain & DNS
 *   4. Email & Bizmail360
 *   5. Security & Compliance
 *   6. Clients Portal
 *   7. WhatsApp API Services
 *   8. Troubleshooting
 *
 * Plus the advanced sections we committed to in the strategic section:
 *   - API Status & Diagnostics Panel
 *   - AI Assistant Usage Guide
 *   - WhatsApp Automation Workflows
 *   - Virtualizor Network Modes (Bridged vs Routed)
 *
 * Each category opens a detail panel on the same page with a full list of
 * articles. Articles link to the relevant product surface (Clients Portal,
 * Domain Search, Tickets, etc.) or expand inline, so the KB is useful
 * even without dedicated per-article routes.
 */

// ---------------------------------------------------------------------------
// Types & data
// ---------------------------------------------------------------------------

interface KbArticle {
  /** Short URL-safe id used for deep linking and "View article" selection. */
  id: string;
  title: string;
  /** One-line summary shown in the article list. */
  summary: string;
  /** Estimated read time, purely decorative. */
  readMinutes: number;
  /** Optional tag displayed as a pill (e.g. "Popular", "New"). */
  tag?: "Popular" | "New" | "Updated";
  /** Optional CTA link for the user (defaults to "Open article"). */
  cta?: { label: string; to: string; external?: boolean };
  /**
   * Rich body rendered as sequential blocks when the article is opened.
   * Using a structured block model (instead of raw HTML) keeps the KB
   * accessible and Tailwind-styleable without dangerouslySetInnerHTML.
   */
  body: KbBlock[];
}

type KbBlock =
  | { kind: "paragraph"; text: string }
  | { kind: "heading"; text: string }
  | { kind: "list"; items: string[] }
  | { kind: "ordered"; items: string[] }
  | { kind: "code"; language?: string; code: string }
  | { kind: "callout"; variant: "info" | "warning" | "success"; title: string; text: string };

interface KbCategory {
  id: string;
  title: string;
  description: string;
  icon: LucideIcon;
  /** Tailwind gradient class for the icon tile. */
  gradient: string;
  articles: KbArticle[];
}

const CATEGORIES: KbCategory[] = [
  // 1. Getting Started ------------------------------------------------------
  {
    id: "getting-started",
    title: "Getting Started",
    description:
      "Your first steps on DoItEasy: create an account, explore the Clients Portal, order services and pay.",
    icon: Rocket,
    gradient: "from-emerald-500 to-teal-500",
    articles: [
      {
        id: "creating-an-account",
        title: "Creating a DoItEasy Account",
        summary:
          "Sign up, verify your email, and log in to access hosting, VPS, email and more.",
        readMinutes: 3,
        tag: "Popular",
        cta: { label: "Create account", to: "/register" },
        body: [
          {
            kind: "paragraph",
            text: "A DoItEasy account gives you unified access to hosting, VPS, domains, Bizmail360, WhatsApp API and support — all from a single Clients Portal.",
          },
          { kind: "heading", text: "Sign up in under a minute" },
          {
            kind: "ordered",
            items: [
              "Open the Register page and enter your email address and a strong password.",
              "Confirm the verification email we send to finish activating your account.",
              "Complete your profile with billing details so invoices are generated correctly.",
              "Enable two-factor authentication (2FA) from Account Settings for extra security.",
            ],
          },
          {
            kind: "callout",
            variant: "info",
            title: "Already have an account?",
            text: "If you migrated from a previous provider, our team can import your services and domains for free — just open a ticket.",
          },
        ],
      },
      {
        id: "clients-portal-overview",
        title: "Clients Portal Overview",
        summary:
          "Your centralized dashboard to manage all services, billing and support operations.",
        readMinutes: 4,
        tag: "Popular",
        cta: { label: "Open Clients Portal", to: "/client" },
        body: [
          {
            kind: "paragraph",
            text: "The DoItEasy Clients Portal is your centralized dashboard to manage all services, billing, and support operations.",
          },
          { kind: "heading", text: "Key features" },
          {
            kind: "list",
            items: [
              "Service management — VPS, Hosting, Domains",
              "Billing & invoices with full history",
              "Integrated ticketing system",
              "API access & integration",
              "Real-time notifications and alerts",
            ],
          },
          { kind: "heading", text: "Access the portal" },
          {
            kind: "paragraph",
            text: "Sign in at https://client.doiteasy.net or open the built-in Client Area from the top navigation.",
          },
          { kind: "heading", text: "Dashboard functions" },
          {
            kind: "list",
            items: [
              "View all active services at a glance",
              "Monitor usage and service status",
              "Quick actions: restart, renew, upgrade",
            ],
          },
        ],
      },
      {
        id: "ordering-services",
        title: "Ordering Services",
        summary:
          "Browse the catalog, configure your plan and pay — your service is provisioned in minutes.",
        readMinutes: 3,
        cta: { label: "Browse hosting plans", to: "/hosting" },
        body: [
          { kind: "heading", text: "The order flow" },
          {
            kind: "ordered",
            items: [
              "Pick a product category: Shared Hosting, Cloud VPS, Dedicated, Email or WhatsApp API.",
              "Configure plan options (region, billing cycle, add-ons).",
              "Review your cart and apply a promo code if you have one.",
              "Pay with credit card, PayPal or local payment methods — provisioning is automatic.",
            ],
          },
          {
            kind: "callout",
            variant: "success",
            title: "Instant delivery",
            text: "Most services (shared hosting, VPS, email) are provisioned within minutes of successful payment.",
          },
        ],
      },
      {
        id: "payment-methods-billing",
        title: "Payment Methods & Billing",
        summary:
          "Supported payment options, invoice downloads, and automatic renewals explained.",
        readMinutes: 3,
        body: [
          { kind: "heading", text: "Supported payment methods" },
          {
            kind: "list",
            items: [
              "Credit & debit cards (Visa, Mastercard, Amex)",
              "PayPal and wallet providers",
              "Bank transfer (wire) for annual contracts",
              "Local payment methods in supported regions",
            ],
          },
          { kind: "heading", text: "Invoices & receipts" },
          {
            kind: "paragraph",
            text: "Every invoice is stored in your Clients Portal under Billing → Invoices. You can download a PDF copy at any time or configure automated email delivery to your finance team.",
          },
          { kind: "heading", text: "Auto-renew" },
          {
            kind: "paragraph",
            text: "Services auto-renew by default to prevent downtime. You can toggle auto-renew per service from the service details page.",
          },
        ],
      },
    ],
  },

  // 2. Web Hosting & VPS ----------------------------------------------------
  {
    id: "hosting-vps",
    title: "Web Hosting & VPS",
    description:
      "Everything about shared hosting, VPS access, Virtualizor management and backups.",
    icon: Server,
    gradient: "from-blue-500 to-indigo-500",
    articles: [
      {
        id: "what-is-vps",
        title: "What is VPS Hosting?",
        summary:
          "A VPS gives you dedicated resources on a virtualized server — power without the price of dedicated.",
        readMinutes: 4,
        body: [
          {
            kind: "paragraph",
            text: "A Virtual Private Server (VPS) is an isolated virtual machine that runs on top of shared hardware but with dedicated CPU, RAM and disk guaranteed to your account.",
          },
          { kind: "heading", text: "When should you choose a VPS?" },
          {
            kind: "list",
            items: [
              "You outgrew shared hosting and need full root / admin access",
              "You run custom applications, services or APIs that shared hosting cannot host",
              "You need predictable performance with reserved resources",
              "You want to scale up or down on demand without migrating servers",
            ],
          },
          {
            kind: "callout",
            variant: "info",
            title: "Not sure which plan?",
            text: "Our team can size your VPS based on real traffic, concurrency and storage needs — open a pre-sales ticket and we'll recommend a plan.",
          },
        ],
      },
      {
        id: "ssh-rdp-access",
        title: "How to Access Your VPS (SSH / RDP)",
        summary:
          "Connect to Linux VPS using SSH or Windows VPS using RDP — with security best practices.",
        readMinutes: 5,
        tag: "Popular",
        body: [
          { kind: "heading", text: "SSH access (Linux VPS)" },
          {
            kind: "paragraph",
            text: "Use any modern SSH client (OpenSSH, PuTTY, Termius) with the root credentials we provision for you.",
          },
          {
            kind: "code",
            language: "bash",
            code: "ssh root@YOUR_VPS_IP -p 22\n# first login will prompt for the password from your welcome email",
          },
          { kind: "heading", text: "RDP access (Windows VPS)" },
          {
            kind: "paragraph",
            text: "On Windows use Remote Desktop Connection; on macOS install Microsoft Remote Desktop from the App Store. Connect to the VPS IP on port 3389.",
          },
          {
            kind: "callout",
            variant: "warning",
            title: "Harden your VPS immediately",
            text: "Change default passwords, disable root password login in favor of SSH keys, and enable a firewall (ufw / Windows Defender Firewall).",
          },
        ],
      },
      {
        id: "virtualizor",
        title: "Managing VPS via Virtualizor",
        summary:
          "Start, stop, reboot, reinstall OS and monitor your VPS from the Virtualizor control panel.",
        readMinutes: 4,
        body: [
          {
            kind: "paragraph",
            text: "All DoItEasy VPS plans ship with Virtualizor end-user access for full lifecycle control of your virtual machine.",
          },
          { kind: "heading", text: "What you can do from Virtualizor" },
          {
            kind: "list",
            items: [
              "Start, stop, reboot or force-stop the VPS",
              "Reinstall the operating system from 20+ templates",
              "Mount recovery ISO or rescue mode",
              "View VNC/HTML5 console when SSH/RDP is unreachable",
              "Monitor live CPU, RAM, disk and bandwidth graphs",
            ],
          },
        ],
      },
      {
        id: "backup-restore",
        title: "Backup & Restore",
        summary:
          "Automated daily / weekly backups and one-click restore for hosting and VPS plans.",
        readMinutes: 4,
        body: [
          { kind: "heading", text: "Automated backups" },
          {
            kind: "paragraph",
            text: "Most hosting plans include daily backups kept for 7 days, and VPS plans offer weekly full snapshots with daily incremental backups.",
          },
          { kind: "heading", text: "Restoring a backup" },
          {
            kind: "ordered",
            items: [
              "Log in to the Clients Portal and open the service details page.",
              "Go to the Backups tab and select the restore point.",
              "Click Restore — the system will revert your data to that point in time.",
              "We always email you a confirmation once the restore is complete.",
            ],
          },
          {
            kind: "callout",
            variant: "info",
            title: "Pro tip",
            text: "Before a major upgrade (CMS version, PHP version), take a manual snapshot so you can roll back instantly if anything breaks.",
          },
        ],
      },
    ],
  },

  // 3. Domain & DNS ---------------------------------------------------------
  {
    id: "domain-dns",
    title: "Domain & DNS",
    description:
      "Register, transfer and manage domains. Configure DNS records and nameservers with confidence.",
    icon: Globe,
    gradient: "from-sky-500 to-cyan-500",
    articles: [
      {
        id: "dns-records",
        title: "Managing DNS Records",
        summary:
          "A, AAAA, CNAME, MX, TXT — what each record does and how to configure them in the portal.",
        readMinutes: 5,
        cta: { label: "Open Domain Manager", to: "/domain-search" },
        body: [
          { kind: "heading", text: "The DNS record types you'll actually use" },
          {
            kind: "list",
            items: [
              "A — maps a hostname to an IPv4 address (e.g. www → 1.2.3.4)",
              "AAAA — maps a hostname to an IPv6 address",
              "CNAME — aliases one hostname to another",
              "MX — routes mail for your domain (used by Bizmail360 setup)",
              "TXT — arbitrary text, commonly used for SPF / DKIM / domain verification",
            ],
          },
          { kind: "heading", text: "Editing records" },
          {
            kind: "paragraph",
            text: "From the Domain manager, open your domain, go to DNS Management, and add or edit records inline. Most changes propagate within 5–15 minutes.",
          },
        ],
      },
      {
        id: "changing-nameservers",
        title: "Changing Nameservers",
        summary:
          "Point your domain to DoItEasy nameservers — or to an external DNS provider like Cloudflare.",
        readMinutes: 3,
        body: [
          { kind: "heading", text: "DoItEasy default nameservers" },
          {
            kind: "code",
            language: "text",
            code: "ns1.doiteasy.net\nns2.doiteasy.net",
          },
          { kind: "heading", text: "Steps" },
          {
            kind: "ordered",
            items: [
              "Open the Clients Portal and go to Domains.",
              "Select your domain and click Nameservers.",
              "Enter the new NS values (ours or a third-party's).",
              "Save — full propagation can take up to 24–48 hours.",
            ],
          },
        ],
      },
      {
        id: "domain-propagation",
        title: "Domain Propagation",
        summary:
          "Why DNS changes aren't instant and how to check propagation status.",
        readMinutes: 3,
        body: [
          {
            kind: "paragraph",
            text: "DNS changes must replicate across the global network of resolvers. This is called propagation and typically completes within 5 minutes to 24 hours depending on the record type and TTL.",
          },
          {
            kind: "list",
            items: [
              "A / AAAA / CNAME — usually 5–15 minutes on short TTLs",
              "Nameserver changes — up to 24–48 hours worst case",
              "MX — up to 1 hour for email routing to fully stabilize",
            ],
          },
          {
            kind: "callout",
            variant: "info",
            title: "Check propagation yourself",
            text: "Use tools like dnschecker.org to see how your record is resolving around the world in real time.",
          },
        ],
      },
    ],
  },

  // 4. Email & Bizmail360 ---------------------------------------------------
  {
    id: "email-bizmail360",
    title: "Email & Bizmail360",
    description:
      "Create professional mailboxes, configure SMTP/IMAP clients, and troubleshoot delivery issues.",
    icon: Mail,
    gradient: "from-fuchsia-500 to-pink-500",
    articles: [
      {
        id: "setup-email-accounts",
        title: "Setting up Email Accounts",
        summary:
          "Create your first mailbox on your own domain with Bizmail360 in under 5 minutes.",
        readMinutes: 4,
        cta: { label: "Go to Bizmail360", to: "/bizmail360" },
        body: [
          { kind: "heading", text: "Pre-requisites" },
          {
            kind: "list",
            items: [
              "An active Bizmail360 or Business Email plan",
              "A domain you control (A, MX, SPF & DKIM permissions)",
            ],
          },
          { kind: "heading", text: "Steps" },
          {
            kind: "ordered",
            items: [
              "Open the Clients Portal and select your Email plan.",
              "Go to Mailboxes → Add Mailbox.",
              "Pick a username, set a strong password, and choose the storage quota.",
              "Point your domain's MX records to our mail servers as shown in the setup wizard.",
            ],
          },
        ],
      },
      {
        id: "smtp-imap",
        title: "SMTP / IMAP Configuration",
        summary:
          "Exact settings for Outlook, Apple Mail, Thunderbird and mobile clients.",
        readMinutes: 4,
        body: [
          { kind: "heading", text: "Incoming (IMAP)" },
          {
            kind: "code",
            language: "text",
            code: "Server:   imap.doiteasy.net\nPort:     993\nSecurity: SSL/TLS\nUsername: your-full-email@yourdomain.com",
          },
          { kind: "heading", text: "Outgoing (SMTP)" },
          {
            kind: "code",
            language: "text",
            code: "Server:   smtp.doiteasy.net\nPort:     465 (SSL) or 587 (STARTTLS)\nUsername: your-full-email@yourdomain.com\nAuth:     required",
          },
          {
            kind: "callout",
            variant: "warning",
            title: "Always use SSL/TLS",
            text: "Never configure email clients over plain text ports (25/143/110) — use the secure ports listed above.",
          },
        ],
      },
      {
        id: "email-delivery-issues",
        title: "Troubleshooting Email Delivery",
        summary:
          "Diagnose spam flags, bounces, and stuck mail with a simple SPF/DKIM/MX checklist.",
        readMinutes: 5,
        body: [
          { kind: "heading", text: "If your email is landing in spam" },
          {
            kind: "list",
            items: [
              "Make sure SPF, DKIM and DMARC are published for your domain",
              "Check that your sending IP / domain isn't on a major RBL",
              "Avoid spam-trigger words and large image-only campaigns",
            ],
          },
          { kind: "heading", text: "If your email is bouncing" },
          {
            kind: "list",
            items: [
              "Read the bounce message — it almost always points to the cause",
              "Verify the recipient address exists and isn't full",
              "Check your MX records are pointing to Bizmail360 correctly",
            ],
          },
        ],
      },
    ],
  },

  // 5. Security & Compliance ------------------------------------------------
  {
    id: "security",
    title: "Security & Compliance",
    description:
      "Harden your mail, server and network with SPF, DKIM, PTR, blacklist handling and best practices.",
    icon: ShieldCheck,
    gradient: "from-rose-500 to-red-500",
    articles: [
      {
        id: "spf-dkim-ptr",
        title: "SPF / DKIM / PTR Setup",
        summary:
          "The three DNS records that every domain sending email must publish.",
        readMinutes: 5,
        tag: "Popular",
        body: [
          { kind: "heading", text: "SPF (Sender Policy Framework)" },
          {
            kind: "paragraph",
            text: "Publish a TXT record that lists which servers are allowed to send mail for your domain.",
          },
          {
            kind: "code",
            language: "text",
            code: "v=spf1 include:_spf.doiteasy.net -all",
          },
          { kind: "heading", text: "DKIM (DomainKeys Identified Mail)" },
          {
            kind: "paragraph",
            text: "Bizmail360 generates a DKIM key for your domain automatically. Add the provided TXT record to your DNS and enable signing from the Email settings.",
          },
          { kind: "heading", text: "PTR (Reverse DNS)" },
          {
            kind: "paragraph",
            text: "For VPS and dedicated customers, set a PTR record so your sending IP resolves back to your domain. This drastically improves email deliverability.",
          },
        ],
      },
      {
        id: "blacklist",
        title: "Handling Blacklisting Issues",
        summary:
          "Detect, delist and prevent future blacklisting with a simple action plan.",
        readMinutes: 4,
        body: [
          { kind: "heading", text: "Check if you're listed" },
          {
            kind: "paragraph",
            text: "Use mxtoolbox.com/blacklists or similar tools. If listed, each RBL has its own delisting form — follow it carefully.",
          },
          { kind: "heading", text: "Fix the root cause" },
          {
            kind: "list",
            items: [
              "Secure compromised mailboxes and reset passwords",
              "Disable open relays or weak SMTP auth",
              "Review outbound email volume for spikes",
              "Harden SPF, DKIM and DMARC records",
            ],
          },
        ],
      },
      {
        id: "server-security",
        title: "Server Security Best Practices",
        summary:
          "Firewall rules, unattended upgrades, intrusion detection, and backup strategy.",
        readMinutes: 5,
        body: [
          {
            kind: "list",
            items: [
              "Enable a host firewall (ufw, firewalld or Windows Defender) and restrict to required ports",
              "Install automatic security updates (unattended-upgrades / Windows Update)",
              "Use SSH key authentication and disable root password login",
              "Enable fail2ban or CSF to block brute-force attempts",
              "Keep full off-site backups in at least one additional region",
            ],
          },
        ],
      },
    ],
  },

  // 6. Clients Portal -------------------------------------------------------
  {
    id: "clients-portal",
    title: "Clients Portal",
    description:
      "Manage services, tickets, users, API access and notifications — all from the portal.",
    icon: LayoutDashboard,
    gradient: "from-emerald-600 to-green-500",
    articles: [
      {
        id: "managing-services",
        title: "Managing Services in Clients Portal",
        summary:
          "Start, stop, upgrade and manage your VPS, hosting, email and domains directly from the portal.",
        readMinutes: 4,
        tag: "Popular",
        cta: { label: "Open my services", to: "/client" },
        body: [
          {
            kind: "paragraph",
            text: "You can manage all your active services directly from the Clients Portal.",
          },
          { kind: "heading", text: "Available actions" },
          {
            kind: "list",
            items: [
              "Start / Stop / Reboot VPS",
              "Upgrade / Downgrade plans",
              "View service details and configuration",
              "Access credentials and one-time tokens",
              "Manage add-ons (backups, extra IPs, storage)",
            ],
          },
          { kind: "heading", text: "Steps" },
          {
            kind: "ordered",
            items: [
              "Login to the Clients Portal",
              "Navigate to Services",
              "Select the service you want to manage",
              "Click Manage to open the service control screen",
            ],
          },
          {
            kind: "callout",
            variant: "warning",
            title: "Reboot carefully",
            text: "Some actions may require confirmation. Ensure no active background processes (backups, database imports) are running before rebooting.",
          },
        ],
      },
      {
        id: "opening-tickets",
        title: "Opening a Support Ticket",
        summary:
          "Reach the right team fast with a well-structured support ticket.",
        readMinutes: 3,
        cta: { label: "Open a ticket", to: "/tickets" },
        body: [
          {
            kind: "paragraph",
            text: "The Clients Portal includes a built-in ticketing system for technical and billing support.",
          },
          { kind: "heading", text: "Steps to open a ticket" },
          {
            kind: "ordered",
            items: [
              "Login to the Clients Portal",
              "Go to Support → Open Ticket",
              "Select the department (Technical, Billing, Sales)",
              "Provide a detailed issue description",
              "Attach logs or screenshots if needed",
            ],
          },
          {
            kind: "callout",
            variant: "success",
            title: "Best practice",
            text: "Include server IP, exact error message, and time of issue. This reduces resolution time significantly.",
          },
        ],
      },
      {
        id: "api-integration",
        title: "Clients Portal API Integration Guide",
        summary:
          "Programmatic access to your services and billing using secure API tokens.",
        readMinutes: 6,
        tag: "Updated",
        body: [
          {
            kind: "paragraph",
            text: "The Clients Portal provides API access for automation and system integration.",
          },
          { kind: "heading", text: "Authentication" },
          {
            kind: "list",
            items: [
              "API Identifier",
              "API Secret Key",
              "Endpoint URL (https://client.doiteasy.net/api/)",
            ],
          },
          { kind: "heading", text: "Example request" },
          {
            kind: "code",
            language: "php",
            code: "$endpoint = \"https://client.doiteasy.net/api/\";\n$action   = \"GetClients\";\n\n$postData = [\n    'limitstart' => 0,\n    'limitnum'   => 25,\n];",
          },
          { kind: "heading", text: "Requirements" },
          {
            kind: "list",
            items: [
              "IP whitelisting enabled for your API user",
              "Valid API credentials",
              "HTTPS requests only",
            ],
          },
          {
            kind: "callout",
            variant: "warning",
            title: "Troubleshooting",
            text: "Check firewall (Imunify360 / WAF), validate API permissions, and monitor API response logs.",
          },
        ],
      },
      {
        id: "portal-access-issues",
        title: "Troubleshooting Clients Portal Access Issues",
        summary:
          "Service Unavailable, login failures and API timeouts — resolved step by step.",
        readMinutes: 4,
        body: [
          { kind: "heading", text: "Common errors" },
          {
            kind: "list",
            items: [
              "“Service Temporarily Unavailable”",
              "Login failures",
              "API connection timeouts",
            ],
          },
          { kind: "heading", text: "Root causes" },
          {
            kind: "list",
            items: [
              "Backend service not responding",
              "Firewall blocking requests",
              "Invalid API credentials",
              "High server load",
            ],
          },
          { kind: "heading", text: "Resolution steps" },
          {
            kind: "ordered",
            items: [
              "Verify portal URL accessibility",
              "Check server firewall rules",
              "Whitelist your IP",
              "Validate API credentials",
              "Review server logs for correlated errors",
            ],
          },
        ],
      },
      {
        id: "portal-notifications",
        title: "Clients Portal Notifications & Alerts",
        summary:
          "Real-time alerts for activations, invoices, security events and maintenance windows.",
        readMinutes: 3,
        body: [
          {
            kind: "paragraph",
            text: "The Clients Portal provides real-time alerts for important events.",
          },
          { kind: "heading", text: "Notifications include" },
          {
            kind: "list",
            items: [
              "Service activation",
              "Invoice reminders",
              "Security alerts",
              "System maintenance windows",
            ],
          },
          { kind: "heading", text: "Customization" },
          {
            kind: "list",
            items: [
              "Email notifications",
              "SMS alerts",
              "WhatsApp notifications (if enabled)",
            ],
          },
        ],
      },
    ],
  },

  // 7. WhatsApp API ---------------------------------------------------------
  {
    id: "whatsapp-api",
    title: "WhatsApp API Services",
    description:
      "Connect your WhatsApp device, activate sessions with QR codes and manage multi-number setups.",
    icon: MessageSquare,
    gradient: "from-green-500 to-emerald-500",
    articles: [
      {
        id: "connect-whatsapp",
        title: "Connecting a WhatsApp Device",
        summary:
          "Link a number to the WhatsApp API gateway in 3 steps.",
        readMinutes: 3,
        cta: { label: "Open WhatsApp API", to: "/whatsapp-api" },
        body: [
          {
            kind: "ordered",
            items: [
              "Open the WhatsApp API page in the Clients Portal.",
              "Click New Session and pick the phone number you want to link.",
              "Scan the generated QR code from the WhatsApp app on your phone.",
            ],
          },
        ],
      },
      {
        id: "qr-activation",
        title: "QR Code Activation",
        summary:
          "If the QR code expires or doesn't scan, here's how to regenerate it.",
        readMinutes: 2,
        body: [
          {
            kind: "list",
            items: [
              "QR codes expire after 60 seconds — click Refresh to generate a new one",
              "Make sure your phone has a stable internet connection while scanning",
              "Use the latest version of WhatsApp to avoid compatibility issues",
            ],
          },
        ],
      },
      {
        id: "manage-sessions",
        title: "Managing Sessions",
        summary:
          "Start, stop, restart and monitor your WhatsApp API sessions.",
        readMinutes: 3,
        body: [
          {
            kind: "list",
            items: [
              "View all active sessions and their connection status",
              "Restart a session if messages are not being delivered",
              "Disconnect a number safely before linking it to a new session",
              "Enable webhooks to receive inbound messages in your application",
            ],
          },
        ],
      },
      {
        id: "whatsapp-automation",
        title: "WhatsApp Automation Workflows",
        summary:
          "Trigger messages from your CRM, website or backend for notifications and marketing.",
        readMinutes: 5,
        tag: "New",
        body: [
          {
            kind: "paragraph",
            text: "Pair the WhatsApp API with automation tools (n8n, Make, Zapier, custom backends) to deliver transactional alerts and reminders at scale.",
          },
          { kind: "heading", text: "Common workflows" },
          {
            kind: "list",
            items: [
              "Order confirmation and shipping updates",
              "OTP and account verification messages",
              "Abandoned cart reminders",
              "Appointment reminders and re-bookings",
              "Customer support escalation to a human agent",
            ],
          },
        ],
      },
    ],
  },

  // 8. Troubleshooting ------------------------------------------------------
  {
    id: "troubleshooting",
    title: "Troubleshooting",
    description:
      "Common errors, downtime diagnostics and performance optimization tips.",
    icon: Wrench,
    gradient: "from-orange-500 to-amber-500",
    articles: [
      {
        id: "common-errors",
        title: "Common Errors",
        summary:
          "500s, 502s, SSL handshake errors, database connection refused — and how to fix them.",
        readMinutes: 5,
        body: [
          {
            kind: "list",
            items: [
              "HTTP 500 — check application logs and PHP error logs",
              "HTTP 502 / 504 — usually a backend (PHP-FPM / Node) restart is enough",
              "SSL handshake failed — verify certificate chain and hostname match",
              "Database connection refused — check credentials, socket path, and MySQL/MariaDB status",
            ],
          },
        ],
      },
      {
        id: "downtime",
        title: "Service Downtime Issues",
        summary:
          "Use Uptime Monitor and status pages to detect and triage downtime quickly.",
        readMinutes: 4,
        cta: { label: "Open Uptime Monitor", to: "/uptime-monitor" },
        body: [
          {
            kind: "ordered",
            items: [
              "Check the DoItEasy status page for known incidents.",
              "Use the Uptime Monitor to confirm the issue is not local to your network.",
              "Review your server logs for resource exhaustion (CPU, RAM, disk).",
              "Open a priority ticket with timestamps and error messages so we can triage faster.",
            ],
          },
        ],
      },
      {
        id: "performance",
        title: "Performance Optimization",
        summary:
          "Caching, CDN, database indexing and PHP tuning — quick wins for slow sites.",
        readMinutes: 5,
        body: [
          {
            kind: "list",
            items: [
              "Enable caching (Redis, Memcached, opcode cache) for dynamic sites",
              "Use a CDN like Cloudflare for static assets and DDoS protection",
              "Add missing indexes on slow database queries",
              "Upgrade PHP to the latest LTS version for a noticeable speed boost",
              "Move from shared hosting to a VPS when you consistently exceed your plan limits",
            ],
          },
        ],
      },
    ],
  },

  // Strategic / advanced sections ------------------------------------------
  {
    id: "api-diagnostics",
    title: "API Status & Diagnostics Panel",
    description:
      "Understand the diagnostic panel in Admin → WHMCS Logs and how to read its signals.",
    icon: Activity,
    gradient: "from-indigo-500 to-violet-500",
    articles: [
      {
        id: "diagnostics-overview",
        title: "Diagnostics Panel Overview",
        summary:
          "Check WHMCS connectivity, API latency and recent error logs in one place.",
        readMinutes: 4,
        tag: "Updated",
        body: [
          { kind: "heading", text: "What the panel shows" },
          {
            kind: "list",
            items: [
              "Backend API reachability and response time",
              "WHMCS health check status (database, cron, recent errors)",
              "Recent admin-side warnings and stack traces",
              "Whitelisted IPs and API user roles",
            ],
          },
          {
            kind: "callout",
            variant: "info",
            title: "Where to find it",
            text: "Login to Admin → CMS → Diagnostics (WHMCS Logs) to open the live panel.",
          },
        ],
      },
    ],
  },

  {
    id: "ai-assistant",
    title: "AI Assistant Usage Guide",
    description:
      "Use DoItEasy's AI Assistant to summarize tickets, draft replies and answer client questions.",
    icon: Bot,
    gradient: "from-violet-500 to-fuchsia-500",
    articles: [
      {
        id: "ai-assistant-intro",
        title: "Introducing the AI Assistant",
        summary:
          "Learn what the AI Assistant can and cannot do — and how to prompt it effectively.",
        readMinutes: 4,
        tag: "New",
        body: [
          {
            kind: "paragraph",
            text: "The AI Assistant runs on top of your Clients Portal data (tickets, services, knowledge base) and helps agents and customers find answers faster.",
          },
          { kind: "heading", text: "What it's great at" },
          {
            kind: "list",
            items: [
              "Summarizing long ticket threads",
              "Drafting first-response replies",
              "Answering frequently asked questions",
              "Linking to the most relevant KB article",
            ],
          },
          {
            kind: "callout",
            variant: "warning",
            title: "Always review AI output",
            text: "Treat AI responses as a first draft. For billing, security or legal issues, a human must confirm the answer before sending.",
          },
        ],
      },
    ],
  },

  {
    id: "virtualizor-network",
    title: "Virtualizor Network Modes",
    description:
      "Understand bridged vs routed networking on VPS and when to pick each mode.",
    icon: Network,
    gradient: "from-cyan-500 to-blue-500",
    articles: [
      {
        id: "bridged-vs-routed",
        title: "Bridged vs Routed Networking",
        summary:
          "A quick reference to the two networking modes and their trade-offs.",
        readMinutes: 4,
        body: [
          { kind: "heading", text: "Bridged mode" },
          {
            kind: "paragraph",
            text: "The VPS appears as a direct neighbor on the physical network with its own IP and MAC. Best for full network-level control.",
          },
          { kind: "heading", text: "Routed mode" },
          {
            kind: "paragraph",
            text: "The host node routes traffic to the VPS. More isolation, better for dense multi-tenant setups, slightly different default gateway configuration.",
          },
          {
            kind: "callout",
            variant: "info",
            title: "Which should I pick?",
            text: "If you plan to run custom protocols or need direct LAN behavior, go bridged. For general-purpose VPS workloads, routed is the safer default.",
          },
        ],
      },
    ],
  },
];

// ---------------------------------------------------------------------------
// Small presentational helpers
// ---------------------------------------------------------------------------

function Block({ block }: { block: KbBlock }) {
  switch (block.kind) {
    case "paragraph":
      return <p className="text-slate-700 leading-relaxed text-[15px]">{block.text}</p>;
    case "heading":
      return (
        <h3 className="text-lg font-bold text-slate-900 mt-4 flex items-center gap-2">
          <span className="w-1.5 h-5 rounded bg-[#0e6305]" />
          {block.text}
        </h3>
      );
    case "list":
      return (
        <ul className="space-y-1.5">
          {block.items.map((it) => (
            <li key={it} className="flex items-start gap-2 text-slate-700 text-[15px]">
              <CheckCircle2 className="w-4 h-4 text-[#0e6305] mt-0.5 shrink-0" />
              <span>{it}</span>
            </li>
          ))}
        </ul>
      );
    case "ordered":
      return (
        <ol className="space-y-2 list-decimal list-inside marker:text-[#0e6305] marker:font-bold">
          {block.items.map((it) => (
            <li key={it} className="text-slate-700 text-[15px] leading-relaxed">
              {it}
            </li>
          ))}
        </ol>
      );
    case "code":
      return (
        <pre className="bg-slate-900 text-slate-100 text-xs md:text-sm rounded-xl p-4 overflow-x-auto border border-slate-800">
          <code>{block.code}</code>
        </pre>
      );
    case "callout": {
      const styles = {
        info: {
          wrap: "bg-sky-50 border-sky-200 text-sky-900",
          icon: <Lightbulb className="w-5 h-5 text-sky-600" />,
        },
        warning: {
          wrap: "bg-amber-50 border-amber-200 text-amber-900",
          icon: <AlertTriangle className="w-5 h-5 text-amber-600" />,
        },
        success: {
          wrap: "bg-emerald-50 border-emerald-200 text-emerald-900",
          icon: <CheckCircle2 className="w-5 h-5 text-emerald-600" />,
        },
      }[block.variant];
      return (
        <div className={`rounded-xl border p-4 flex items-start gap-3 ${styles.wrap}`}>
          <div className="shrink-0 mt-0.5">{styles.icon}</div>
          <div>
            <div className="font-bold mb-0.5">{block.title}</div>
            <p className="text-[14px] leading-relaxed">{block.text}</p>
          </div>
        </div>
      );
    }
  }
}

// ---------------------------------------------------------------------------
// Page component
// ---------------------------------------------------------------------------

export default function KnowledgeBase() {
  const [query, setQuery] = useState("");
  const [activeCategoryId, setActiveCategoryId] = useState<string>(CATEGORIES[0].id);
  const [activeArticleId, setActiveArticleId] = useState<string | null>(null);

  // Global search across all categories and articles.
  const searchResults = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return null;

    const hits: Array<{ category: KbCategory; article: KbArticle }> = [];
    for (const cat of CATEGORIES) {
      for (const art of cat.articles) {
        const haystack =
          `${cat.title} ${art.title} ${art.summary} ${art.body
            .map((b) => {
              if (b.kind === "paragraph" || b.kind === "heading") return b.text;
              if (b.kind === "list" || b.kind === "ordered") return b.items.join(" ");
              if (b.kind === "code") return b.code;
              if (b.kind === "callout") return `${b.title} ${b.text}`;
              return "";
            })
            .join(" ")}`.toLowerCase();
        if (haystack.includes(q)) hits.push({ category: cat, article: art });
      }
    }
    return hits;
  }, [query]);

  const activeCategory =
    CATEGORIES.find((c) => c.id === activeCategoryId) ?? CATEGORIES[0];
  const activeArticle =
    activeCategory.articles.find((a) => a.id === activeArticleId) ?? null;

  // Totals for hero stats.
  const totals = useMemo(() => {
    let articles = 0;
    for (const c of CATEGORIES) articles += c.articles.length;
    return { categories: CATEGORIES.length, articles };
  }, []);

  const quickLinks: Array<{ icon: LucideIcon; label: string; to: string }> = [
    { icon: LayoutDashboard, label: "Clients Portal", to: "/client" },
    { icon: FileText, label: "Open a ticket", to: "/tickets" },
    { icon: Globe, label: "Domain search", to: "/domain-search" },
    { icon: Activity, label: "Uptime Monitor", to: "/uptime-monitor" },
    { icon: Mail, label: "Bizmail360", to: "/bizmail360" },
    { icon: MessageSquare, label: "WhatsApp API", to: "/whatsapp-api" },
  ];

  const popularArticles = useMemo(() => {
    const flat: Array<{ cat: KbCategory; art: KbArticle }> = [];
    for (const c of CATEGORIES)
      for (const a of c.articles) if (a.tag === "Popular") flat.push({ cat: c, art: a });
    return flat;
  }, []);

  return (
    <SiteLayout>
      {/* HERO ---------------------------------------------------------- */}
      <section className="relative overflow-hidden bg-[#0b1d14] text-white">
        <div className="absolute inset-0 -z-0">
          <div className="absolute inset-0 bg-gradient-to-br from-[#0b1d14] via-[#123826] to-[#0e6305]" />
          <div className="absolute -top-40 -right-32 w-[40rem] h-[40rem] rounded-full bg-[#0e6305]/40 blur-3xl" />
          <div className="absolute -bottom-40 -left-32 w-[40rem] h-[40rem] rounded-full bg-emerald-400/10 blur-3xl" />
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-32 pb-20 text-center">
          <AnimateIn>
            <div className="inline-flex items-center gap-2 bg-emerald-400/15 border border-emerald-400/40 backdrop-blur-sm rounded-full px-4 py-1.5 text-xs md:text-sm mb-5">
              <BookOpen className="w-4 h-4" />
              DoItEasy Knowledge Base
            </div>
            <h1 className="text-4xl md:text-6xl font-extrabold leading-tight mb-5 max-w-3xl mx-auto">
              Answers, guides & tutorials —{" "}
              <span className="text-emerald-300">all in one place</span>
            </h1>
            <p className="text-lg md:text-xl text-slate-200 mb-8 leading-relaxed max-w-2xl mx-auto">
              Search across {totals.articles}+ articles covering hosting, VPS,
              domains, email, WhatsApp API, security and more.
            </p>

            {/* Search ----------------------------------------------------- */}
            <div className="max-w-2xl mx-auto relative">
              <div className="relative">
                <Search className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <input
                  type="search"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="Search the knowledge base (e.g. ‘SPF record’, ‘VPS reboot’, ‘ticket API’)"
                  className="w-full pl-14 pr-5 py-4 rounded-2xl bg-white/95 backdrop-blur text-slate-900 placeholder:text-slate-400 border border-white/30 focus:border-emerald-400 focus:ring-2 focus:ring-emerald-300/50 outline-none shadow-[0_20px_50px_-20px_rgba(16,185,129,0.6)]"
                  aria-label="Search the knowledge base"
                />
              </div>
              {query.trim() && searchResults && (
                <div className="absolute left-0 right-0 mt-2 bg-white text-slate-900 rounded-2xl shadow-2xl border border-slate-200 max-h-96 overflow-y-auto z-20 text-left">
                  {searchResults.length === 0 ? (
                    <div className="p-5 text-sm text-slate-500">
                      No articles match{" "}
                      <span className="font-semibold">&ldquo;{query}&rdquo;</span>. Try a
                      different keyword or{" "}
                      <Link
                        to="/tickets"
                        className="text-[#0e6305] font-semibold underline"
                      >
                        open a support ticket
                      </Link>
                      .
                    </div>
                  ) : (
                    <ul className="divide-y divide-slate-100">
                      {searchResults.slice(0, 8).map(({ category, article }) => (
                        <li key={`${category.id}-${article.id}`}>
                          <button
                            type="button"
                            className="w-full text-left px-5 py-3 hover:bg-emerald-50 transition flex items-start gap-3"
                            onClick={() => {
                              setActiveCategoryId(category.id);
                              setActiveArticleId(article.id);
                              setQuery("");
                              // Scroll to category details
                              requestAnimationFrame(() => {
                                document
                                  .getElementById("kb-details")
                                  ?.scrollIntoView({ behavior: "smooth", block: "start" });
                              });
                            }}
                          >
                            <span className="w-9 h-9 rounded-lg bg-[#0e6305]/10 text-[#0e6305] flex items-center justify-center shrink-0">
                              <category.icon className="w-4 h-4" />
                            </span>
                            <span className="min-w-0 flex-1">
                              <span className="block text-sm font-bold text-slate-900">
                                {article.title}
                              </span>
                              <span className="block text-xs text-slate-500 mt-0.5 truncate">
                                {category.title} · {article.summary}
                              </span>
                            </span>
                            <ArrowUpRight className="w-4 h-4 text-slate-400 mt-1" />
                          </button>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              )}
            </div>

            {/* Quick links ----------------------------------------------- */}
            <div className="mt-8 flex flex-wrap justify-center gap-2">
              {quickLinks.map(({ icon: Icon, label, to }) => (
                <Link
                  key={label}
                  to={to}
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 border border-white/25 hover:bg-white/20 text-sm font-semibold transition backdrop-blur-sm"
                >
                  <Icon className="w-4 h-4" />
                  {label}
                </Link>
              ))}
            </div>
          </AnimateIn>
        </div>
      </section>

      {/* STATS --------------------------------------------------------- */}
      <section className="py-10 bg-white border-b border-slate-100">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[
              { icon: BookOpen, label: "Categories", value: String(totals.categories) },
              { icon: FileText, label: "Articles", value: `${totals.articles}+` },
              { icon: Users, label: "Monthly readers", value: "50k+" },
              { icon: Sparkles, label: "AI-assisted answers", value: "24/7" },
            ].map((s, idx) => (
              <AnimateIn
                key={s.label}
                delay={idx * 70}
                className="text-center p-5 rounded-2xl bg-gradient-to-br from-emerald-50 to-white border border-emerald-100"
              >
                <div className="w-11 h-11 mx-auto rounded-xl bg-[#0e6305] text-white flex items-center justify-center mb-2">
                  <s.icon className="w-5 h-5" />
                </div>
                <div className="text-2xl md:text-3xl font-extrabold text-[#0e6305]">
                  {s.value}
                </div>
                <div className="text-xs md:text-sm text-slate-600 mt-0.5 font-medium">
                  {s.label}
                </div>
              </AnimateIn>
            ))}
          </div>
        </div>
      </section>

      {/* CATEGORIES GRID ---------------------------------------------- */}
      <section className="py-16 bg-slate-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="text-center mb-10 max-w-3xl mx-auto">
            <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
              Browse by category
            </span>
            <h2 className="text-3xl md:text-4xl font-bold text-[#111827] mt-2">
              Pick a topic to get started
            </h2>
            <p className="text-slate-600 mt-3">
              Every category is curated by our support team based on real
              customer questions.
            </p>
          </AnimateIn>

          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {CATEGORIES.map((cat, idx) => {
              const Icon = cat.icon;
              const isActive = cat.id === activeCategoryId;
              return (
                <AnimateIn key={cat.id} delay={idx * 60}>
                  <button
                    type="button"
                    onClick={() => {
                      setActiveCategoryId(cat.id);
                      setActiveArticleId(null);
                      requestAnimationFrame(() => {
                        document
                          .getElementById("kb-details")
                          ?.scrollIntoView({ behavior: "smooth", block: "start" });
                      });
                    }}
                    className={`w-full text-left group relative rounded-2xl p-5 border bg-white hover:-translate-y-1 hover:shadow-xl transition ${
                      isActive
                        ? "border-[#0e6305] shadow-lg"
                        : "border-slate-200 hover:border-[#0e6305]"
                    }`}
                  >
                    <div
                      className={`w-12 h-12 rounded-xl bg-gradient-to-br ${cat.gradient} text-white flex items-center justify-center mb-3 shadow-md`}
                    >
                      <Icon className="w-6 h-6" />
                    </div>
                    <h3 className="text-lg font-bold text-slate-900 mb-1.5 flex items-center gap-1.5">
                      {cat.title}
                      <ChevronRight className="w-4 h-4 text-slate-400 group-hover:text-[#0e6305] group-hover:translate-x-0.5 transition" />
                    </h3>
                    <p className="text-sm text-slate-600 leading-relaxed line-clamp-2">
                      {cat.description}
                    </p>
                    <div className="mt-4 inline-flex items-center gap-1.5 text-xs font-bold text-[#0e6305]">
                      <FileText className="w-3.5 h-3.5" />
                      {cat.articles.length} articles
                    </div>
                  </button>
                </AnimateIn>
              );
            })}
          </div>
        </div>
      </section>

      {/* DETAIL: ARTICLE LIST + READER -------------------------------- */}
      <section id="kb-details" className="py-16 bg-white scroll-mt-24">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid lg:grid-cols-[320px_minmax(0,1fr)] gap-8">
            {/* Sidebar: categories + articles in active category */}
            <aside className="lg:sticky lg:top-24 self-start">
              <div className="bg-gradient-to-br from-slate-50 to-white border border-slate-200 rounded-2xl p-5 shadow-sm">
                <div className="text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-3">
                  Categories
                </div>
                <nav className="space-y-1">
                  {CATEGORIES.map((cat) => {
                    const Icon = cat.icon;
                    const isActive = cat.id === activeCategoryId;
                    return (
                      <button
                        key={cat.id}
                        type="button"
                        onClick={() => {
                          setActiveCategoryId(cat.id);
                          setActiveArticleId(null);
                        }}
                        className={`w-full text-left flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-semibold transition ${
                          isActive
                            ? "bg-[#0e6305] text-white shadow"
                            : "text-slate-700 hover:bg-slate-100"
                        }`}
                      >
                        <Icon className="w-4 h-4 shrink-0" />
                        <span className="truncate">{cat.title}</span>
                      </button>
                    );
                  })}
                </nav>

                <div className="mt-6 pt-5 border-t border-slate-200">
                  <div className="text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-3">
                    Still stuck?
                  </div>
                  <Link
                    to="/tickets"
                    className="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg bg-[#0e6305] text-white text-sm font-bold hover:bg-[#0a4a04] transition shadow"
                  >
                    <MessageSquare className="w-4 h-4" />
                    Open a ticket
                  </Link>
                </div>
              </div>
            </aside>

            {/* Main panel */}
            <div className="min-w-0">
              {/* Active category header */}
              <div className="flex items-start gap-4 mb-6">
                <div
                  className={`w-14 h-14 rounded-2xl bg-gradient-to-br ${activeCategory.gradient} text-white flex items-center justify-center shadow-lg shrink-0`}
                >
                  <activeCategory.icon className="w-7 h-7" />
                </div>
                <div className="min-w-0">
                  <h2 className="text-2xl md:text-3xl font-extrabold text-slate-900">
                    {activeCategory.title}
                  </h2>
                  <p className="text-slate-600 mt-1">{activeCategory.description}</p>
                </div>
              </div>

              {/* Article reader or article list */}
              {activeArticle ? (
                <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 md:p-8">
                  <button
                    type="button"
                    onClick={() => setActiveArticleId(null)}
                    className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-[#0e6305] font-semibold mb-4"
                  >
                    <ChevronRight className="w-4 h-4 rotate-180" />
                    Back to {activeCategory.title}
                  </button>

                  <div className="flex flex-wrap items-center gap-2 mb-2">
                    {activeArticle.tag && (
                      <span
                        className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full ${
                          activeArticle.tag === "Popular"
                            ? "bg-amber-100 text-amber-800"
                            : activeArticle.tag === "New"
                            ? "bg-emerald-100 text-emerald-800"
                            : "bg-sky-100 text-sky-800"
                        }`}
                      >
                        {activeArticle.tag}
                      </span>
                    )}
                    <span className="text-xs text-slate-500 font-medium">
                      {activeArticle.readMinutes} min read
                    </span>
                  </div>

                  <h1 className="text-2xl md:text-3xl font-extrabold text-slate-900 leading-tight">
                    {activeArticle.title}
                  </h1>
                  <p className="text-slate-600 mt-2 text-base leading-relaxed">
                    {activeArticle.summary}
                  </p>

                  <div className="mt-6 space-y-4">
                    {activeArticle.body.map((block, i) => (
                      <Block key={i} block={block} />
                    ))}
                  </div>

                  {/* Per-article feedback widget (thumbs up/down + comment) */}
                  <FeedbackWidget
                    articleId={activeArticle.id}
                    categoryId={activeCategory.id}
                    articleTitle={activeArticle.title}
                  />

                  {activeArticle.cta && (
                    <div className="mt-8 flex items-center gap-3 p-4 rounded-xl bg-emerald-50 border border-emerald-200">
                      <Sparkles className="w-5 h-5 text-[#0e6305]" />
                      <div className="flex-1">
                        <div className="font-bold text-emerald-900">
                          Ready to take the next step?
                        </div>
                        <div className="text-sm text-emerald-800">
                          Use the button to jump straight to the related product area.
                        </div>
                      </div>
                      {activeArticle.cta.external ? (
                        <a
                          href={activeArticle.cta.to}
                          target="_blank"
                          rel="noreferrer"
                          className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-[#0e6305] text-white text-sm font-bold hover:bg-[#0a4a04] transition"
                        >
                          {activeArticle.cta.label}
                          <ExternalLink className="w-3.5 h-3.5" />
                        </a>
                      ) : (
                        <Link
                          to={activeArticle.cta.to}
                          className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-[#0e6305] text-white text-sm font-bold hover:bg-[#0a4a04] transition"
                        >
                          {activeArticle.cta.label}
                          <ArrowRight className="w-4 h-4" />
                        </Link>
                      )}
                    </div>
                  )}

                  {/* Next-article navigation */}
                  <div className="mt-8 pt-6 border-t border-slate-200 flex flex-wrap gap-3">
                    {activeCategory.articles
                      .filter((a) => a.id !== activeArticle.id)
                      .slice(0, 2)
                      .map((a) => (
                        <button
                          key={a.id}
                          type="button"
                          onClick={() => {
                            setActiveArticleId(a.id);
                            requestAnimationFrame(() => {
                              document
                                .getElementById("kb-details")
                                ?.scrollIntoView({ behavior: "smooth", block: "start" });
                            });
                          }}
                          className="flex-1 min-w-[240px] text-left p-4 rounded-xl border border-slate-200 hover:border-[#0e6305] hover:shadow transition bg-white"
                        >
                          <div className="text-[10px] font-bold uppercase tracking-wider text-slate-400">
                            Next
                          </div>
                          <div className="font-bold text-slate-900 mt-0.5">
                            {a.title}
                          </div>
                          <div className="text-xs text-slate-500 mt-1 line-clamp-2">
                            {a.summary}
                          </div>
                        </button>
                      ))}
                  </div>
                </div>
              ) : (
                <div className="grid sm:grid-cols-2 gap-4">
                  {activeCategory.articles.map((art, idx) => (
                    <AnimateIn key={art.id} delay={idx * 50}>
                      <button
                        type="button"
                        onClick={() => setActiveArticleId(art.id)}
                        className="w-full text-left h-full group bg-white border border-slate-200 hover:border-[#0e6305] hover:shadow-lg rounded-2xl p-5 transition"
                      >
                        <div className="flex items-start gap-3">
                          <div className="w-10 h-10 rounded-xl bg-[#0e6305]/10 text-[#0e6305] flex items-center justify-center shrink-0 group-hover:bg-[#0e6305] group-hover:text-white transition">
                            <FileText className="w-4 h-4" />
                          </div>
                          <div className="min-w-0 flex-1">
                            <div className="flex items-center gap-2 flex-wrap mb-1">
                              {art.tag && (
                                <span
                                  className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full ${
                                    art.tag === "Popular"
                                      ? "bg-amber-100 text-amber-800"
                                      : art.tag === "New"
                                      ? "bg-emerald-100 text-emerald-800"
                                      : "bg-sky-100 text-sky-800"
                                  }`}
                                >
                                  {art.tag}
                                </span>
                              )}
                              <span className="text-[11px] text-slate-500 font-medium">
                                {art.readMinutes} min read
                              </span>
                            </div>
                            <h3 className="font-bold text-slate-900 leading-tight group-hover:text-[#0e6305]">
                              {art.title}
                            </h3>
                            <p className="text-sm text-slate-600 mt-1 line-clamp-2">
                              {art.summary}
                            </p>
                          </div>
                          <ArrowRight className="w-4 h-4 text-slate-400 group-hover:text-[#0e6305] group-hover:translate-x-0.5 transition shrink-0 mt-2" />
                        </div>
                      </button>
                    </AnimateIn>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* POPULAR ARTICLES --------------------------------------------- */}
      {popularArticles.length > 0 && (
        <section className="py-16 bg-slate-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <AnimateIn className="text-center mb-10 max-w-2xl mx-auto">
              <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
                Trending this week
              </span>
              <h2 className="text-3xl md:text-4xl font-bold text-[#111827] mt-2">
                Popular articles
              </h2>
            </AnimateIn>

            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
              {popularArticles.slice(0, 6).map(({ cat, art }, idx) => (
                <AnimateIn key={`${cat.id}-${art.id}`} delay={idx * 60}>
                  <button
                    type="button"
                    onClick={() => {
                      setActiveCategoryId(cat.id);
                      setActiveArticleId(art.id);
                      requestAnimationFrame(() => {
                        document
                          .getElementById("kb-details")
                          ?.scrollIntoView({ behavior: "smooth", block: "start" });
                      });
                    }}
                    className="w-full text-left h-full bg-white rounded-2xl border border-slate-200 hover:border-[#0e6305] hover:shadow-xl hover:-translate-y-0.5 transition p-5 group"
                  >
                    <div
                      className={`w-11 h-11 rounded-xl bg-gradient-to-br ${cat.gradient} text-white flex items-center justify-center mb-3 shadow`}
                    >
                      <cat.icon className="w-5 h-5" />
                    </div>
                    <div className="text-[11px] font-bold uppercase tracking-wider text-slate-400">
                      {cat.title}
                    </div>
                    <h3 className="font-bold text-slate-900 mt-1 group-hover:text-[#0e6305]">
                      {art.title}
                    </h3>
                    <p className="text-sm text-slate-600 mt-1.5 line-clamp-2">
                      {art.summary}
                    </p>
                    <div className="mt-3 inline-flex items-center gap-1 text-xs font-bold text-[#0e6305]">
                      Read article <ArrowRight className="w-3.5 h-3.5" />
                    </div>
                  </button>
                </AnimateIn>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* SEO-FRIENDLY TITLES BAND ------------------------------------ */}
      <section className="py-16 bg-white">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn>
            <div className="rounded-3xl border border-slate-200 bg-gradient-to-br from-emerald-50 via-white to-white p-8 md:p-10">
              <div className="flex items-center gap-3 mb-4">
                <KeyRound className="w-6 h-6 text-[#0e6305]" />
                <h2 className="text-2xl md:text-3xl font-bold text-slate-900">
                  Most searched guides
                </h2>
              </div>
              <p className="text-slate-600 mb-6">
                Shortcuts to the guides people ask about most often.
              </p>
              <div className="grid sm:grid-cols-2 gap-3">
                {[
                  { label: "DoItEasy Clients Portal Guide", to: "", cat: "clients-portal", art: "clients-portal-overview" },
                  { label: "How to Manage VPS from Clients Portal", to: "", cat: "hosting-vps", art: "virtualizor" },
                  { label: "Clients Portal API Integration Tutorial", to: "", cat: "clients-portal", art: "api-integration" },
                  { label: "Fix Clients Portal Access Issues", to: "", cat: "clients-portal", art: "portal-access-issues" },
                  { label: "Open Support Ticket in DoItEasy Portal", to: "", cat: "clients-portal", art: "opening-tickets" },
                  { label: "SPF, DKIM & PTR Setup Guide", to: "", cat: "security", art: "spf-dkim-ptr" },
                ].map((s) => (
                  <button
                    key={s.label}
                    type="button"
                    onClick={() => {
                      setActiveCategoryId(s.cat);
                      setActiveArticleId(s.art);
                      requestAnimationFrame(() => {
                        document
                          .getElementById("kb-details")
                          ?.scrollIntoView({ behavior: "smooth", block: "start" });
                      });
                    }}
                    className="flex items-center justify-between gap-3 px-4 py-3 rounded-xl bg-white border border-slate-200 hover:border-[#0e6305] hover:shadow transition text-left"
                  >
                    <span className="font-semibold text-slate-800">{s.label}</span>
                    <ArrowRight className="w-4 h-4 text-[#0e6305]" />
                  </button>
                ))}
              </div>
            </div>
          </AnimateIn>
        </div>
      </section>

      {/* SUPPORT CTA --------------------------------------------------- */}
      <section className="py-20 bg-slate-50">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="rounded-3xl bg-gradient-to-br from-[#0e6305] via-[#0a5004] to-[#1e3828] text-white p-10 md:p-14 shadow-2xl text-center relative overflow-hidden">
            <div className="absolute -top-20 -right-20 w-72 h-72 rounded-full bg-white/10 blur-3xl" />
            <div className="absolute -bottom-20 -left-20 w-72 h-72 rounded-full bg-[#f5c400]/20 blur-3xl" />
            <div className="relative">
              <Bell className="w-12 h-12 mx-auto mb-5 text-[#f5c400]" />
              <h2 className="text-3xl md:text-5xl font-extrabold mb-4">
                Didn&apos;t find what you were looking for?
              </h2>
              <p className="text-slate-100 max-w-2xl mx-auto mb-8">
                Our 24/7 support team is just one click away. Open a ticket and
                we&apos;ll get back to you — usually within a few hours.
              </p>
              <div className="flex flex-wrap justify-center gap-3">
                <Link
                  to="/tickets"
                  className="px-8 py-3.5 bg-[#f5c400] text-[#1e3828] font-bold rounded-md hover:bg-yellow-400 transition inline-flex items-center gap-2"
                >
                  <TerminalIcon className="w-4 h-4" /> Open a Support Ticket
                </Link>
                <Link
                  to="/about"
                  className="px-8 py-3.5 bg-white/10 border border-white/30 text-white font-bold rounded-md hover:bg-white/20 transition inline-flex items-center gap-2"
                >
                  Contact our team <ArrowRight className="w-4 h-4" />
                </Link>
              </div>
            </div>
          </AnimateIn>
        </div>
      </section>
    </SiteLayout>
  );
}