// Lavadero Curupí — WhatsApp bot demo (interactive)

const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;

const WA_BG = '#0b141a';
const WA_BG_LIGHT = '#efeae2';
const WA_GREEN = '#005c4b';
const WA_GREEN_LIGHT = '#d9fdd3';

// Conversation script (state machine)
const FLOWS = {
  start: {
    bot: ["¡Hola! 👋 Soy *Curu*, el asistente del Lavadero Curupí.", "¿En qué te puedo ayudar?"],
    options: [
      { label: "📅 Reservar turno", next: "askBrand" },
      { label: "💰 Ver precios", next: "showPricing" },
      { label: "📍 Ubicación y horarios", next: "showInfo" },
      { label: "💬 Hablar con una persona", next: "human" },
    ],
  },
  askBrand: {
    bot: ["¡Genial! Vamos a agendar tu turno. 🚗", "¿Qué marca es tu auto?"],
    options: LC_DATA.cars.slice(0, 6).map(c => ({ label: c.brand, next: "askModel", payload: { brand: c.brand } })),
    extraOptions: [{ label: "Ver más marcas...", next: "askBrandMore" }],
  },
  askBrandMore: {
    bot: ["Marcas disponibles:"],
    options: LC_DATA.cars.slice(6).map(c => ({ label: c.brand, next: "askModel", payload: { brand: c.brand } })),
  },
  askModel: {
    bot: (s) => [`Perfecto, ${s.brand}. ¿Qué modelo?`],
    options: (s) => {
      const brand = LC_DATA.cars.find(c => c.brand === s.brand);
      return brand.models.map(m => ({ label: m, next: "askService", payload: { model: m } }));
    },
  },
  askService: {
    bot: (s) => {
      const sz = LC_DATA.sizes.find(z => z.id === LC_DATA.modelSize[s.model]);
      return [
        `Listo: *${s.brand} ${s.model}* (categoría ${sz.label.toLowerCase()}). 👌`,
        "¿Qué servicio quieres hacerle?",
      ];
    },
    options: (s) => {
      const sz = LC_DATA.sizes.find(z => z.id === LC_DATA.modelSize[s.model]);
      return LC_DATA.services.map(svc => ({
        label: `${svc.name} · $${Math.round(svc.price * sz.mult).toLocaleString('es-UY')}`,
        next: "askDate",
        payload: { serviceId: svc.id },
      }));
    },
  },
  askDate: {
    bot: (s) => {
      const svc = LC_DATA.services.find(x => x.id === s.serviceId);
      return [
        `🌟 *${svc.name}* anotado. ${svc.tagline}`,
        "¿Para cuándo lo quieres?",
      ];
    },
    options: [
      { label: "📅 Hoy", next: "askTime", payload: { dateLabel: "hoy" } },
      { label: "📅 Mañana", next: "askTime", payload: { dateLabel: "mañana" } },
      { label: "📅 Pasado mañana", next: "askTime", payload: { dateLabel: "pasado mañana" } },
      { label: "Elegir otro día", next: "askTime", payload: { dateLabel: "el lunes" } },
    ],
  },
  askTime: {
    bot: (s) => [`Para ${s.dateLabel}. ¿Mañana o tarde?`],
    options: [
      { label: "🌅 Mañana (8 a 12)", next: "showSlots", payload: { period: "mañana" } },
      { label: "🌇 Tarde (14 a 19)", next: "showSlots", payload: { period: "tarde" } },
    ],
  },
  showSlots: {
    bot: (s) => [`Estos son los cupos libres para ${s.dateLabel} a la ${s.period}:`],
    options: (s) => {
      const slots = s.period === 'mañana' ? ['08:00', '09:30', '11:00'] : ['14:45', '16:15', '17:00', '18:30'];
      return slots.map(t => ({ label: `🕐 ${t} hs`, next: "askName", payload: { time: t } }));
    },
  },
  askName: {
    bot: ["¡Reservado provisoriamente! 🔒", "Para terminar necesito tu *nombre y apellido*:"],
    input: { type: "text", placeholder: "Andrés Pereyra", field: "name", next: "confirm" },
  },
  confirm: {
    bot: (s) => {
      const svc = LC_DATA.services.find(x => x.id === s.serviceId);
      const sz = LC_DATA.sizes.find(z => z.id === LC_DATA.modelSize[s.model]);
      const price = Math.round(svc.price * sz.mult);
      return [
        `Listo ${s.name.split(' ')[0]}, te resumo:`,
        `\n🚗 *Vehículo:* ${s.brand} ${s.model}\n✨ *Servicio:* ${svc.name}\n📅 *Cuándo:* ${s.dateLabel} a las ${s.time}\n💰 *Total:* $${price.toLocaleString('es-UY')} UYU\n📍 Nicolás Corbo 1325 esq. Sarandí, Lascano`,
        "¿Confirmamos?",
      ];
    },
    options: [
      { label: "✅ Sí, confirmar", next: "done" },
      { label: "❌ Cancelar", next: "start" },
    ],
  },
  done: {
    bot: (s) => [
      `🎉 ¡Reserva confirmada, ${s.name.split(' ')[0]}!`,
      `Te enviamos un recordatorio el día anterior. Si necesitas cambiar algo, escríbenos aquí. ¡Te esperamos! 🚗💨`,
      "_— Curu, el bot del Lavadero Curupí_",
    ],
    options: [
      { label: "🔄 Empezar de nuevo", next: "start" },
    ],
  },
  showPricing: {
    bot: ["Te paso los precios base (auto chico/mediano):"],
    options: () => LC_DATA.services.map(s => ({
      label: `${s.name} · desde $${s.price.toLocaleString('es-UY')}`,
      next: "pricingChosen",
      payload: { serviceId: s.id },
    })),
    extraOptions: [{ label: "↩️ Menú principal", next: "start" }],
  },
  pricingChosen: {
    bot: (s) => {
      const svc = LC_DATA.services.find(x => x.id === s.serviceId);
      return [`*${svc.name}* — $${svc.price.toLocaleString('es-UY')} UYU\n${svc.desc}\nDura ~${svc.duration} min.`];
    },
    options: [
      { label: "📅 Reservar este", next: "askBrand" },
      { label: "↩️ Volver al menú", next: "start" },
    ],
  },
  showInfo: {
    bot: [
      "📍 *Nicolás Corbo 1325 esq. Sarandí, Lascano*",
      "🕐 *Horarios:*\nLun a Vie · 9:00 a 18:00\nSáb y Dom cerrado",
      "📞 *Teléfono:* 092 211 407",
    ],
    options: [
      { label: "📅 Reservar turno", next: "askBrand" },
      { label: "↩️ Menú principal", next: "start" },
    ],
  },
  human: {
    bot: [
      "Te derivo con Diego del equipo 🙋‍♂️",
      "Te responde en unos minutos. Mientras, ¿quieres que te agendemos un turno?",
    ],
    options: [
      { label: "📅 Sí, reservar turno", next: "askBrand" },
      { label: "↩️ Volver al menú", next: "start" },
    ],
  },
};

function WABot({ open, onClose }) {
  const [messages, setMessages] = useStateW([]);
  const [state, setState] = useStateW({ flow: 'start' });
  const [typing, setTyping] = useStateW(false);
  const [inputValue, setInputValue] = useStateW('');
  const scrollRef = useRefW(null);
  const initRef = useRefW(false);

  // initial message
  useEffectW(() => {
    if (!open) {
      // reset on close
      setMessages([]);
      setState({ flow: 'start' });
      initRef.current = false;
      return;
    }
    if (!initRef.current) {
      initRef.current = true;
      setTimeout(() => runFlow('start', {}), 400);
    }
  }, [open]);

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

  const addMessage = (msg) => {
    setMessages(m => [...m, { ...msg, id: Date.now() + Math.random(), time: now() }]);
  };

  const now = () => {
    const d = new Date();
    return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
  };

  const runFlow = async (flowId, mergedState) => {
    const flow = FLOWS[flowId];
    if (!flow) return;
    const newState = { ...mergedState, flow: flowId };
    setState(newState);

    const botMessages = typeof flow.bot === 'function' ? flow.bot(newState) : flow.bot;
    for (let i = 0; i < botMessages.length; i++) {
      setTyping(true);
      await sleep(700 + botMessages[i].length * 8);
      setTyping(false);
      addMessage({ from: 'bot', text: botMessages[i] });
      await sleep(200);
    }

    // options or input come from current state
  };

  const sleep = (ms) => new Promise(r => setTimeout(r, ms));

  const handleOption = async (opt) => {
    addMessage({ from: 'user', text: opt.label });
    const newState = { ...state, ...(opt.payload || {}) };
    await sleep(400);
    runFlow(opt.next, newState);
  };

  const handleInputSubmit = async () => {
    const flow = FLOWS[state.flow];
    if (!flow.input || !inputValue.trim()) return;
    const val = inputValue.trim();
    setInputValue('');
    addMessage({ from: 'user', text: val });
    const newState = { ...state, [flow.input.field]: val };
    await sleep(400);
    runFlow(flow.input.next, newState);
  };

  const currentFlow = FLOWS[state.flow];
  const showOptions = currentFlow && !typing && currentFlow.options && messages.length > 0 && messages[messages.length - 1].from === 'bot';
  const options = showOptions ? (typeof currentFlow.options === 'function' ? currentFlow.options(state) : currentFlow.options) : null;
  const extraOptions = showOptions && currentFlow.extraOptions ? currentFlow.extraOptions : null;
  const showInput = currentFlow && !typing && currentFlow.input && messages.length > 0 && messages[messages.length - 1].from === 'bot';

  if (!open) return null;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20,
      animation: 'lc-fade-up .3s ease-out',
    }}>
      <div onClick={e => e.stopPropagation()} style={{ display: 'flex', alignItems: 'center', gap: 32 }} className="bot-modal">
        {/* Phone frame */}
        <div style={{
          width: 360, height: 720,
          background: '#000', borderRadius: 56,
          padding: 12, position: 'relative',
          boxShadow: '0 50px 120px -30px rgba(0,0,0,0.8), 0 0 0 1px rgba(255,255,255,0.05) inset',
        }}>
          {/* Notch */}
          <div style={{
            position: 'absolute', top: 14, left: '50%', transform: 'translateX(-50%)',
            width: 110, height: 30, background: '#000', borderRadius: 999, zIndex: 5,
          }} />

          <div style={{
            background: WA_BG, height: '100%', borderRadius: 46,
            overflow: 'hidden', position: 'relative',
            display: 'flex', flexDirection: 'column',
          }}>
            {/* Status bar */}
            <div style={{
              padding: '14px 30px 6px', display: 'flex', justifyContent: 'space-between',
              color: 'white', fontSize: 13, fontWeight: 600,
            }}>
              <span>9:41</span>
              <span style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                <span style={{ fontSize: 10 }}>●●●●</span>
                <span style={{ fontSize: 10 }}>📶</span>
                <span style={{ width: 22, height: 11, border: '1px solid white', borderRadius: 2, position: 'relative' }}>
                  <span style={{ position: 'absolute', inset: 1, background: 'white', width: '70%', borderRadius: 1 }} />
                </span>
              </span>
            </div>

            {/* WA Header */}
            <div style={{
              background: '#202c33', padding: '8px 14px',
              display: 'flex', alignItems: 'center', gap: 12,
              borderBottom: '1px solid rgba(255,255,255,0.05)',
            }}>
              <LCIcons.ArrowLeft size={20} style={{ color: 'white' }} />
              <div style={{
                width: 36, height: 36, borderRadius: 999,
                background: 'oklch(0.82 0.18 145)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#061008" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 3c-3 4-5 7-5 11a5 5 0 0 0 10 0c0-4-2-7-5-11z"/>
                  <path d="M12 14v6" />
                </svg>
              </div>
              <div style={{ flex: 1, color: 'white' }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>Lavadero Curupí</div>
                <div style={{ fontSize: 11, opacity: 0.7 }}>
                  {typing ? 'escribiendo...' : 'bot activo · responde 24/7'}
                </div>
              </div>
              <span style={{ color: 'white', opacity: 0.8 }}>📞</span>
            </div>

            {/* Chat area */}
            <div ref={scrollRef} style={{
              flex: 1, overflowY: 'auto',
              padding: '16px 12px',
              backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='80'><circle cx='10' cy='10' r='1' fill='%23ffffff08'/><circle cx='40' cy='40' r='1' fill='%23ffffff08'/></svg>")`,
              backgroundColor: WA_BG,
            }}>
              <DateChip text="HOY" />
              <SystemMessage text="🔒 Los mensajes están cifrados de extremo a extremo. Conectado con el bot Curu." />

              {messages.map(m => (
                <Bubble key={m.id} msg={m} />
              ))}

              {typing && <TypingBubble />}

              {/* Quick options */}
              {showOptions && options && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 8, animation: 'lc-fade-up .25s ease' }}>
                  {options.map((opt, i) => (
                    <button key={i} onClick={() => handleOption(opt)}
                      style={{
                        background: '#1f2c34', color: '#53bdeb',
                        border: '1px solid rgba(255,255,255,0.05)', borderRadius: 8,
                        padding: '10px 14px', fontSize: 13, fontWeight: 500,
                        textAlign: 'left', transition: 'background .15s',
                      }}
                      onMouseEnter={e => e.target.style.background = '#26343d'}
                      onMouseLeave={e => e.target.style.background = '#1f2c34'}>
                      {opt.label}
                    </button>
                  ))}
                  {extraOptions && extraOptions.map((opt, i) => (
                    <button key={`e${i}`} onClick={() => handleOption(opt)}
                      style={{
                        background: 'transparent', color: '#8696a0',
                        border: '1px dashed rgba(255,255,255,0.1)', borderRadius: 8,
                        padding: '8px 14px', fontSize: 12,
                        textAlign: 'left',
                      }}>
                      {opt.label}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Input */}
            <div style={{
              background: '#1f2c34', padding: '8px 10px',
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <span style={{ color: '#8696a0', fontSize: 20 }}>😊</span>
              <input
                type="text"
                value={inputValue}
                onChange={e => setInputValue(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && handleInputSubmit()}
                placeholder={showInput ? (currentFlow.input.placeholder) : "Mensaje"}
                style={{
                  flex: 1, background: '#2a3942', color: 'white',
                  border: 'none', borderRadius: 999, padding: '10px 16px',
                  fontSize: 14, outline: 'none',
                }}
              />
              {inputValue ? (
                <button onClick={handleInputSubmit} style={{
                  background: 'oklch(0.82 0.18 145)', color: '#061008', border: 'none',
                  width: 38, height: 38, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <LCIcons.Send size={16} />
                </button>
              ) : (
                <span style={{ color: '#8696a0', fontSize: 20 }}>🎤</span>
              )}
            </div>

            {/* Home indicator */}
            <div style={{ display: 'flex', justifyContent: 'center', padding: 6 }}>
              <div style={{ width: 130, height: 4, background: 'rgba(255,255,255,0.4)', borderRadius: 999 }} />
            </div>
          </div>
        </div>

        {/* Side panel - explainer */}
        <div className="bot-explainer" style={{
          maxWidth: 320, color: 'var(--text)',
          padding: 24,
        }}>
          <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ marginBottom: 24 }}>
            <LCIcons.Close size={14} /> Cerrar demo
          </button>

          <span className="eyebrow">DEMO INTERACTIVA</span>
          <h2 style={{ fontSize: 32, marginTop: 12, marginBottom: 16 }}>
            Conoce a <span style={{ color: 'var(--accent)', fontStyle: 'italic' }}>Curu</span>, nuestro bot.
          </h2>
          <p style={{ color: 'var(--text-muted)', fontSize: 15, marginBottom: 24 }}>
            Toca las opciones del chat para vivir el flujo real. Funciona 24h y reserva turnos sin que hagas una llamada.
          </p>

          <div className="col gap-2" style={{ fontSize: 13 }}>
            {[
              ['🤖', 'Responde al instante, día y noche'],
              ['📅', 'Muestra cupos en tiempo real'],
              ['💬', 'Si te traba, te deriva a una persona'],
              ['🔔', 'Manda recordatorio el día anterior'],
            ].map(([icon, txt], i) => (
              <div key={i} className="row gap-2" style={{ alignItems: 'flex-start' }}>
                <span style={{ fontSize: 18, lineHeight: 1 }}>{icon}</span>
                <span style={{ color: 'var(--text-muted)' }}>{txt}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 760px) {
          .bot-explainer { display: none !important; }
        }
      `}</style>
    </div>
  );
}

function Bubble({ msg }) {
  const isBot = msg.from === 'bot';
  return (
    <div style={{
      display: 'flex',
      justifyContent: isBot ? 'flex-start' : 'flex-end',
      marginBottom: 4,
      animation: 'lc-fade-up .2s ease',
    }}>
      <div style={{
        maxWidth: '82%',
        background: isBot ? '#202c33' : WA_GREEN,
        color: 'white',
        padding: '6px 10px',
        borderRadius: 8,
        borderTopLeftRadius: isBot ? 2 : 8,
        borderTopRightRadius: isBot ? 8 : 2,
        fontSize: 13.5,
        lineHeight: 1.4,
        boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
        whiteSpace: 'pre-wrap',
      }}>
        <FormattedText text={msg.text} />
        <div style={{ fontSize: 10, opacity: 0.6, textAlign: 'right', marginTop: 2 }}>
          {msg.time} {!isBot && '✓✓'}
        </div>
      </div>
    </div>
  );
}

function FormattedText({ text }) {
  // Parse *bold* and _italic_
  const parts = [];
  let i = 0;
  let buf = '';
  while (i < text.length) {
    if (text[i] === '*') {
      if (buf) { parts.push(buf); buf = ''; }
      const end = text.indexOf('*', i + 1);
      if (end > -1) {
        parts.push(<strong key={i}>{text.slice(i + 1, end)}</strong>);
        i = end + 1;
        continue;
      }
    }
    if (text[i] === '_' && (i === 0 || text[i-1] === ' ' || text[i-1] === '\n')) {
      const end = text.indexOf('_', i + 1);
      if (end > -1) {
        if (buf) { parts.push(buf); buf = ''; }
        parts.push(<em key={i} style={{ opacity: 0.85 }}>{text.slice(i + 1, end)}</em>);
        i = end + 1;
        continue;
      }
    }
    buf += text[i];
    i++;
  }
  if (buf) parts.push(buf);
  return <>{parts}</>;
}

function TypingBubble() {
  return (
    <div style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 4 }}>
      <div style={{
        background: '#202c33', padding: '10px 14px', borderRadius: 8,
        borderTopLeftRadius: 2, display: 'flex', gap: 4,
      }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{
            width: 6, height: 6, borderRadius: 999, background: '#8696a0',
            animation: `lc-typing-dot 1.4s ${i * 0.2}s infinite`,
          }} />
        ))}
        <style>{`
          @keyframes lc-typing-dot {
            0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
            30% { opacity: 1; transform: translateY(-3px); }
          }
        `}</style>
      </div>
    </div>
  );
}

function DateChip({ text }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', margin: '8px 0' }}>
      <span style={{
        background: 'rgba(30, 42, 50, 0.85)', color: '#8696a0',
        padding: '4px 12px', borderRadius: 8, fontSize: 11, fontWeight: 500,
      }}>
        {text}
      </span>
    </div>
  );
}

function SystemMessage({ text }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', margin: '4px 0 12px' }}>
      <span style={{
        background: 'rgba(30, 42, 50, 0.85)', color: '#8696a0',
        padding: '6px 14px', borderRadius: 8, fontSize: 11, textAlign: 'center', maxWidth: '85%',
      }}>
        {text}
      </span>
    </div>
  );
}

window.WABot = WABot;
