'use client';

import { useState, useEffect } from 'react';
import Navbar from '@/components/layout/Navbar';
import Footer from '@/components/layout/Footer';
import type { DocsLocale, NavGroup } from '@/lib/docs-types';
import Link from 'next/link';
import { Menu, X } from 'lucide-react';
import styles from './DocsLayout.module.css';
import DocsSearch from '../docs/DocsSearch';
import TableOfContents from '../docs/TableOfContents';

type DocsLayoutProps = {
  locale: DocsLocale;
  currentSlug: string;
  children: React.ReactNode;
  docsNavigation: NavGroup[];
};


export default function DocsLayout({ locale, currentSlug, children, docsNavigation }: DocsLayoutProps) {
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);

  const currentGroup = docsNavigation.find(group =>
    group.items.some(item => item.slug === currentSlug)
  );
  const currentItem = currentGroup?.items.find(item => item.slug === currentSlug);

  const categoryLabel = currentGroup?.label[locale] ?? '';
  const pageTitle = currentItem?.label[locale] ?? '';

  const toggleSidebar = () => {
    setIsSidebarOpen(!isSidebarOpen);
  };

  const closeSidebar = () => {
    setIsSidebarOpen(false);
  };

  // Close sidebar when clicking outside on mobile
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (isSidebarOpen && !target.closest(`.${styles.sidebar}`) && !target.closest(`.${styles.sidebarToggle}`)) {
        closeSidebar();
      }
    };

    if (isSidebarOpen) {
      document.addEventListener('click', handleClickOutside);
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }

    return () => {
      document.removeEventListener('click', handleClickOutside);
      document.body.style.overflow = '';
    };
  }, [isSidebarOpen]);

  return (
    <main>
      <Navbar />
      <section className={styles.container}>
        {/* Sidebar toggle button for mobile */}
        <button
          className={styles.sidebarToggle}
          onClick={toggleSidebar}
          aria-label={locale === 'en' ? 'Toggle sidebar' : 'Mở/đóng sidebar'}
          aria-expanded={isSidebarOpen}
        >
          {isSidebarOpen ? <X size={20} /> : <Menu size={20} />}
        </button>

        {/* Overlay for mobile */}
        {isSidebarOpen && (
          <div className={styles.sidebarOverlay} onClick={closeSidebar} />
        )}

        {/* Sidebar trái: nav docs nhiều cấp */}
        <aside className={`${styles.sidebar} ${isSidebarOpen ? styles.sidebarOpen : ''}`}>
          <div className={styles.sidebarHeader}>
            <div className={styles.sidebarLabel}>
              {locale === 'en' ? 'Documentation' : 'Tài liệu'}
            </div>
            <button
              className={styles.sidebarClose}
              onClick={closeSidebar}
              aria-label={locale === 'en' ? 'Close sidebar' : 'Đóng sidebar'}
            >
              <X size={20} />
            </button>
          </div>
          <nav className={styles.sidebarNav}>
            {docsNavigation.map(group => (
              <div key={group.id}>
                <div className={styles.sidebarGroupTitle}>{group.label[locale]}</div>
                <div className={styles.sidebarGroupItems}>
                  {group.items.map(item => {
                    const href = `/${locale}/docs/${item.slug}`;
                    const isActive = currentSlug === item.slug;

                    return (
                      <Link
                        key={item.id}
                        href={href}
                        className={`${styles.sidebarLink} ${isActive ? styles.sidebarLinkActive : ''
                          }`}
                        onClick={closeSidebar}
                      >
                        {item.label[locale]}
                      </Link>
                    );
                  })}
                </div>
              </div>
            ))}
          </nav>
        </aside>

        {/* Nội dung MDX ở giữa */}
        <article className={styles.content}>
          <div className={styles.contentHeaderRow}>
            {pageTitle && (
              <header className={styles.header}>
                {categoryLabel && <div className={styles.headerCategory}>{categoryLabel}</div>}
                <div className={styles.headerTitle}>{pageTitle}</div>
              </header>
            )}
            <DocsSearch
              placeholder={locale === 'en' ? 'Search documentation…' : 'Tìm trong tài liệu…'}
              locale={locale}
              docsNavigation={docsNavigation}
            />

          </div>
          <div data-docs-content className={styles.contentBody}>
            {children}
          </div>
        </article>

        {/* Table of Contents bên phải */}
        <TableOfContents locale={locale} />
      </section>
      <Footer />
    </main>
  );
}

