import React, { useEffect, useRef } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { X, Shield } from 'lucide-react';
import './Sidebar.css';

export default function Sidebar({ isOpen, onClose }) {
  const location = useLocation();
  const sidebarRef = useRef(null);

  // Close sidebar on Escape key
  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  // Focus trap on open
  useEffect(() => {
    if (isOpen && sidebarRef.current) {
      const focusable = sidebarRef.current.querySelectorAll('a, button');
      if (focusable.length > 0) {
        focusable[0].focus();
      }
    }
  }, [isOpen]);

  const navLinks = [
    { path: '/', label: 'Home' },
    { path: '/services', label: 'Services' },
    { path: '/industries', label: 'Industries' },
    { path: '/about', label: 'About' },
    { path: '/contact', label: 'Get In Touch' },
  ];

  return (
    <>
      {/* Backdrop */}
      <div className={`sidebar-backdrop ${isOpen ? 'active' : ''}`} onClick={onClose} />

      {/* Sidebar drawer */}
      <aside
        ref={sidebarRef}
        className={`sidebar ${isOpen ? 'active' : ''}`}
        aria-label="Mobile navigation menu"
        aria-hidden={!isOpen}
      >
        <div className="sidebar-header">
          <Link to="/" className="logo-link" onClick={onClose}>
            <img src="/logo.png.jpeg" alt="Cynomos Logo" className="logo-image" style={{ height: '28px', width: 'auto', borderRadius: '4px' }} />
            <span className="logo-text">Cynomos</span>
          </Link>
          <button className="sidebar-close" onClick={onClose} aria-label="Close navigation menu">
            <X size={24} />
          </button>
        </div>

        <nav className="sidebar-nav">
          <ul className="sidebar-menu">
            {navLinks.map((link) => (
              <li key={link.path} className="sidebar-menu-item">
                <Link
                  to={link.path}
                  className={`sidebar-link ${location.pathname === link.path ? 'active' : ''}`}
                  onClick={onClose}
                >
                  {link.label}
                </Link>
              </li>
            ))}
          </ul>
        </nav>

        <div className="sidebar-footer">
          <Link to="/contact" className="btn btn-primary btn-full" onClick={onClose}>
            Book Evaluation
          </Link>
        </div>
      </aside>
    </>
  );
}
