/* WhatsApp chat bot animation — loops a scripted conversation. */
const { useState, useEffect, useRef } = React;

const chatScript = [
  { from: "user", text: "Hi! Is the sofa still available?" },
  { from: "bot",  text: "Yes! The Nora 3-seater in beige — in stock at our HSR store.", typing: 900 },
  { from: "bot",  text: "Would you like to reserve it for a visit? I can hold it for 24h.", typing: 700 },
  { from: "user", text: "Yes please — tomorrow 6pm" },
  { from: "bot",  text: "Done. Reserved for Sat 6:00 PM ✅", typing: 600 },
  { from: "bot",  text: "I've also sent directions and a 10% first-visit code.", typing: 500 },
];

function useLoopingChat(speedMs = 1400) {
  const [visible, setVisible] = useState([]);
  const [typing, setTyping] = useState(false);
  const idx = useRef(0);
  const loop = useRef(0);

  useEffect(() => {
    let t1, t2;
    const step = () => {
      const i = idx.current;
      if (i >= chatScript.length) {
        // reset after a pause
        t1 = setTimeout(() => {
          setVisible([]);
          idx.current = 0;
          loop.current += 1;
          step();
        }, 3200);
        return;
      }
      const msg = chatScript[i];
      const typingMs = msg.typing || 0;
      if (msg.from === "bot" && typingMs) {
        setTyping(true);
        t1 = setTimeout(() => {
          setTyping(false);
          setVisible(v => [...v, { ...msg, id: `${loop.current}-${i}` }]);
          idx.current += 1;
          t2 = setTimeout(step, speedMs);
        }, typingMs + 400);
      } else {
        setVisible(v => [...v, { ...msg, id: `${loop.current}-${i}` }]);
        idx.current += 1;
        t2 = setTimeout(step, speedMs);
      }
    };
    t2 = setTimeout(step, 600);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [speedMs]);

  return { visible, typing };
}

function WAChatStage({ compact = false, showHeader = true }) {
  const { visible, typing } = useLoopingChat(compact ? 1100 : 1500);
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [visible, typing]);

  return (
    <div className="wa-stage">
      {showHeader && (
        <div className="wa-header">
          <div className="wa-avatar">K</div>
          <div style={{ flex: 1 }}>
            <div className="wa-name">Kavya's Furniture</div>
            <div className="wa-status">online · Business</div>
          </div>
          <div className="wa-icons">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M23 7l-7 5 7 5V7zM14 5H3a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z"/></svg>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.8 12.8 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.8 12.8 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
          </div>
        </div>
      )}
      <div className="wa-body" ref={scrollRef}>
        <div className="wa-date-chip">Today</div>
        {visible.map(m => (
          <div key={m.id} className={`wa-msg ${m.from}`}>
            <div className="wa-bubble">
              {m.text}
              <span className="wa-time">{m.from === "bot" ? "12:41" : "12:40"}{m.from === "user" && <span className="wa-ticks">✓✓</span>}</span>
            </div>
          </div>
        ))}
        {typing && (
          <div className="wa-msg bot">
            <div className="wa-bubble typing">
              <span className="wa-dot" /><span className="wa-dot" /><span className="wa-dot" />
            </div>
          </div>
        )}
      </div>
      <div className="wa-input">
        <div className="wa-input-box">Message</div>
        <div className="wa-mic">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 1 0 6 0V5a3 3 0 0 0-3-3zm7 10a7 7 0 0 1-14 0H3a9 9 0 0 0 8 8.9V23h2v-2.1a9 9 0 0 0 8-8.9h-2z"/></svg>
        </div>
      </div>
      <style>{`
        .wa-stage { width: 100%; height: 100%; background: #0b3621;
          background-image: radial-gradient(rgba(255,255,255,.04) 1px, transparent 1px),
                             radial-gradient(rgba(255,255,255,.03) 1px, transparent 1px);
          background-size: 40px 40px, 26px 26px;
          background-position: 0 0, 13px 13px;
          display: flex; flex-direction: column; font-family: var(--f-sans); }
        .wa-header { display: flex; align-items: center; gap: 10px; padding: 14px 14px; background: #1f2c33; color: #fff; }
        .wa-avatar { width: 36px; height: 36px; border-radius: 50%; background: #0ac775; color: #002415; display:grid; place-items:center; font-weight: 600; font-size: 14px; }
        .wa-name { font-size: 15px; font-weight: 500; }
        .wa-status { font-size: 12px; color: #a9b6bd; }
        .wa-icons { display: flex; gap: 14px; color: #a9b6bd; }
        .wa-body { flex: 1; overflow: hidden; padding: 14px 10px; display: flex; flex-direction: column; gap: 6px; scroll-behavior: smooth; }
        .wa-date-chip { align-self: center; background: rgba(14,30,23,.6); color: #cbd3d6; font-size: 11px; padding: 4px 10px; border-radius: 999px; margin-bottom: 6px; }
        .wa-msg { display: flex; width: 100%; animation: msg-pop .35s cubic-bezier(.2,.7,.2,1) both; }
        .wa-msg.user { justify-content: flex-end; }
        .wa-msg.bot { justify-content: flex-start; }
        .wa-bubble {
          max-width: 78%; padding: 8px 11px 20px; border-radius: 10px;
          font-size: 13.5px; line-height: 1.3; position: relative;
          box-shadow: 0 1px 0 rgba(0,0,0,.2);
        }
        .wa-msg.user .wa-bubble { background: #005c4b; color: #e8eef0; border-top-right-radius: 2px; }
        .wa-msg.bot .wa-bubble { background: #1f2c33; color: #e8eef0; border-top-left-radius: 2px; }
        .wa-time { position: absolute; right: 8px; bottom: 4px; font-size: 10px; color: #91a1a8; display: flex; align-items: center; gap: 4px; }
        .wa-ticks { color: #53bdeb; font-size: 12px; }
        .wa-bubble.typing { display: inline-flex; gap: 4px; padding: 12px 14px; }
        .wa-dot { width: 7px; height: 7px; border-radius: 50%; background: #91a1a8; animation: typing-pulse 1.1s ease-in-out infinite; }
        .wa-dot:nth-child(2) { animation-delay: .15s; }
        .wa-dot:nth-child(3) { animation-delay: .3s; }
        .wa-input { display: flex; align-items: center; gap: 8px; padding: 10px; background: transparent; }
        .wa-input-box { flex: 1; background: #1f2c33; color: #7e8b91; border-radius: 999px; padding: 10px 16px; font-size: 13px; }
        .wa-mic { width: 40px; height: 40px; border-radius: 50%; background: #00a884; color: #fff; display: grid; place-items: center; }

        @keyframes msg-pop {
          from { opacity: 0; transform: translateY(6px) scale(.98); }
          to { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes typing-pulse {
          0%, 100% { transform: translateY(0); opacity: .4; }
          50% { transform: translateY(-3px); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

window.WAChatStage = WAChatStage;
