import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { db } from '../firebase/config';
import { ref, onValue, push, set } from 'firebase/database';
import { Utensils, Star, Clock, MapPin, ChefHat, Instagram, Facebook, ArrowRight, MessageSquare, Send, Plus } from 'lucide-react';

export default function CustomerMenu() {
  const defaultItems = [
    { id: 'h1', name: 'Hamburgesa Clásica', price: 12.50, category: 'Fuertes', image: '/images/burger.png', active: true },
    { id: 'p1', name: 'Pasta Pomodoro', price: 10.00, category: 'Pasta', image: '/images/pasta.png', active: true },
    { id: 't1', name: 'Tacos de Pollo', price: 9.00, category: 'Entradas', image: '/images/tacos.png', active: true },
    { id: 'z1', name: 'Pizza Margherita', price: 14.00, category: 'Pizzas', image: '/images/pizza.png', active: true },
    { id: 'e1', name: 'Ensalada César', price: 8.50, category: 'Entradas', image: 'https://images.unsplash.com/photo-1550304943-4f24f54ddde9?auto=format&fit=crop&q=80&w=1000', active: true },
    { id: 's1', name: 'Sopa de Tomate', price: 7.00, category: 'Entradas', image: 'https://images.unsplash.com/photo-1547592166-23ac45744acd?auto=format&fit=crop&q=80&w=1000', active: true },
    { id: 'g1', name: 'Sandwich Gourmet', price: 11.00, category: 'Fuertes', image: 'https://images.unsplash.com/photo-1528735602780-2552fd46c7af?auto=format&fit=crop&q=80&w=1000', active: true },
    { id: 'm1', name: 'Chocolate Muffin', price: 4.50, category: 'Postres', image: 'https://images.unsplash.com/photo-1582231222779-1adb0b322f84?auto=format&fit=crop&q=80&w=1000', active: true },
    { id: 'sp1', name: 'Ribeye Premium', price: 35.00, category: 'Especialidades', image: '/images/steak.png', active: true },
    { id: 'sp2', name: 'Risotto de Trufa', price: 28.00, category: 'Especialidades', image: '/images/risotto.png', active: true },
    { id: 'sp3', name: 'Salmón Glaseado', price: 26.00, category: 'Especialidades', image: 'https://images.unsplash.com/photo-1467003909585-2f8a72700288?auto=format&fit=crop&q=80&w=1000', active: true },
    { id: 'sp4', name: 'Pato a la Naranja', price: 32.00, category: 'Especialidades', image: 'https://images.unsplash.com/photo-1626082927389-6cd097cdc6ec?auto=format&fit=crop&q=80&w=1000', active: true },
    { id: 'sp5', name: 'Langosta Thermidor', price: 45.00, category: 'Especialidades', image: 'https://images.unsplash.com/photo-1553243599-c052f82958d2?auto=format&fit=crop&q=80&w=1000', active: true }
  ];

  const [menuItems, setMenuItems] = useState(defaultItems);
  const [categories, setCategories] = useState(['Todos', 'Entradas', 'Fuertes', 'Pizzas', 'Pasta', 'Postres', 'Especialidades']);
  const [activeCategory, setActiveCategory] = useState('Todos');
  const [menuTheme, setMenuTheme] = useState('light');
  const [feedback, setFeedback] = useState({ rating: 5, comment: '' });
  const [submitted, setSubmitted] = useState(false);
  const [cartCount, setCartCount] = useState(0);
  const navigate = useNavigate();

  useEffect(() => {
    try {
      const menuRef = ref(db, 'menu');
      onValue(menuRef, (snapshot) => {
        const data = snapshot.val();
        if (data) {
          const list = Object.keys(data).map(id => ({ id, ...data[id] })).filter(item => item.active !== false);
          if (list.length > 0) {
            setMenuItems(list);
            const cats = [...new Set(list.map(item => item.category))];
            setCategories(['Todos', ...cats]);
          }
        }
      }, (error) => {
        console.error("Error cargando menú de Firebase, usando locales:", error);
      });

      const themeRef = ref(db, 'config/menuTheme');
      onValue(themeRef, (snapshot) => {
        if (snapshot.exists()) setMenuTheme(snapshot.val());
      });
    } catch (err) {
      console.error("Error en useEffect de CustomerMenu:", err);
    }
  }, []);

  const filteredItems = activeCategory === 'Todos' 
    ? menuItems 
    : menuItems.filter(item => item.category === activeCategory);

  const isDark = menuTheme === 'dark';
  // Forzamos modo claro si el usuario lo pidió
  const forceLight = true; 
  
  const themeColors = {
    bg: forceLight ? '#ffffff' : (isDark ? '#050505' : '#f8f9fa'),
    text: forceLight ? '#1a1a1a' : (isDark ? '#ffffff' : '#1a1a1a'),
    muted: forceLight ? '#666666' : (isDark ? 'rgba(255,255,255,0.5)' : 'rgba(0,0,0,0.5)'),
    card: forceLight ? '#ffffff' : (isDark ? 'rgba(255,255,255,0.02)' : 'rgba(255,255,255,0.8)'),
    border: forceLight ? '#eeeeee' : (isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'),
    accent: '#FF6B6B',
    accentGradient: 'linear-gradient(135deg, #FF6B6B 0%, #FF4757 100%)'
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      background: themeColors.bg, 
      color: themeColors.text, 
      fontFamily: "'Outfit', sans-serif",
      transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
      overflowX: 'hidden'
    }}>
      
      {/* Floating Header */}
      <header style={{
        position: 'fixed', top: 0, left: 0, width: '100%', zIndex: 1000,
        padding: '20px 40px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'rgba(255,255,255,0.8)', backdropFilter: 'blur(20px)', borderBottom: `1px solid ${themeColors.border}`,
        boxShadow: '0 2px 20px rgba(0,0,0,0.05)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <img src="/images/logo.png" alt="Logo" style={{ height: '40px' }} />
          <span style={{ fontSize: '1.5rem', fontWeight: '900', letterSpacing: '-1px', color: '#1a1a1a' }}>RESTAURANT<span style={{color: themeColors.accent}}>OS</span></span>
        </div>
        <div style={{ display: 'flex', gap: '15px', color: '#1a1a1a' }}>
          <button onClick={() => navigate('/login')} style={{ background: 'none', border: 'none', color: 'inherit', cursor: 'pointer', fontWeight: '600' }}>Admin</button>
          <div style={{ position: 'relative', cursor: 'pointer' }}>
             <Utensils size={24} />
             {cartCount > 0 && <span style={{ position: 'absolute', top: '-8px', right: '-8px', background: themeColors.accent, color: '#fff', borderRadius: '50%', width: '18px', height: '18px', fontSize: '0.7rem', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: '800' }}>{cartCount}</span>}
          </div>
        </div>
      </header>

      {/* Hero Section */}
      <section style={{ 
        height: '70vh', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: `linear-gradient(rgba(255,255,255,0.4), #ffffff), url('https://images.unsplash.com/photo-1514362545857-3bc16c4c7d1b?auto=format&fit=crop&q=80&w=2070')`,
        backgroundSize: 'cover', backgroundPosition: 'center', backgroundAttachment: 'fixed'
      }}>
        <div style={{ textAlign: 'center', padding: '0 20px', maxWidth: '900px' }} className="animate-fade-in">
          <h1 style={{ fontSize: '5rem', fontWeight: '900', marginBottom: '1.5rem', letterSpacing: '-3px', lineHeight: '0.9', color: '#1a1a1a' }}>
            Nuestra <span style={{color: themeColors.accent}}>Historia</span> y Sabor.
          </h1>
          <p style={{ fontSize: '1.4rem', color: '#666', maxWidth: '700px', margin: '0 auto', lineHeight: '1.5' }}>
            Desde 1995, fusionando la tradición culinaria con la innovación moderna.
          </p>
        </div>
      </section>

      {/* History Section */}
      <section style={{ padding: '100px 40px', background: '#fff' }}>
        <div style={{ maxWidth: '1000px', margin: '0 auto', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '60px', alignItems: 'center' }}>
          <div style={{ borderRadius: '30px', overflow: 'hidden', boxShadow: '0 30px 60px rgba(0,0,0,0.1)' }}>
            <img src="https://images.unsplash.com/photo-1552566626-52f8b828add9?auto=format&fit=crop&q=80&w=1000" alt="History" style={{ width: '100%', display: 'block' }} />
          </div>
          <div>
            <h2 style={{ fontSize: '2.5rem', fontWeight: '900', marginBottom: '1.5rem', color: '#1a1a1a' }}>Un Legado de Pasión</h2>
            <p style={{ color: '#666', fontSize: '1.1rem', lineHeight: '1.8', marginBottom: '1.5rem' }}>
              Lo que comenzó como un pequeño bistro familiar en el corazón de la ciudad, se ha transformado en un referente de la gastronomía contemporánea.
            </p>
            <p style={{ color: '#666', fontSize: '1.1rem', lineHeight: '1.8' }}>
              Nuestra misión es simple: servir felicidad en cada plato, respetando los ingredientes y celebrando la creatividad de nuestro equipo.
            </p>
          </div>
        </div>
      </section>

      {/* Main Menu Area */}
      <main style={{ maxWidth: '1400px', margin: '0 auto', padding: '80px 40px' }}>
        
        <div style={{ textAlign: 'center', marginBottom: '60px' }}>
          <h2 style={{ fontSize: '3rem', fontWeight: '900', color: '#1a1a1a' }}>Nuestra Carta Digital</h2>
          <div style={{ width: '80px', height: '5px', background: themeColors.accentGradient, margin: '20px auto', borderRadius: '10px' }}></div>
        </div>

        {/* Categories */}
        <div style={{ 
          display: 'flex', justifyContent: 'center', gap: '12px', marginBottom: '60px',
          padding: '10px', overflowX: 'auto'
        }}>
          {categories.map(cat => (
            <button
              key={cat}
              onClick={() => setActiveCategory(cat)}
              style={{
                padding: '12px 28px', borderRadius: '40px', border: activeCategory === cat ? 'none' : '1px solid #ddd', cursor: 'pointer',
                background: activeCategory === cat ? themeColors.accentGradient : '#fff',
                color: activeCategory === cat ? '#fff' : '#666',
                fontWeight: '700', transition: 'all 0.3s ease',
                whiteSpace: 'nowrap', fontSize: '0.95rem'
              }}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Menu Grid */}
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', 
          gap: '40px' 
        }}>
          {filteredItems.map(item => (
            <div key={item.id} style={{ 
              background: '#fff', borderRadius: '30px', overflow: 'hidden',
              border: '1px solid #eee', transition: 'all 0.4s ease',
              boxShadow: '0 10px 30px rgba(0,0,0,0.03)',
              position: 'relative'
            }} className="menu-card-hover">
              
              <div style={{ height: '280px', overflow: 'hidden', position: 'relative' }}>
                <img 
                  src={item.image || 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?auto=format&fit=crop&q=80&w=1760'} 
                  alt={item.name} 
                  style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                />
                <div style={{ 
                  position: 'absolute', top: '20px', right: '20px', 
                  background: 'rgba(255,255,255,0.9)', color: '#1a1a1a', padding: '8px 20px', 
                  borderRadius: '30px', fontWeight: '900', fontSize: '1.2rem', backdropFilter: 'blur(10px)',
                  boxShadow: '0 10px 20px rgba(0,0,0,0.05)'
                }}>
                  ${item.price}
                </div>
              </div>

              <div style={{ padding: '30px' }}>
                <h3 style={{ fontSize: '1.6rem', fontWeight: '800', marginBottom: '10px', color: '#1a1a1a' }}>{item.name}</h3>
                <p style={{ color: '#666', fontSize: '0.95rem', lineHeight: '1.6', marginBottom: '20px' }}>
                  Una delicia preparada con ingredientes frescos para deleitar tu paladar.
                </p>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                   <span style={{ fontSize: '0.8rem', color: themeColors.accent, fontWeight: '800', textTransform: 'uppercase' }}>{item.category}</span>
                   <button 
                    onClick={() => setCartCount(c => c + 1)}
                    style={{ 
                      background: '#f5f5f5', border: 'none', color: '#1a1a1a', 
                      width: '40px', height: '40px', borderRadius: '12px', cursor: 'pointer',
                      display: 'flex', alignItems: 'center', justifyContent: 'center'
                    }}>
                     <Plus size={20} />
                   </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </main>

      {/* Modern Footer */}
      <footer style={{ padding: '80px 40px', borderTop: '1px solid #eee', textAlign: 'center', background: '#fafafa' }}>
        <div style={{ maxWidth: '600px', margin: '0 auto' }}>
          <h2 style={{ fontSize: '2rem', fontWeight: '900', marginBottom: '1rem', color: '#1a1a1a' }}>RESTAURANT OS</h2>
          <p style={{ color: '#666', marginBottom: '30px' }}>Pasión por la cocina, amor por el servicio.</p>
          <div style={{ fontSize: '0.85rem', color: '#999' }}>
            © {new Date().getFullYear()} Gourmet Experience. Todos los derechos reservados.
          </div>
        </div>
      </footer>

    </div>
  );
}


