// AI Event Builder — calls Claude API with event params + product catalog (light theme)

const EVENT_TYPES = [
  { id: "asado", label: "Asado/Parrilla", icon: "🔥" },
  { id: "cumple", label: "Cumpleaños", icon: "🎂" },
  { id: "reunion", label: "Reunión familiar", icon: "👨‍👩‍👧" },
  { id: "finde", label: "Fin de semana", icon: "🌤️" },
  { id: "empresa", label: "Evento empresa", icon: "🏢" },
];

const TIMES_OF_DAY = [
  { id: "mediodia", label: "Mediodía" },
  { id: "tarde", label: "Tarde" },
  { id: "noche", label: "Noche" },
];

function AIEventBuilder({ products, onAddToCart, onClose, onOpenCart }) {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    eventType: "asado",
    adults: 0,
    kids: 0,
    timeOfDay: "noche",
    extras: "",
  });
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);

  const handleChange = (key, val) => setForm(f => ({ ...f, [key]: val }));

  const buildPrompt = () => {
    const catalog = products.map(p =>
      `- ID:${p.id} | ${p.name} | $${p.price} | cat:${p.category} | combo:${p.is_combo}`
    ).join("\n");

    return `Sos el asistente de ventas de "Hamburguesas La Plata Rafaela" (HLPRaf), una tienda de productos congelados en Rafaela, Argentina. Hablás en argentino, con tono amigable, cercano y respetuoso (vos, no tú). No uses signos de apertura ¡ ni ¿. PROHIBIDO usar las palabras: "colegas", "boludo", "pelotudo", "che boludo", "loco", ni groserías o palabras ofensivas. Lenguaje claro y cercano pero nunca desubicado.

CATÁLOGO DISPONIBLE:
${catalog}

EVENTO DEL CLIENTE:
- Tipo de evento: ${EVENT_TYPES.find(e => e.id === form.eventType)?.label}
- Adultos: ${form.adults}
- Niños: ${form.kids}
- Momento: ${TIMES_OF_DAY.find(t => t.id === form.timeOfDay)?.label}
${form.extras ? `- Pedido especial: ${form.extras}` : ""}

INSTRUCCIONES:
1. Armá 2 combos/sugerencias para este evento. Priorizá productos con mayor margen (combos, hamburguesas premium, bebidas).
2. Cada sugerencia debe incluir: nombre del combo, lista de productos con IDs y cantidades, precio total estimado, y una frase de venta corta en argentino.
3. Sé conciso. Respondé SOLO en JSON con este formato exacto:
{
  "suggestions": [
    {
      "name": "Nombre del combo",
      "tagline": "Frase corta de venta",
      "items": [{"id": "p01", "qty": 2, "name": "Producto", "price": 48000}],
      "total": 96000
    }
  ],
  "tip": "Un consejo breve en argentino para el evento"
}`;
  };

  const handleGenerate = async () => {
    setStep(2);
    setError(null);
    try {
      const prompt = buildPrompt();
      const raw = await window.claude.complete({
        messages: [{ role: "user", content: prompt }]
      });
      const jsonMatch = raw.match(/\{[\s\S]*\}/);
      if (!jsonMatch) throw new Error("Respuesta inválida");
      const parsed = JSON.parse(jsonMatch[0]);
      setResult(parsed);
      setStep(3);
    } catch (e) {
      setError("No pudimos generar sugerencias. Intentá de nuevo.");
      setStep(1);
    }
  };

  const handleAddSuggestion = (suggestion) => {
    suggestion.items.forEach(item => {
      const product = products.find(p => p.id === item.id);
      if (product) {
        for (let i = 0; i < item.qty; i++) onAddToCart(product.id);
      }
    });
    onClose();
    if (typeof onOpenCart === "function") onOpenCart();
  };

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(40,25,10,0.5)", zIndex: 400, display: "flex", alignItems: "flex-end", justifyContent: "center", backdropFilter: "blur(6px)" }}
      onClick={onClose}>
      <div style={{
        background: "#fdfaf3", borderRadius: "22px 22px 0 0",
        padding: "24px 20px 32px", width: "100%", maxWidth: 520,
        maxHeight: "90vh", overflowY: "auto",
        boxShadow: "0 -8px 40px rgba(26,16,8,0.25)"
      }} onClick={e => e.stopPropagation()}>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
          <div>
            <h2 style={{ color: "#1a1008", fontFamily: "'Bebas Neue', cursive", fontSize: 24, letterSpacing: "0.05em", margin: 0, display: "flex", alignItems: "center", gap: 8 }}>
              <img src="assets/ia-logo.png" alt="IA" style={{ width: 30, height: 30, objectFit: "contain" }} /> Armador de Evento con IA
            </h2>
            <p style={{ color: "#8a7a66", fontSize: 12, fontFamily: "'DM Sans', sans-serif", margin: "4px 0 0" }}>
              Contanos tu evento y armamos el pedido ideal
            </p>
          </div>
          <button onClick={onClose} style={{
            background: "#f5ede1", border: "none", color: "#6b5d4e",
            borderRadius: "50%", width: 32, height: 32, cursor: "pointer", fontSize: 14,
            display: "flex", alignItems: "center", justifyContent: "center"
          }}>✕</button>
        </div>

        {step === 1 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div>
              <label style={labelStyle}>Qué tipo de evento</label>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 8 }}>
                {EVENT_TYPES.map(et => (
                  <button key={et.id} onClick={() => handleChange("eventType", et.id)} style={{
                    background: form.eventType === et.id ? "#d97706" : "#fff",
                    color: form.eventType === et.id ? "#fff" : "#1a1008",
                    border: form.eventType === et.id ? "1px solid #d97706" : "1px solid #e8dcc8",
                    borderRadius: 30, padding: "7px 14px",
                    fontSize: 13, fontWeight: 700, cursor: "pointer",
                    fontFamily: "'DM Sans', sans-serif", transition: "all 0.15s"
                  }}>
                    {et.icon} {et.label}
                  </button>
                ))}
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div>
                <label style={labelStyle}>Adultos 👥</label>
                <div style={numberInputWrapper}>
                  <button onClick={() => handleChange("adults", Math.max(0, form.adults - 1))} style={numBtnStyle}>−</button>
                  <span style={{ color: "#1a1008", fontWeight: 700, fontSize: 18, minWidth: 32, textAlign: "center" }}>{form.adults}</span>
                  <button onClick={() => handleChange("adults", form.adults + 1)} style={numBtnStyle}>+</button>
                </div>
              </div>
              <div>
                <label style={labelStyle}>Niños 👶</label>
                <div style={numberInputWrapper}>
                  <button onClick={() => handleChange("kids", Math.max(0, form.kids - 1))} style={numBtnStyle}>−</button>
                  <span style={{ color: "#1a1008", fontWeight: 700, fontSize: 18, minWidth: 32, textAlign: "center" }}>{form.kids}</span>
                  <button onClick={() => handleChange("kids", form.kids + 1)} style={numBtnStyle}>+</button>
                </div>
              </div>
            </div>

            <div>
              <label style={labelStyle}>A qué hora</label>
              <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                {TIMES_OF_DAY.map(t => (
                  <button key={t.id} onClick={() => handleChange("timeOfDay", t.id)} style={{
                    flex: 1, background: form.timeOfDay === t.id ? "#d97706" : "#fff",
                    color: form.timeOfDay === t.id ? "#fff" : "#1a1008",
                    border: form.timeOfDay === t.id ? "1px solid #d97706" : "1px solid #e8dcc8",
                    borderRadius: 10, padding: "10px 0",
                    fontSize: 13, fontWeight: 700, cursor: "pointer",
                    fontFamily: "'DM Sans', sans-serif", transition: "all 0.15s"
                  }}>{t.label}</button>
                ))}
              </div>
            </div>

            <div>
              <label style={labelStyle}>Algo especial que necesitás</label>
              <input
                value={form.extras}
                onChange={e => handleChange("extras", e.target.value)}
                placeholder="Ej: vegetarianos, sin alcohol, mucho carbón..."
                style={{ ...aiInputStyle, marginTop: 8 }}
              />
            </div>

            <button onClick={handleGenerate} style={{
              background: "linear-gradient(135deg, #d97706, #b91c1c)",
              color: "#fff", border: "none", borderRadius: 14,
              padding: "15px 0", fontWeight: 800, fontSize: 16,
              cursor: "pointer", fontFamily: "'DM Sans', sans-serif",
              boxShadow: "0 4px 16px rgba(217,119,6,0.3)", marginTop: 4
            }}>
              <img src="assets/ia-logo.png" alt="" style={{ width: 22, height: 22, objectFit: "contain", verticalAlign: "middle", marginRight: 6 }} /> Generar sugerencia con IA →
            </button>
          </div>
        )}

        {step === 2 && (
          <div style={{ textAlign: "center", padding: "48px 0" }}>
            <div style={{ marginBottom: 16, animation: "spin 1.5s linear infinite", display: "inline-block" }}><img src="assets/ia-logo.png" alt="" style={{ width: 60, height: 60, objectFit: "contain" }} /></div>
            <p style={{ color: "#1a1008", fontFamily: "'DM Sans', sans-serif", fontSize: 16, fontWeight: 600 }}>
              Armando tu pedido ideal...
            </p>
            <p style={{ color: "#8a7a66", fontFamily: "'DM Sans', sans-serif", fontSize: 13, marginTop: 6 }}>
              La IA está pensando en tu evento
            </p>
          </div>
        )}

        {step === 3 && result && (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {result.tip && (
              <div style={{
                background: "#fef3c7", borderRadius: 12, padding: "12px 14px",
                border: "1px solid #fcd34d"
              }}>
                <span style={{ fontSize: 16 }}>💡 </span>
                <span style={{ color: "#78350f", fontSize: 13, fontFamily: "'DM Sans', sans-serif" }}>{result.tip}</span>
              </div>
            )}

            {result.suggestions && result.suggestions.map((sug, idx) => (
              <div key={idx} style={{
                background: "#fff", borderRadius: 16,
                overflow: "hidden", border: "1px solid #e8dcc8",
                boxShadow: "0 2px 8px rgba(60,40,20,0.06)"
              }}>
                <div style={{
                  background: idx === 0 ? "linear-gradient(135deg, #fde4d3, #fad9d4)" : "#f5ede1",
                  padding: "14px 16px", borderBottom: "1px solid #e8dcc8"
                }}>
                  <div style={{ color: "#b91c1c", fontFamily: "'Bebas Neue', cursive", fontSize: 22, letterSpacing: "0.04em" }}>
                    {idx === 0 ? "⭐ " : "🔹 "}{sug.name}
                  </div>
                  <div style={{ color: "#6b5d4e", fontFamily: "'DM Sans', sans-serif", fontSize: 13, marginTop: 2 }}>
                    {sug.tagline}
                  </div>
                </div>
                <div style={{ padding: "12px 16px" }}>
                  {sug.items && sug.items.map((item, i) => (
                    <div key={i} style={{
                      display: "flex", justifyContent: "space-between",
                      fontSize: 13, fontFamily: "'DM Sans', sans-serif",
                      color: "#1a1008", padding: "5px 0",
                      borderBottom: i < sug.items.length - 1 ? "1px solid #f5ede1" : "none"
                    }}>
                      <span>{item.qty}× {item.name}</span>
                      <span style={{ color: "#8a7a66" }}>${(item.price * item.qty).toLocaleString("es-AR")}</span>
                    </div>
                  ))}
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12 }}>
                    <div>
                      <div style={{ color: "#8a7a66", fontSize: 11, fontFamily: "'DM Sans', sans-serif" }}>Total estimado</div>
                      <div style={{ color: "#d97706", fontFamily: "'Bebas Neue', cursive", fontSize: 26, letterSpacing: "0.04em" }}>
                        ${sug.total.toLocaleString("es-AR")}
                      </div>
                    </div>
                    <button onClick={() => handleAddSuggestion(sug)} style={{
                      background: "#d97706", color: "#fff",
                      border: "none", borderRadius: 30, padding: "10px 20px",
                      fontWeight: 800, fontSize: 13, cursor: "pointer",
                      fontFamily: "'DM Sans', sans-serif"
                    }}>Agregar al carrito →</button>
                  </div>
                </div>
              </div>
            ))}

            <button onClick={() => setStep(1)} style={{
              background: "#f5ede1", color: "#6b5d4e",
              border: "1px solid #e8dcc8", borderRadius: 10, padding: "12px 0",
              fontFamily: "'DM Sans', sans-serif", fontSize: 13, cursor: "pointer"
            }}>← Modificar evento</button>
          </div>
        )}

        {error && (
          <div style={{ color: "#b91c1c", fontFamily: "'DM Sans', sans-serif", fontSize: 14, textAlign: "center", marginTop: 12 }}>
            {error}
          </div>
        )}
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

const labelStyle = {
  color: "#6b5d4e", fontSize: 12, fontWeight: 600,
  fontFamily: "'DM Sans', sans-serif", textTransform: "uppercase", letterSpacing: "0.06em"
};
const numberInputWrapper = {
  display: "flex", alignItems: "center", justifyContent: "space-between",
  background: "#fff", border: "1px solid #e8dcc8",
  borderRadius: 12, padding: "8px 14px", marginTop: 8
};
const numBtnStyle = {
  background: "none", border: "none", color: "#1a1008",
  fontSize: 22, cursor: "pointer", padding: "0 4px", fontWeight: 700
};
const aiInputStyle = {
  background: "#fff", border: "1px solid #e8dcc8",
  borderRadius: 12, padding: "12px 14px", color: "#1a1008",
  fontSize: 14, fontFamily: "'DM Sans', sans-serif", outline: "none",
  width: "100%", boxSizing: "border-box"
};

Object.assign(window, { AIEventBuilder });
