import { useState, useEffect } from 'react';
import { Link, useSearchParams } from 'react-router-dom';

export default function Layout({ children }) {
  const [darkMode, setDarkMode] = useState(true);
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
  const [searchParams] = useSearchParams();
  const returnDate = searchParams.get('date');
  
  const isCurrentDay = selectedDate === new Date().toISOString().split('T')[0];

  useEffect(() => {
    setDarkMode(document.documentElement.classList.contains('dark'));
  }, []);

  useEffect(() => {
    if (darkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [darkMode]);

  function handleDateChange(e) {
    setSelectedDate(e.target.value);
  }

  function goToToday() {
    setSelectedDate(new Date().toISOString().split('T')[0]);
  }

  const bgMain = darkMode ? 'bg-gray-900' : 'bg-gray-100';
  const bgCard = darkMode ? 'bg-gray-800' : 'bg-white';
  const textMain = darkMode ? 'text-white' : 'text-gray-900';
  const textMuted = darkMode ? 'text-gray-400' : 'text-gray-500';
  const inputBg = darkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-300 text-gray-900';

  return (
    <div className={"min-h-screen " + bgMain}>
      {/* Persistent Header */}
      <div className={bgCard + " p-3 flex items-center justify-between sticky top-0 z-50 shadow-md"}>
        <div className="flex items-center gap-2">
          <Link to={'/?date=' + selectedDate} className="text-emerald-500 font-bold text-lg">🍽️</Link>
          <input 
            type="date" 
            value={selectedDate}
            onChange={handleDateChange}
            className={inputBg + " rounded px-2 py-1 text-sm"}
          />
          {!isCurrentDay && (
            <button onClick={goToToday} className="text-emerald-500 text-sm font-semibold">
              Today
            </button>
          )}
        </div>
        <button 
          onClick={() => setDarkMode(!darkMode)}
          className="w-10 h-10 rounded-full flex items-center justify-center text-xl"
        >
          {darkMode ? '☀️' : '🌙'}
        </button>
      </div>
      
      <div className="p-4 max-w-md mx-auto">
        {children}
      </div>
    </div>
  );
}
