/* global React, Icon */
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

/* ----------------------------------------------------------
   WAChat — scripted WhatsApp-style conversation player
   script: [{ from: 'client'|'system', text, delay }]
   Plays sequentially with typing indicator before system msgs.
   Loops after a pause. Pauses when off-screen.
---------------------------------------------------------- */
function WAChat({ title = "Negocio", subtitle = "en línea", script = [], height = 360, compact = false, statusBar = false, fill = false }) {
  const [shown, setShown] = useStateC(0);     // number of fully-shown messages
  const [typing, setTyping] = useStateC(false);
  const [active, setActive] = useStateC(false);
  const wrapRef = useRefC(null);
  const bodyRef = useRefC(null);
  const timers = useRefC([]);

  // observe visibility
  useEffectC(() => {
    const el = wrapRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (es) => es.forEach((e) => setActive(e.isIntersecting)),
      { threshold: 0.25 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  useEffectC(() => {
    if (!active) return;
    let cancelled = false;
    const clearAll = () => { timers.current.forEach(clearTimeout); timers.current = []; };
    const run = () => {
      setShown(0); setTyping(false);
      let t = 400;
      script.forEach((msg, i) => {
        const gap = msg.delay ?? (msg.from === "system" ? 1100 : 850);
        if (msg.from === "system") {
          timers.current.push(setTimeout(() => { if (!cancelled) setTyping(true); }, t));
          t += 700;
        }
        timers.current.push(setTimeout(() => {
          if (cancelled) return;
          setTyping(false);
          setShown(i + 1);
        }, t));
        t += gap;
      });
      // loop
      timers.current.push(setTimeout(() => { if (!cancelled) run(); }, t + 2600));
    };
    run();
    return () => { cancelled = true; clearAll(); };
  }, [active, script]);

  // autoscroll to bottom
  useEffectC(() => {
    const b = bodyRef.current;
    if (b) b.scrollTop = b.scrollHeight;
  }, [shown, typing]);

  return (
    <div ref={wrapRef} className={"wachat" + (fill ? " wachat--fill" : "")} style={fill ? undefined : { height }}>
      {statusBar && (
        <div className="wachat__status">
          <span className="wachat__time">9:41</span>
          <span className="wachat__statusicons">
            <svg width="18" height="11" viewBox="0 0 18 11" aria-hidden="true"><rect x="0" y="6.5" width="3.2" height="4.5" rx="1" fill="currentColor"/><rect x="4.8" y="4.3" width="3.2" height="6.7" rx="1" fill="currentColor"/><rect x="9.6" y="2.1" width="3.2" height="8.9" rx="1" fill="currentColor"/><rect x="14.4" y="0" width="3.2" height="11" rx="1" fill="currentColor"/></svg>
            <svg width="16" height="12" viewBox="0 0 16 12" aria-hidden="true"><path d="M8 3.1C5.5 3.1 3.2 4 1.5 5.6a.6.6 0 0 0 0 .9l6 5.1c.3.2.7.2 1 0l6-5.1a.6.6 0 0 0 0-.9C12.8 4 10.5 3.1 8 3.1z" fill="currentColor"/></svg>
            <svg width="25" height="12" viewBox="0 0 25 12" aria-hidden="true"><rect x="0.6" y="0.6" width="20.5" height="10.8" rx="3" fill="none" stroke="currentColor" strokeOpacity=".5" strokeWidth="1"/><rect x="2.1" y="2.1" width="16" height="7.8" rx="1.8" fill="currentColor"/><rect x="22.4" y="3.9" width="1.8" height="4.2" rx=".9" fill="currentColor" opacity=".55"/></svg>
          </span>
        </div>
      )}
      <div className="wachat__hdr">
        <span className="wachat__back" aria-hidden="true">
          <svg width="11" height="18" viewBox="0 0 11 18" fill="none"><path d="M9.5 1.5L2 9l7.5 7.5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </span>
        <div className="wachat__avatar"><Icon name="chat" size={18} /></div>
        <div style={{ lineHeight: 1.25, minWidth: 0, flex: 1 }}>
          <div className="wachat__title">{title}<span className="wachat__verified" title="Cuenta verificada"><Icon name="check" size={9} stroke={3} /></span></div>
          <div className="wachat__sub">{subtitle}</div>
        </div>
        <div className="wachat__hdr-actions" aria-hidden="true">
          <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M23 7l-7 5 7 5V7z"/><rect x="1" y="5" width="15" height="14" rx="2.5"/></svg>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3-8.6A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.3 1.8.6 2.6a2 2 0 0 1-.4 2.1L8 9.6a16 16 0 0 0 6 6l1.2-1.2a2 2 0 0 1 2.1-.5c.8.3 1.7.5 2.6.6a2 2 0 0 1 1.7 2z"/></svg>
        </div>
      </div>
      <div ref={bodyRef} className="wachat__body">
        {script.slice(0, shown).map((m, i) => (
          <div key={i} className={"wabubble " + (m.from === "client" ? "wabubble--client" : "wabubble--system") + (m.product ? " wabubble--product" : "")}>
            {m.product ? (
              <span className="waprod">
                <span className="waprod__thumb">{m.product.thumb || "📱"}</span>
                <span className="waprod__info">
                  <b>{m.product.name}</b>
                  <i>{m.product.variant}</i>
                  <u>{m.product.price}</u>
                  <em className="waprod__stock">● {m.product.stock || "En stock"}</em>
                </span>
              </span>
            ) : (
              <span>{m.text}</span>
            )}
            <span className="wabubble__time">
              {m.time || "09:4" + (i)}
              {m.from === "client" && <span className="wabubble__ticks">✓✓</span>}
            </span>
          </div>
        ))}
        {typing && (
          <div className="wabubble wabubble--system wabubble--typing">
            <span className="dot" /><span className="dot" /><span className="dot" />
          </div>
        )}
      </div>
      <div className="wachat__input">
        <span className="wachat__field">Escribe un mensaje…</span>
        <span className="wachat__sendbtn"><Icon name="send" size={16} /></span>
      </div>
    </div>
  );
}

window.WAChat = WAChat;
