// Animated Telegram-style chat — auto-plays a sequence of scenes.
const { useState, useEffect, useRef, useMemo } = React;

function ChatBubbleUser({ msg }) {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar" style={{ background: msg.avatar }}>
        {msg.name[0]}
      </div>
      <div className="msg-body">
        <div className="msg-name">{msg.name}</div>
        {msg.voice ? (
          <div className="voice-pill">
            {Icons.voice({ width: 14, height: 14, style: { color: 'var(--text)' } })}
            <div className="voice-wave">
              {Array.from({ length: 22 }).map((_, i) => (
                <span key={i} style={{ height: `${4 + Math.abs(Math.sin(i * 1.2)) * 14}px` }} />
              ))}
            </div>
            <span className="voice-time">{msg.voice}</span>
          </div>
        ) : (
          <div className="msg-text">{msg.text}</div>
        )}
      </div>
    </div>
  );
}

function ChatBubbleUserShort({ msg }) {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar" style={{ background: msg.avatar }}>{msg.name[0]}</div>
      <div className="msg-body">
        <div className="msg-name">{msg.name}</div>
        <div className="msg-text">{msg.text}</div>
      </div>
    </div>
  );
}

function ChatBubblePhoto({ msg }) {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar" style={{ background: msg.avatar }}>{msg.name[0]}</div>
      <div className="msg-body">
        <div className="msg-name">{msg.name}</div>
        <div className="photo-pill">
          <div className="photo-thumb" />
          <div className="photo-meta">
            {Icons.image({ width: 14, height: 14, style: { color: 'var(--text-secondary)' } })}
            <span>{msg.label}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function Typing() {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar bot-avatar">{Icons.mark({ width: 16, height: 16 })}</div>
      <div className="msg-body">
        <div className="msg-name accent">octodus_bot</div>
        <div className="typing-pill">
          <span className="typing-dot" />
          <span className="typing-dot" style={{ animationDelay: '120ms' }} />
          <span className="typing-dot" style={{ animationDelay: '240ms' }} />
        </div>
      </div>
    </div>
  );
}

function BotBubble({ msg }) {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar bot-avatar">{Icons.mark({ width: 16, height: 16 })}</div>
      <div className="msg-body bot-body">
        <div className="msg-name accent">octodus_bot</div>
        <div className="msg-text bot-text">{msg.text}</div>
      </div>
    </div>
  );
}

function BotList({ msg }) {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar bot-avatar">{Icons.mark({ width: 16, height: 16 })}</div>
      <div className="msg-body bot-body">
        <div className="bot-list">
          {msg.items.map((item, i) => (
            <div className="bot-list-item" key={i}>
              <span className="bot-list-tick">{Icons.check({ width: 12, height: 12 })}</span>
              <span>{item}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function BotStatus({ msg }) {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar bot-avatar">{Icons.mark({ width: 16, height: 16 })}</div>
      <div className="msg-body bot-body">
        <div className="bot-status">
          {msg.items.map((item, i) => (
            <div className="bot-status-row" key={i}>
              <span className="bot-status-label">{item.label}</span>
              <span className="bot-status-val">{item.status}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function BotAlert({ msg }) {
  return (
    <div className="msg msg-row">
      <div className="msg-avatar bot-avatar">{Icons.mark({ width: 16, height: 16 })}</div>
      <div className="msg-body bot-body alert-body">
        <div className="alert-row">
          <span className="alert-icon">
            {Icons.alert({ width: 14, height: 14 })}
          </span>
          <div>
            <div className="msg-name accent">octodus_bot · auto-detected</div>
            <div className="msg-text">{msg.text}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function renderMsg(m, idx) {
  switch (m.kind) {
    case 'user':       return <ChatBubbleUser msg={m} key={idx} />;
    case 'user-short': return <ChatBubbleUserShort msg={m} key={idx} />;
    case 'user-photo': return <ChatBubblePhoto msg={m} key={idx} />;
    case 'typing':     return <Typing key={idx} />;
    case 'bot':        return <BotBubble msg={m} key={idx} />;
    case 'bot-list':   return <BotList msg={m} key={idx} />;
    case 'bot-status': return <BotStatus msg={m} key={idx} />;
    case 'bot-alert':  return <BotAlert msg={m} key={idx} />;
    default: return null;
  }
}

// Animated chat: builds up scene messages one by one, then advances scene.
function AnimatedChat({ tall = false, autoplay = true }) {
  const [sceneIdx, setSceneIdx] = useState(0);
  const [stepIdx, setStepIdx] = useState(0);
  const scene = SCENES[sceneIdx];
  const scrollRef = useRef(null);

  useEffect(() => {
    if (!autoplay) return;
    const total = scene.messages.length;
    if (stepIdx < total) {
      const last = scene.messages[stepIdx];
      // typing is faster, bot list/status is slower
      let delay = 950;
      if (last.kind === 'typing') delay = 1200;
      if (last.kind === 'user' || last.kind === 'user-short' || last.kind === 'user-photo') delay = 750;
      if (last.kind === 'bot-list' || last.kind === 'bot-status') delay = 1600;
      const t = setTimeout(() => setStepIdx((i) => i + 1), delay);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(() => {
        setStepIdx(0);
        setSceneIdx((s) => (s + 1) % SCENES.length);
      }, 2200);
      return () => clearTimeout(t);
    }
  }, [stepIdx, sceneIdx, autoplay, scene.messages.length]);

  // Filter sequential typing — when next message after typing arrives, hide typing
  const visible = useMemo(() => {
    const out = [];
    const slice = scene.messages.slice(0, stepIdx);
    for (let i = 0; i < slice.length; i++) {
      const m = slice[i];
      if (m.kind === 'typing' && i < slice.length - 1) continue; // hide if a bot reply followed
      out.push(m);
    }
    return out;
  }, [scene, stepIdx]);

  // Auto-scroll to bottom on new message
  useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
  }, [visible.length, sceneIdx]);

  return (
    <div className={`chat-shell ${tall ? 'chat-tall' : ''}`}>
      <div className="chat-window">
        {/* Header */}
        <div className="chat-header">
          <div className="chat-tg-dot">{Icons.mark({ width: 18, height: 18 })}</div>
          <div className="chat-title-block">
            <div className="chat-title">octodus · team</div>
            <div className="chat-sub">
              <span className="online" /> 4 online
            </div>
          </div>
          <div className="chat-chip" style={{ '--chip': scene.chipColor }}>
            <span className="chat-chip-dot" />
            {scene.chip}
          </div>
        </div>

        {/* Messages */}
        <div className="chat-scroll" ref={scrollRef}>
          {visible.map((m, i) => (
            <div className="msg-enter" key={`${sceneIdx}-${i}`}>
              {renderMsg(m, i)}
            </div>
          ))}
          <div style={{ height: 8 }} />
        </div>

        {/* Input row */}
        <div className="chat-input">
          <div className="chat-input-field">Message @octodus_bot…</div>
          <button className="chat-send" aria-label="Send">
            {Icons.send({ width: 14, height: 14 })}
          </button>
        </div>
      </div>

      {/* Scene indicator dots */}
      <div className="scene-dots" role="tablist">
        {SCENES.map((s, i) => (
          <button
            key={s.id}
            className={`scene-dot ${i === sceneIdx ? 'active' : ''}`}
            onClick={() => { setSceneIdx(i); setStepIdx(0); }}
            aria-label={s.chip}
          >
            <span className="scene-dot-label">{s.chip}</span>
          </button>
        ))}
      </div>

      <style>{`
        .chat-shell {
          position: relative;
          width: 100%;
          max-width: 480px;
          margin: 0 auto;
        }
        .chat-shell::before {
          content: "";
          position: absolute;
          inset: -32px;
          background: radial-gradient(ellipse 60% 60% at 50% 40%,
            var(--accent-tint-22) 0%, var(--accent-tint-06) 45%, transparent 75%);
          filter: blur(40px);
          z-index: 0;
          pointer-events: none;
        }
        .chat-window {
          position: relative;
          z-index: 1;
          background: linear-gradient(180deg, rgba(235, 227, 210, 1.00) 0%, rgba(235, 227, 210, 1.00) 100%);
          border: 1px solid var(--border);
          border-radius: 24px;
          overflow: hidden;
          box-shadow:
            inset 0 1px 0 var(--border),
            0 30px 80px -20px rgba(58, 49, 32, 0.14),
            0 0 40px var(--accent-tint-08);
          backdrop-filter: blur(20px);
        }
        .chat-header {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 14px 18px;
          border-bottom: 1px solid var(--border);
          background: rgba(235, 227, 210, 0.50);
        }
        .chat-tg-dot {
          width: 32px; height: 32px;
          border-radius: 8px;
          background: var(--accent-soft);
          color: var(--accent-light);
          border: 1px solid color-mix(in oklch, var(--accent) 30%, transparent);
          display: flex; align-items: center; justify-content: center;
          position: relative;
        }
        .chat-title-block { flex: 1; min-width: 0; }
        .chat-title {
          font-weight: 600; font-size: 14px;
          color: var(--text); letter-spacing: -0.01em;
        }
        .chat-sub {
          display: flex; align-items: center; gap: 6px;
          font-family: var(--font-mono);
          font-size: 11px; color: var(--text-muted);
          margin-top: 2px;
        }
        .online {
          width: 6px; height: 6px; border-radius: 50%;
          background: var(--accent-light);
          box-shadow: 0 0 8px var(--accent-light);
        }
        .chat-chip {
          font-family: var(--font-mono);
          font-size: 10px;
          font-weight: 600;
          letter-spacing: 0.12em;
          padding: 6px 10px;
          border-radius: 999px;
          background: color-mix(in oklch, var(--chip) 18%, transparent);
          color: var(--chip, var(--accent-light));
          border: 1px solid color-mix(in oklch, var(--chip) 30%, transparent);
          display: flex; align-items: center; gap: 6px;
          white-space: nowrap;
          max-width: 220px;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .chat-chip-dot {
          width: 6px; height: 6px; border-radius: 50%;
          background: currentColor;
          box-shadow: 0 0 8px currentColor;
        }
        .chat-scroll {
          height: 420px;
          overflow-y: auto;
          padding: 18px;
          display: flex; flex-direction: column; gap: 14px;
          background: rgba(235, 227, 210, 0.55);
          scroll-behavior: smooth;
        }
        .chat-tall .chat-scroll { height: 500px; }
        .chat-scroll::-webkit-scrollbar { width: 4px; }
        .chat-scroll::-webkit-scrollbar-thumb { background: var(--border-light); }

        .msg-enter {
          animation: msg-in 360ms cubic-bezier(0.16, 1, 0.3, 1) both;
        }
        @keyframes msg-in {
          from { opacity: 0; transform: translateY(6px) scale(0.98); }
          to   { opacity: 1; transform: translateY(0) scale(1); }
        }

        .msg-row { display: flex; gap: 10px; align-items: flex-start; }
        .msg-avatar {
          width: 30px; height: 30px;
          border-radius: 8px;
          display: flex; align-items: center; justify-content: center;
          font-size: 11px; font-weight: 700; color: #fff;
          flex-shrink: 0;
          font-family: var(--font-mono);
        }
        .bot-avatar {
          background: var(--accent-soft);
          border: 1px solid color-mix(in oklch, var(--accent) 30%, transparent);
          color: var(--accent-light);
          border-radius: 8px;
          position: relative;
        }
        .bot-avatar .dot {
          width: 14px; height: 14px;
          display: block;
          color: var(--accent-light);
        }
        .bot-avatar .dot::before {
          content: "";
          display: block;
          width: 100%; height: 100%;
          background: currentColor;
          mask: radial-gradient(circle 3px at center, black 90%, transparent 100%);
          -webkit-mask: radial-gradient(circle 3px at center, black 90%, transparent 100%);
        }
        .msg-body { min-width: 0; flex: 1; }
        .msg-name {
          font-size: 11px;
          font-family: var(--font-mono);
          color: var(--text-muted);
          margin-bottom: 4px;
        }
        .msg-name.accent { color: var(--accent-light); }
        .msg-text {
          font-size: 14px;
          color: var(--text);
          line-height: 1.5;
        }
        .bot-text {
          padding: 10px 14px;
          background: var(--accent-tint-10);
          border: 1px solid var(--accent-tint-25);
          border-radius: 12px 12px 12px 4px;
          display: inline-block;
        }

        /* Voice */
        .voice-pill {
          display: inline-flex;
          align-items: center;
          gap: 10px;
          padding: 10px 14px;
          background: rgba(107, 79, 168, 0.10);
          border: 1px solid rgba(107, 79, 168, 0.25);
          border-radius: 999px;
          min-width: 200px;
        }
        .voice-wave {
          display: flex;
          align-items: center;
          gap: 2px;
          flex: 1;
        }
        .voice-wave span {
          width: 2px; background: var(--text-secondary);
          border-radius: 1px;
          animation: wave 1.8s ease-in-out infinite;
        }
        .voice-wave span:nth-child(odd) { animation-delay: 150ms; background: var(--text); }
        @keyframes wave {
          0%, 100% { transform: scaleY(0.6); opacity: 0.6; }
          50% { transform: scaleY(1.0); opacity: 1; }
        }
        .voice-time {
          font-family: var(--font-mono);
          font-size: 11px;
          color: var(--text-secondary);
        }

        /* Photo */
        .photo-pill {
          display: inline-flex;
          flex-direction: column;
          gap: 6px;
        }
        .photo-thumb {
          width: 180px; height: 120px;
          border-radius: 12px;
          background:
            linear-gradient(135deg, #C9A876 0%, #B8956F 60%, #8F6F4E 100%),
            repeating-linear-gradient(45deg, rgba(184, 110, 30, 0.10) 0px, rgba(184, 110, 30, 0.10) 2px, transparent 2px, transparent 6px);
          background-blend-mode: overlay;
          position: relative;
          overflow: hidden;
          border: 1px solid var(--border);
        }
        .photo-thumb::after {
          content: ""; position: absolute; inset: 30%;
          border-radius: 50%;
          background: radial-gradient(circle, rgba(245,158,11,0.5) 0%, rgba(168,108,40,0.3) 50%, transparent 80%);
          filter: blur(8px);
        }
        .photo-thumb::before {
          content: ""; position: absolute; inset: 20% 35%;
          border-radius: 50%;
          background: linear-gradient(135deg, rgba(245,200,80,0.4) 0%, rgba(180,130,40,0.2) 100%);
          box-shadow: inset 0 0 10px rgba(255,200,100,0.3);
        }
        .photo-meta {
          font-family: var(--font-mono);
          font-size: 11px;
          color: var(--text-muted);
          display: inline-flex;
          align-items: center;
          gap: 6px;
        }

        /* Typing */
        .typing-pill {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          padding: 12px 14px;
          background: var(--accent-tint-10);
          border: 1px solid var(--accent-tint-25);
          border-radius: 12px 12px 12px 4px;
        }
        .typing-dot {
          width: 6px; height: 6px;
          border-radius: 50%;
          background: var(--accent-light);
          animation: typing-bob 1.1s ease-in-out infinite;
        }
        @keyframes typing-bob {
          0%, 100% { transform: translateY(0); opacity: 0.4; }
          40% { transform: translateY(-3px); opacity: 1; }
        }

        /* Bot list */
        .bot-list {
          padding: 12px 14px;
          background: var(--accent-tint-10);
          border: 1px solid var(--accent-tint-25);
          border-radius: 12px 12px 12px 4px;
          display: flex;
          flex-direction: column;
          gap: 8px;
          min-width: 220px;
        }
        .bot-list-item {
          display: flex; align-items: center; gap: 8px;
          font-size: 13px;
          color: var(--text);
        }
        .bot-list-tick {
          width: 18px; height: 18px;
          border-radius: 50%;
          background: var(--accent);
          color: var(--on-accent);
          display: flex; align-items: center; justify-content: center;
        }

        /* Bot status */
        .bot-status {
          padding: 12px 14px;
          background: var(--accent-tint-08);
          border: 1px solid var(--accent-tint-22);
          border-radius: 12px 12px 12px 4px;
          display: flex;
          flex-direction: column;
          gap: 8px;
          min-width: 240px;
          font-family: var(--font-mono);
          font-size: 12px;
        }
        .bot-status-row {
          display: flex; justify-content: space-between; align-items: center;
          gap: 16px;
          padding: 4px 0;
          border-bottom: 1px dashed var(--border);
        }
        .bot-status-row:last-child { border-bottom: none; }
        .bot-status-label { color: var(--text-secondary); }
        .bot-status-val { color: var(--accent-light); font-weight: 600; }

        /* Bot alert */
        .alert-body { }
        .alert-row {
          display: flex; gap: 10px; align-items: flex-start;
          padding: 12px 14px;
          background: rgba(239,68,68,0.08);
          border: 1px solid rgba(239,68,68,0.25);
          border-radius: 12px 12px 12px 4px;
        }
        .alert-icon {
          width: 24px; height: 24px;
          flex-shrink: 0;
          border-radius: 50%;
          background: rgba(239,68,68,0.2);
          color: #fca5a5;
          display: flex; align-items: center; justify-content: center;
        }

        /* Input row */
        .chat-input {
          display: flex; align-items: center; gap: 10px;
          padding: 12px 16px;
          border-top: 1px solid var(--border);
          background: rgba(235, 227, 210, 0.50);
        }
        .chat-input-field {
          flex: 1;
          font-family: var(--font-mono);
          font-size: 12px;
          color: var(--text-muted);
        }
        .chat-send {
          width: 32px; height: 32px;
          border-radius: 50%;
          border: none;
          background: var(--accent);
          color: var(--on-accent);
          display: flex; align-items: center; justify-content: center;
          transition: transform 180ms var(--ease-out), background 180ms var(--ease-out);
        }
        .chat-send:hover { transform: scale(1.08); background: var(--accent-light); }

        /* Scene dots */
        .scene-dots {
          margin-top: 18px;
          display: flex; justify-content: center; gap: 10px;
          flex-wrap: wrap;
        }
        .scene-dot {
          background: transparent;
          border: 1px solid var(--border);
          border-radius: 999px;
          padding: 5px 12px;
          color: var(--text-muted);
          font-family: var(--font-mono);
          font-size: 10px;
          letter-spacing: 0.1em;
          transition: all 200ms var(--ease-out);
          opacity: 0.6;
        }
        .scene-dot:hover { opacity: 1; border-color: var(--border-light); }
        .scene-dot.active {
          opacity: 1;
          background: var(--accent-tint-12);
          border-color: var(--accent-tint-40);
          color: var(--accent-light);
        }
        .scene-dot-label { display: inline-block; }
      `}</style>
    </div>
  );
}

Object.assign(window, { AnimatedChat });
