"use client";
import { HomeIcon, ExclamationCircleIcon, Cog6ToothIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState, useEffect } from 'react';

const tabs = [
  { href: "/dashboard", icon: HomeIcon, label: "Home" },
  { href: "/info", icon: ExclamationCircleIcon, label: "Info" },
  { href: "/settings", icon: Cog6ToothIcon, label: "Settings" },
];

export default function TabBar() {
  const pathname = usePathname();
  const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
  
  // Handle keyboard visibility for mobile devices
  useEffect(() => {
    // Function to detect if an input or textarea is focused (which typically means keyboard is open)
    const checkFocus = () => {
      const activeElement = document.activeElement;
      const isInput = activeElement?.tagName === 'INPUT' || activeElement?.tagName === 'TEXTAREA';
      setIsKeyboardVisible(isInput);
    };
    
    // Add event listeners for focus and blur events
    document.addEventListener('focusin', checkFocus);
    document.addEventListener('focusout', () => setIsKeyboardVisible(false));
    
    // Cleanup
    return () => {
      document.removeEventListener('focusin', checkFocus);
      document.removeEventListener('focusout', () => setIsKeyboardVisible(false));
    };
  }, []);
  
  // Hide the TabBar when keyboard is visible on mobile
  if (isKeyboardVisible) {
    return null;
  }
  
  return (
    <nav className="fixed bottom-0 left-0 right-0 z-50 bg-white border-t border-gray-200 shadow-md" style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
      <div className="flex justify-between items-center w-full max-w-md mx-auto h-12 px-2">
        {tabs.map((tab) => {
          const active = pathname.startsWith(tab.href);
          const Icon = tab.icon;
          return (
            <Link
              key={tab.href}
              href={tab.href}
              className={`flex flex-col items-center justify-center text-[10px] font-medium transition-colors duration-150 ${active ? "text-primary" : "text-gray-500"}`}
              style={{ width: '33%', maxWidth: '75px' }}
            >
              <Icon className={`w-4 h-4 mb-0.5 ${active ? "" : "opacity-70"}`} />
              <span className="truncate w-full text-center">{tab.label}</span>
            </Link>
          );
        })}
      </div>
    </nav>
  );
}
