import React, { useState, useEffect, useRef } from "react";
import { createRoot } from "react-dom/client";
import { GoogleGenAI } from "@google/genai";

// --- Configuration ---
// Nota: Em um app real, o número do salão viria de uma config.
const SALON_PHONE_NUMBER = "5512997335155"; // Exemplo
const API_KEY = process.env.API_KEY;
const ADMIN_PASSWORD = "242024Julio";

// --- Data Models ---

interface Service {
  id: string;
  name: string;
  price: string;
  duration: string;
  description: string;
  image: string; // Emoji or Icon class for simplicity
}

interface Product {
  id: string;
  name: string;
  price: number;
  description: string;
  image: string; // URL da imagem
}

const SERVICES: Service[] = [
  {
    id: "corte-fem",
    name: "Corte & Estilo",
    price: "A partir de R$180,00",
    duration: "60 min",
    description: "Lavagem, corte visagista e finalização.",
    image: "fa-scissors",
  },
  {
    id: "mechas",
    name: "Mechas & Luzes",
    price: "A partir de R$350,00",
    duration: "180 min",
    description: "Técnicas de balayage, ombré ou luzes tradicionais.",
    image: "fa-wand-magic-sparkles",
  },
  {
    id: "hidratacao",
    name: "Hidratação Profunda",
    price: "A partir de R$80,00",
    duration: "45 min",
    description: "Reconstrução capilar com produtos premium.",
    image: "fa-droplet",
  },
  {
    id: "manicure",
    name: "Manicure & Pedicure",
    price: "A partir de R$80,00",
    duration: "60 min",
    description: "Cuidado completo para mãos ou pés.",
    image: "fa-hand-sparkles",
  },
];

const INITIAL_PRODUCTS: Product[] = [
  {
    id: "p1",
    name: "Kit Shampoo & Condicionador Premium",
    price: 189.90,
    description: "Manutenção diária para cabelos coloridos. Protege a cor e hidrata.",
    image: "https://images.unsplash.com/photo-1535585209827-a15fcdbc4c2d?q=80&w=2070&auto=format&fit=crop"
  },
  {
    id: "p2",
    name: "Óleo Reparador de Pontas",
    price: 85.00,
    description: "Nutrição intensa e brilho instantâneo sem pesar.",
    image: "https://images.unsplash.com/photo-1620916566398-39f1143ab7be?q=80&w=1887&auto=format&fit=crop"
  },
  {
    id: "p3",
    name: "Máscara de Reconstrução",
    price: 120.00,
    description: "Recupera a fibra capilar danificada em 5 minutos.",
    image: "https://images.unsplash.com/photo-1556228720-19cb731de486?q=80&w=1931&auto=format&fit=crop"
  }
];

const PROFESSIONALS = ["Gabriele Mira", "Suellen", "Qualquer Disponível"];

// --- Components ---

function Notification({ message, type, onClose }: { message: string, type: 'error' | 'success', onClose: () => void }) {
  useEffect(() => {
    const timer = setTimeout(() => {
      onClose();
    }, 2000);
    return () => clearTimeout(timer);
  }, [onClose]);

  return (
    <div style={{
      position: 'fixed',
      top: '80px', // Abaixo do header
      left: '50%',
      transform: 'translateX(-50%)',
      backgroundColor: type === 'error' ? '#e74c3c' : '#2ecc71',
      color: 'white',
      padding: '15px 30px',
      borderRadius: '50px',
      boxShadow: '0 5px 20px rgba(0,0,0,0.2)',
      zIndex: 2000,
      fontWeight: 'bold',
      display: 'flex',
      alignItems: 'center',
      gap: '10px',
      minWidth: '300px',
      justifyContent: 'center',
      animation: 'fadeIn 0.3s ease-in-out'
    }}>
      <i className={`fa-solid ${type === 'error' ? 'fa-circle-exclamation' : 'fa-circle-check'}`}></i>
      {message}
    </div>
  );
}

function Header({ setView, currentView }) {
  return (
    <header style={{
      backgroundColor: "#1a1a1a",
      color: "#d4af37",
      padding: "1rem 2rem",
      display: "flex",
      justifyContent: "space-between",
      alignItems: "center",
      boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
      position: "sticky",
      top: 0,
      zIndex: 100
    }}>
      <div 
        onClick={() => setView("home")} 
        style={{ cursor: "pointer", display: "flex", alignItems: "center", gap: "10px" }}
      >
        <i className="fa-solid fa-gem" style={{ fontSize: "1.5rem" }}></i>
        <h1 style={{ margin: 0, fontSize: "1.5rem", letterSpacing: "1px" }}>Studio Gabriele Mira</h1>
      </div>
      <nav style={{ display: 'flex', gap: '10px' }}>
        <button 
          onClick={() => setView("store")}
          style={{
            background: currentView === 'store' ? "#d4af37" : "transparent",
            color: currentView === 'store' ? "#1a1a1a" : "#d4af37",
            border: "1px solid #d4af37",
            padding: "8px 16px",
            borderRadius: "20px",
            cursor: "pointer",
            transition: "all 0.3s",
            fontWeight: "bold"
          }}
        >
          <i className="fa-solid fa-shop"></i> Loja
        </button>
        <button 
          onClick={() => setView("ai-consultant")}
          style={{
            background: currentView === 'ai-consultant' ? "#d4af37" : "transparent",
            color: currentView === 'ai-consultant' ? "#1a1a1a" : "#d4af37",
            border: "1px solid #d4af37",
            padding: "8px 16px",
            borderRadius: "20px",
            cursor: "pointer",
            transition: "all 0.3s",
            fontWeight: "bold",
            display: "flex",
            alignItems: "center",
            gap: "5px"
          }}
        >
          <span style={{ fontSize: "1.2rem" }}>👧</span> Pergunte à Gabi
        </button>
      </nav>
    </header>
  );
}

function Hero({ onBookNow }) {
  return (
    <div style={{
      textAlign: "center",
      padding: "4rem 1rem",
      backgroundColor: "#fff",
      backgroundImage: "linear-gradient(to bottom right, #ffffff, #f9f5f0)",
    }}>
      <h2 style={{ fontSize: "2.5rem", color: "#1a1a1a", marginBottom: "1rem" }}>
        Realce sua beleza natural
      </h2>
      <p style={{ color: "#666", maxWidth: "600px", margin: "0 auto 2rem", fontSize: "1.1rem" }}>
        Experiência premium em cuidados capilares e estética. Agende seu horário e transforme seu visual hoje mesmo.
      </p>
      <button 
        onClick={onBookNow}
        style={{
          backgroundColor: "#1a1a1a",
          color: "#fff",
          border: "none",
          padding: "12px 30px",
          fontSize: "1rem",
          borderRadius: "30px",
          cursor: "pointer",
          boxShadow: "0 4px 15px rgba(0,0,0,0.2)",
          textTransform: "uppercase",
          letterSpacing: "1px",
          fontWeight: "bold"
        }}
      >
        Agendar Horário
      </button>
    </div>
  );
}

function ServiceList({ onSelectService }) {
  return (
    <div style={{ padding: "2rem", maxWidth: "1000px", margin: "0 auto" }}>
      <h3 style={{ textAlign: "center", marginBottom: "2rem", fontSize: "2rem", color: "#1a1a1a" }}>Nossos Serviços</h3>
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))",
        gap: "2rem"
      }}>
        {SERVICES.map((service) => (
          <div key={service.id} style={{
            backgroundColor: "white",
            padding: "2rem",
            borderRadius: "15px",
            boxShadow: "0 5px 20px rgba(0,0,0,0.05)",
            textAlign: "center",
            transition: "transform 0.2s",
            border: "1px solid #f0f0f0"
          }}>
            <i className={`fa-solid ${service.image}`} style={{ fontSize: "2.5rem", color: "#d4af37", marginBottom: "1rem" }}></i>
            <h4 style={{ margin: "10px 0", fontSize: "1.2rem" }}>{service.name}</h4>
            <p style={{ fontSize: "0.9rem", color: "#666", minHeight: "40px" }}>{service.description}</p>
            <div style={{ margin: "1rem 0", fontWeight: "bold", color: "#1a1a1a" }}>
              {service.price} <span style={{ fontWeight: "normal", fontSize: "0.8rem", color: "#888" }}>| {service.duration}</span>
            </div>
            <button 
              onClick={() => onSelectService(service)}
              style={{
                width: "100%",
                padding: "10px",
                backgroundColor: "#fff",
                border: "1px solid #1a1a1a",
                color: "#1a1a1a",
                borderRadius: "5px",
                cursor: "pointer",
                fontWeight: "bold",
                marginTop: "10px"
              }}
            >
              Selecionar
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProductForm({ product, onSave, onCancel }) {
  const [formData, setFormData] = useState({
    id: product ? product.id : Date.now().toString(),
    name: product ? product.name : "",
    price: product ? product.price : 0,
    description: product ? product.description : "",
    image: product ? product.image : ""
  });

  const handleChange = (e) => {
    const value = e.target.name === 'price' ? parseFloat(e.target.value) : e.target.value;
    setFormData({ ...formData, [e.target.name]: value });
  };

  return (
    <div style={{ 
      backgroundColor: "white", 
      padding: "2rem", 
      borderRadius: "15px", 
      boxShadow: "0 10px 30px rgba(0,0,0,0.1)",
      maxWidth: "500px",
      margin: "2rem auto"
    }}>
      <h3 style={{ color: "#1a1a1a", marginBottom: "1.5rem" }}>
        {product ? "Editar Produto" : "Novo Produto"}
      </h3>
      
      <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
        <div>
          <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold" }}>Nome do Produto</label>
          <input 
            type="text" 
            name="name" 
            value={formData.name} 
            onChange={handleChange}
            style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box" }}
          />
        </div>
        
        <div>
          <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold" }}>Preço (R$)</label>
          <input 
            type="number" 
            name="price" 
            value={formData.price} 
            onChange={handleChange}
            step="0.01"
            style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box" }}
          />
        </div>

        <div>
          <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold" }}>URL da Imagem</label>
          <input 
            type="text" 
            name="image" 
            value={formData.image} 
            onChange={handleChange}
            placeholder="https://..."
            style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box" }}
          />
        </div>

        <div>
          <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold" }}>Descrição</label>
          <textarea 
            name="description" 
            value={formData.description} 
            onChange={handleChange}
            rows={3}
            style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box", fontFamily: "inherit" }}
          />
        </div>

        <div style={{ display: "flex", gap: "10px", marginTop: "1rem" }}>
          <button 
            onClick={() => onSave(formData)}
            style={{
              flex: 1,
              backgroundColor: "#1a1a1a",
              color: "#fff",
              border: "none",
              padding: "12px",
              borderRadius: "5px",
              cursor: "pointer",
              fontWeight: "bold"
            }}
          >
            Salvar
          </button>
          <button 
            onClick={onCancel}
            style={{
              flex: 1,
              backgroundColor: "#f0f0f0",
              color: "#333",
              border: "none",
              padding: "12px",
              borderRadius: "5px",
              cursor: "pointer",
              fontWeight: "bold"
            }}
          >
            Cancelar
          </button>
        </div>
      </div>
    </div>
  );
}

function Store({ products, onAddProduct, onEditProduct, onDeleteProduct, onBack, showNotification }) {
  const [isAdminMode, setIsAdminMode] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [passwordAttempt, setPasswordAttempt] = useState("");
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [isAdding, setIsAdding] = useState(false);

  const handleBuy = (product: Product) => {
    const message = `Olá! Gostaria de comprar o produto:
    
*${product.id}*
*${product.name}*
Valor: R$ ${product.price.toFixed(2)}


Podemos combinar a entrega/retirada?`;

    const url = `https://wa.me/${SALON_PHONE_NUMBER}?text=${encodeURIComponent(message)}`;
    window.open(url, '_blank');
  };

  const handleAdminLogin = () => {
    if (passwordAttempt.trim() === ADMIN_PASSWORD) {
      setIsAdminMode(true);
      setShowLogin(false);
      setPasswordAttempt("");
      showNotification("Acesso Admin concedido!", "success");
    } else {
      showNotification("Senha incorreta. Tente novamente.", "error");
    }
  };

  const handleLogout = () => {
    setIsAdminMode(false);
    setIsAdding(false);
    setEditingProduct(null);
    setPasswordAttempt("");
  };

  if (isAdding || editingProduct) {
    return (
      <ProductForm 
        product={editingProduct} 
        onSave={(product) => {
          if (editingProduct) {
            onEditProduct(product);
            setEditingProduct(null);
            showNotification("Produto atualizado com sucesso!", "success");
          } else {
            onAddProduct(product);
            setIsAdding(false);
            showNotification("Produto adicionado com sucesso!", "success");
          }
        }} 
        onCancel={() => {
          setEditingProduct(null);
          setIsAdding(false);
        }} 
      />
    );
  }

  return (
    <div style={{ padding: "2rem", maxWidth: "1000px", margin: "0 auto" }}>
      <button 
        onClick={onBack} 
        style={{ 
          background: "none", 
          border: "none", 
          cursor: "pointer", 
          color: "#666", 
          marginBottom: "1rem", 
          display: "flex", 
          alignItems: "center", 
          gap: "5px",
          fontSize: "1rem",
          padding: 0
        }}
      >
        <i className="fa-solid fa-arrow-left"></i> Voltar
      </button>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "2rem", flexWrap: "wrap", gap: "15px" }}>
        <h2 style={{ fontSize: "2rem", color: "#1a1a1a", margin: 0 }}>Gabriele Mira Boutique</h2>
        
        {isAdminMode && (
          <button 
            onClick={() => setIsAdding(true)}
            style={{
              backgroundColor: "#2ecc71",
              color: "white",
              border: "none",
              padding: "10px 20px",
              borderRadius: "20px",
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: "8px",
              fontWeight: "bold",
              fontSize: "0.9rem",
              boxShadow: "0 2px 5px rgba(0,0,0,0.1)"
            }}
          >
            <i className="fa-solid fa-plus"></i> Novo Produto
          </button>
        )}
      </div>

      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
        gap: "2rem"
      }}>
        {products.map((product) => (
          <div key={product.id} style={{
            backgroundColor: "white",
            borderRadius: "15px",
            overflow: "hidden",
            boxShadow: "0 5px 20px rgba(0,0,0,0.05)",
            border: "1px solid #f0f0f0",
            display: "flex",
            flexDirection: "column",
            position: "relative"
          }}>
            <div style={{ height: "200px", overflow: "hidden", position: "relative" }}>
               <img 
                src={product.image || "https://placehold.co/600x400?text=Produto"} 
                alt={product.name}
                style={{ width: "100%", height: "100%", objectFit: "cover" }}
                onError={(e) => { (e.target as HTMLImageElement).src = "https://placehold.co/600x400?text=Sem+Imagem"; }}
              />
              {isAdminMode && (
                <div style={{ 
                    position: "absolute", 
                    top: "10px", 
                    right: "10px", 
                    display: "flex", 
                    gap: "10px",
                    zIndex: 10,
                    backgroundColor: "rgba(255,255,255,0.9)",
                    padding: "8px",
                    borderRadius: "30px",
                    boxShadow: "0 2px 10px rgba(0,0,0,0.2)"
                }}>
                  <button 
                    onClick={() => setEditingProduct(product)}
                    title="Editar"
                    style={{ backgroundColor: "transparent", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", padding: "5px" }}
                  >
                    <i className="fa-solid fa-pen" style={{ color: "#1a1a1a", fontSize: "1.2rem" }}></i>
                  </button>
                  <button 
                    onClick={() => { if(confirm('Tem certeza que deseja excluir este produto?')) onDeleteProduct(product.id); }}
                    title="Excluir"
                    style={{ backgroundColor: "transparent", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", padding: "5px" }}
                  >
                    <i className="fa-solid fa-trash" style={{ color: "#e74c3c", fontSize: "1.2rem" }}></i>
                  </button>
                </div>
              )}
            </div>
            
            <div style={{ padding: "1.5rem", flex: 1, display: "flex", flexDirection: "column" }}>
              <h4 style={{ margin: "0 0 10px 0", fontSize: "1.1rem", color: "#1a1a1a" }}>{product.name}</h4>
              <p style={{ fontSize: "0.9rem", color: "#666", marginBottom: "1rem", flex: 1 }}>{product.description}</p>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: "auto" }}>
                <span style={{ fontSize: "1.2rem", fontWeight: "bold", color: "#d4af37" }}>R$ {product.price.toFixed(2)}</span>
                <button 
                  onClick={() => handleBuy(product)}
                  style={{
                    backgroundColor: "#1a1a1a",
                    color: "white",
                    border: "none",
                    padding: "8px 15px",
                    borderRadius: "20px",
                    cursor: "pointer",
                    fontSize: "0.9rem"
                  }}
                >
                  Comprar
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: "4rem", borderTop: "1px solid #eee", paddingTop: "2rem", display: "flex", justifyContent: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
          {showLogin ? (
             <div style={{ display: "flex", gap: "5px", alignItems: "center", backgroundColor: "#f9f9f9", padding: "5px", borderRadius: "8px", border: "1px solid #ddd" }}>
               <input 
                 type="password" 
                 value={passwordAttempt}
                 onChange={(e) => setPasswordAttempt(e.target.value)}
                 onKeyDown={(e) => e.key === 'Enter' && handleAdminLogin()}
                 placeholder="Senha admin"
                 autoFocus
                 style={{ padding: "6px", borderRadius: "4px", border: "1px solid #ccc", outline: "none", width: "100px" }}
               />
               <button 
                 onClick={handleAdminLogin}
                 style={{ backgroundColor: "#1a1a1a", color: "white", border: "none", borderRadius: "4px", padding: "6px 12px", cursor: "pointer", fontSize: "0.8rem", fontWeight: "bold" }}
               >
                 OK
               </button>
               <button 
                 onClick={() => { setShowLogin(false); setPasswordAttempt(""); }}
                 style={{ backgroundColor: "#e0e0e0", color: "#333", border: "none", borderRadius: "4px", padding: "6px 10px", cursor: "pointer", fontSize: "0.8rem" }}
               >
                 X
               </button>
             </div>
          ) : !isAdminMode ? (
            <button 
              onClick={() => setShowLogin(true)}
              style={{
                background: "transparent",
                border: "none",
                padding: "8px 15px",
                fontSize: "0.85rem",
                cursor: "pointer",
                color: "#ccc",
                transition: "all 0.2s",
                display: "flex",
                alignItems: "center",
                gap: "5px"
              }}
            >
              <i className="fa-solid fa-lock"></i> Gerenciar Loja
            </button>
          ) : (
            <button 
              onClick={handleLogout}
              style={{
                background: "#1a1a1a",
                border: "none",
                padding: "8px 15px",
                borderRadius: "20px",
                fontSize: "0.85rem",
                cursor: "pointer",
                color: "#d4af37",
                fontWeight: "bold",
                display: "flex",
                alignItems: "center",
                gap: "5px"
              }}
            >
              <i className="fa-solid fa-right-from-bracket"></i> Sair do Modo Admin
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function AIConsultant({ onBack }) {
  const [messages, setMessages] = useState<{role: 'user' | 'model', text: string}[]>([
    { role: 'model', text: 'Olá! Sou a Gabi, sua assistente virtual. Tem dúvidas sobre qual corte combina com seu rosto ou como cuidar dos seus fios? Pergunte-me!' }
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages]);

  const handleSend = async () => {
    if (!input.trim()) return;
    const userMsg = input;
    setInput("");
    setMessages(prev => [...prev, { role: 'user', text: userMsg }]);
    setLoading(true);

    try {
      const ai = new GoogleGenAI({ apiKey: API_KEY });
      // Correct usage: define model name in generateContent, pass systemInstruction in config.
      const result = await ai.models.generateContent({
        model: "gemini-2.5-flash",
        contents: [{ role: 'user', parts: [{ text: userMsg }] }],
        config: {
          systemInstruction: "Você é a Gabi, uma especialista em cabelos, visagismo e estética do Studio Gabriele Mira. Responda de forma curta, elegante, amigável e incentive a pessoa a agendar um serviço no salão se for apropriado. Use emojis com moderação.",
        }
      });
      // Correct usage: access .text property directly
      const responseText = result.text || "";
      
      setMessages(prev => [...prev, { role: 'model', text: responseText }]);
    } catch (error) {
      setMessages(prev => [...prev, { role: 'model', text: "Desculpe, tive um problema técnico momentâneo. Tente novamente." }]);
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: "600px", margin: "2rem auto", height: "calc(100vh - 150px)", display: "flex", flexDirection: "column", backgroundColor: "white", borderRadius: "15px", boxShadow: "0 10px 30px rgba(0,0,0,0.1)", overflow: "hidden" }}>
      <div style={{ padding: "1rem", backgroundColor: "#1a1a1a", color: "#d4af37", display: "flex", alignItems: "center", gap: "10px" }}>
        <button 
          onClick={onBack}
          style={{ 
            background: "transparent", 
            border: "none", 
            color: "#d4af37", 
            cursor: "pointer", 
            fontSize: "1.2rem",
            display: "flex",
            alignItems: "center"
          }}
          title="Voltar"
        >
          <i className="fa-solid fa-arrow-left"></i>
        </button>
        <i className="fa-solid fa-sparkles"></i>
        <h3 style={{ margin: 0 }}>Pergunte à Gabi</h3>
      </div>
      
      <div ref={scrollRef} style={{ flex: 1, padding: "1rem", overflowY: "auto", display: "flex", flexDirection: "column", gap: "1rem" }}>
        {messages.map((msg, idx) => (
          <div key={idx} style={{
            alignSelf: msg.role === 'user' ? 'flex-end' : 'flex-start',
            backgroundColor: msg.role === 'user' ? '#1a1a1a' : '#f0f0f0',
            color: msg.role === 'user' ? '#fff' : '#333',
            padding: "10px 15px",
            borderRadius: "10px",
            maxWidth: "80%",
            lineHeight: "1.4"
          }}>
            {msg.text}
          </div>
        ))}
        {loading && <div style={{ alignSelf: 'flex-start', color: '#888', fontStyle: 'italic' }}>Digitando...</div>}
      </div>

      <div style={{ padding: "1rem", borderTop: "1px solid #eee", display: "flex", gap: "10px" }}>
        <input 
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSend()}
          placeholder="Ex: Qual corte dá volume?"
          style={{ flex: 1, padding: "12px", borderRadius: "25px", border: "1px solid #ddd", outline: "none" }}
        />
        <button 
          onClick={handleSend}
          disabled={loading}
          style={{ backgroundColor: "#d4af37", border: "none", color: "white", width: "45px", height: "45px", borderRadius: "50%", cursor: "pointer", display: 'flex', alignItems: 'center', justifyContent: 'center' }}
        >
          <i className="fa-solid fa-paper-plane"></i>
        </button>
      </div>
    </div>
  );
}

function BookingForm({ service, onBack, showNotification }) {
  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    date: "",
    time: "",
    professional: PROFESSIONALS[0]
  });

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleWhatsAppRedirect = () => {
    if (!formData.name || !formData.date || !formData.time) {
      showNotification("Por favor, preencha todos os campos obrigatórios.", "error");
      return;
    }

    // Validate Business Hours (08:00 - 18:00)
    const [hours, minutes] = formData.time.split(':').map(Number);
    if (hours < 8 || hours > 18 || (hours === 18 && minutes > 0)) {
        showNotification("O horário de funcionamento é das 08:00 às 18:00. Por favor, escolha um horário dentro deste período.", "error");
        return;
    }

    // Validate 10-minute intervals
    if (minutes % 10 !== 0) {
      showNotification("Por favor, selecione um horário em intervalos de 10 minutos (ex: 14:10, 14:20).", "error");
      return;
    }

    const message = `Oi Gabi! Gostaria de agendar um horário.
    
*Serviço:* ${service.name} (${service.price})
*Cliente:* ${formData.name}
*Data:* ${formData.date}
*Horário:* ${formData.time}
*Profissional:* ${formData.professional}

Aguardo confirmação!`;

    const url = `https://wa.me/${SALON_PHONE_NUMBER}?text=${encodeURIComponent(message)}`;
    window.open(url, '_blank');
  };

  return (
    <div style={{ maxWidth: "500px", margin: "2rem auto", backgroundColor: "white", padding: "2rem", borderRadius: "15px", boxShadow: "0 10px 30px rgba(0,0,0,0.1)" }}>
      <button onClick={onBack} style={{ background: "none", border: "none", cursor: "pointer", color: "#666", marginBottom: "1rem" }}>
        <i className="fa-solid fa-arrow-left"></i> Voltar
      </button>
      
      <h2 style={{ color: "#1a1a1a", marginBottom: "0.5rem" }}>Agendar Horário</h2>
      <p style={{ color: "#d4af37", fontWeight: "bold", marginBottom: "1.5rem" }}>{service.name} - {service.price}</p>

      <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
        <div>
          <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold", fontSize: "0.9rem" }}>Seu Nome</label>
          <input 
            type="text" name="name" value={formData.name} onChange={handleChange} 
            placeholder="Maria Silva"
            style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box" }}
          />
        </div>

        <div>
          <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold", fontSize: "0.9rem" }}>Telefone</label>
          <input 
            type="tel" name="phone" value={formData.phone} onChange={handleChange} 
            placeholder="(11) 99999-9999"
            style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box" }}
          />
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
          <div>
            <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold", fontSize: "0.9rem" }}>Data</label>
            <input 
              type="date" name="date" value={formData.date} onChange={handleChange} 
              style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box" }}
            />
          </div>
          <div>
            <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold", fontSize: "0.9rem" }}>Hora</label>
            <input 
              type="time" 
              name="time" 
              value={formData.time} 
              onChange={handleChange}
              min="08:00"
              max="18:00"
              step="600"
              style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box" }}
            />
            <small style={{ color: "#666", fontSize: "0.8rem" }}>Funcionamento: 08h às 18h (Intervalos de 10 min)</small>
          </div>
        </div>

        <div>
          <label style={{ display: "block", marginBottom: "5px", fontWeight: "bold", fontSize: "0.9rem" }}>Profissional de Preferência</label>
          <select 
            name="professional" value={formData.professional} onChange={handleChange}
            style={{ width: "100%", padding: "10px", borderRadius: "5px", border: "1px solid #ddd", boxSizing: "border-box", backgroundColor: "white" }}
          >
            {PROFESSIONALS.map(p => <option key={p} value={p}>{p}</option>)}
          </select>
        </div>

        <button 
          onClick={handleWhatsAppRedirect}
          style={{
            marginTop: "1rem",
            backgroundColor: "#25D366", // WhatsApp Green
            color: "white",
            border: "none",
            padding: "15px",
            borderRadius: "50px",
            fontSize: "1rem",
            fontWeight: "bold",
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: "10px",
            boxShadow: "0 4px 10px rgba(37, 211, 102, 0.3)"
          }}
        >
          <i className="fa-brands fa-whatsapp" style={{ fontSize: "1.2rem" }}></i> Confirmar via WhatsApp
        </button>
        <p style={{ fontSize: "0.8rem", color: "#888", textAlign: "center", marginTop: "5px" }}>
          Você será redirecionado para enviar a mensagem de confirmação.
        </p>
      </div>
    </div>
  );
}

function Footer() {
  return (
    <footer style={{ backgroundColor: "#1a1a1a", color: "white", padding: "2rem", textAlign: "center", marginTop: "auto" }}>
      <h3 style={{ fontFamily: "Playfair Display", color: "#d4af37" }}>Studio Gabriele Mira</h3>
      <p style={{ fontSize: "0.9rem", color: "#aaa" }}>Av. José Pereira da Cruz, 297 - Jardim do Vale.</p>
      <div style={{ margin: "1rem 0", display: "flex", justifyContent: "center", gap: "15px" }}>
        <i className="fa-brands fa-instagram" style={{ cursor: "pointer", fontSize: "1.2rem" }}></i>
        <i className="fa-brands fa-facebook" style={{ cursor: "pointer", fontSize: "1.2rem" }}></i>
        <i className="fa-brands fa-tiktok" style={{ cursor: "pointer", fontSize: "1.2rem" }}></i>
      </div>
      <p style={{ fontSize: "0.8rem", color: "#555" }}>&copy; 2025 Gabriele Mira. All rights reserved.</p>
    </footer>
  );
}

// --- Main App Component ---

function App() {
  const [currentView, setCurrentView] = useState("home"); // home, booking, ai-consultant, store
  const [selectedService, setSelectedService] = useState<Service | null>(null);
  const [products, setProducts] = useState<Product[]>(INITIAL_PRODUCTS);
  const [notification, setNotification] = useState<{message: string, type: 'error' | 'success'} | null>(null);

  const showNotification = (message: string, type: 'error' | 'success' = 'error') => {
    setNotification({ message, type });
  };

  const handleSelectService = (service: Service) => {
    setSelectedService(service);
    setCurrentView("booking");
  };

  const handleAddProduct = (newProduct: Product) => {
    setProducts([...products, newProduct]);
  };

  const handleEditProduct = (updatedProduct: Product) => {
    setProducts(products.map(p => p.id === updatedProduct.id ? updatedProduct : p));
  };

  const handleDeleteProduct = (productId: string) => {
    setProducts(products.filter(p => p.id !== productId));
  };

  const renderContent = () => {
    if (currentView === "booking" && selectedService) {
      return (
        <BookingForm 
          service={selectedService} 
          onBack={() => setCurrentView("home")}
          showNotification={showNotification}
        />
      );
    }
    
    if (currentView === "ai-consultant") {
      return <AIConsultant onBack={() => setCurrentView("home")} />;
    }

    if (currentView === "store") {
      return (
        <Store 
          products={products}
          onAddProduct={handleAddProduct}
          onEditProduct={handleEditProduct}
          onDeleteProduct={handleDeleteProduct}
          onBack={() => setCurrentView("home")}
          showNotification={showNotification}
        />
      );
    }

    // Default to home (also handles 'booking' without selectedService fallback case implicitly)
    return (
      <>
        <Hero onBookNow={() => {
            const element = document.getElementById('services-section');
            element?.scrollIntoView({ behavior: 'smooth' });
        }} />
        <div id="services-section">
          <ServiceList onSelectService={handleSelectService} />
        </div>
      </>
    );
  };

  return (
    <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}>
      <Header setView={setCurrentView} currentView={currentView} />
      {notification && (
        <Notification 
          message={notification.message} 
          type={notification.type} 
          onClose={() => setNotification(null)} 
        />
      )}
      <main style={{ flex: 1 }}>
        {renderContent()}
      </main>
      <Footer />
    </div>
  );
}

const root = createRoot(document.getElementById("root")!);
root.render(<App />);