/* Mica chat thread — original UI, brand-gradient bubbles.
   Animates a realistic rep ⇄ Mica exchange. */
const { useState, useEffect, useRef } = React;

const HERO_SCRIPT = [
  { kind: "day",    text: "Today · 14:32" },
  { kind: "them",   text: "Logged a call with Sarah at TechFlow. She wants pricing Thursday and a security review by next week.", time: "14:32", delay: 600 },
  { kind: "typing", delay: 900 },
  { kind: "me",     text: "Got it. Updating Sarah Chen / TechFlow.", time: "14:32", delay: 1200, replaceTyping: true },
  { kind: "card",   delay: 800, payload: {
      label: "Pipeline update",
      stage: "Negotiating",
      rows: [
        ["Company", "TechFlow Labs"],
        ["Contact", "Sarah Chen · VP Ops"],
        ["Deal", "R 480,000 ARR"],
        ["Next step", "Pricing · Thu 14:00"],
      ],
      foot: ["Edit", "Looks good"],
  }},
  { kind: "me",     text: "Also drafting the security one-pager. Want me to send it to her now or after Thursday?", time: "14:33", delay: 1100 },
];

const VOICE_SCRIPT = [
  { kind: "day",    text: "Tomorrow · 08:04" },
  { kind: "them",   kindSub: "voice", duration: 11, time: "08:04", delay: 500 },
  { kind: "typing", delay: 700 },
  { kind: "me",     text: "Captured. Filed under TechFlow → next step: send revised proposal Friday. Want a draft?", time: "08:04", delay: 1300, replaceTyping: true },
  { kind: "them",   text: "yes", time: "08:05", delay: 1000 },
];

const Bubble = ({ msg }) => {
  if (msg.kind === "day") return <div className="chat-day">{msg.text}</div>;
  if (msg.kind === "typing") return (
    <div className="typing"><i></i><i></i><i></i></div>
  );
  if (msg.kindSub === "voice") {
    const bars = Array.from({ length: 22 }, (_, i) => {
      const h = 4 + Math.abs(Math.sin(i * 0.9)) * 16 + (i % 4) * 2;
      return <i key={i} style={{ height: Math.min(20, h) + 'px' }} />;
    });
    return (
      <div className={`bubble ${msg.kind} voice`}>
        <div className="play"><Icon name="play" size={11}/></div>
        <div className="wave">{bars}</div>
        <span className="time mono">0:{String(msg.duration).padStart(2,'0')}</span>
      </div>
    );
  }
  if (msg.kind === "card") {
    const p = msg.payload;
    return (
      <div className="bubble card">
        <div className="card-head">
          <span className="label">{p.label}</span>
          <span className="stage">{p.stage}</span>
        </div>
        <div className="card-body">
          {p.rows.map(([k,v]) => (
            <div className="card-row" key={k}><span className="k">{k}</span><span className="v">{v}</span></div>
          ))}
        </div>
        <div className="card-foot">
          <span className="mini-btn">{p.foot[0]}</span>
          <span className="mini-btn primary">{p.foot[1]}</span>
        </div>
      </div>
    );
  }
  return (
    <div className={`bubble ${msg.kind}`}>
      {msg.text}
      {msg.time ? <span className="time">{msg.time}</span> : null}
    </div>
  );
};

const ChatThread = ({ script = HERO_SCRIPT, loop = true, startDelay = 400, headerName = "Mica", headerTag = "AI · WhatsApp Business" }) => {
  const [visible, setVisible] = useState([]);
  const feedRef = useRef(null);
  const idxRef = useRef(0);
  const timerRef = useRef(null);

  useEffect(() => {
    setVisible([]);
    idxRef.current = 0;

    const step = () => {
      const i = idxRef.current;
      if (i >= script.length) {
        if (loop) {
          timerRef.current = setTimeout(() => {
            setVisible([]);
            idxRef.current = 0;
            timerRef.current = setTimeout(step, 700);
          }, 3500);
        }
        return;
      }
      const msg = script[i];
      setVisible(prev => {
        if (msg.replaceTyping) {
          // remove last item if it's typing
          const arr = prev.filter((p, ix) => !(ix === prev.length - 1 && p.kind === "typing"));
          return [...arr, msg];
        }
        return [...prev, msg];
      });
      idxRef.current = i + 1;
      const next = script[i + 1];
      const wait = next?.delay ?? 800;
      timerRef.current = setTimeout(step, wait);
    };

    timerRef.current = setTimeout(step, startDelay);
    return () => clearTimeout(timerRef.current);
  }, [script, loop, startDelay]);

  useEffect(() => {
    if (feedRef.current) {
      feedRef.current.scrollTop = feedRef.current.scrollHeight;
    }
  }, [visible]);

  return (
    <div className="phone" aria-label="Mica WhatsApp conversation preview">
      <div className="phone-screen">
        <div className="phone-status">
          <span>9:41</span>
          <span className="icons mono">
            <span>•••</span>
            <span>5G</span>
            <span style={{display:'inline-block', width: 22, height: 10, border: '1.5px solid var(--fg)', borderRadius: 2, position: 'relative'}}>
              <span style={{position:'absolute', inset: '1px 9px 1px 1px', background: 'var(--fg)', borderRadius: 1}}/>
            </span>
          </span>
        </div>
        <div className="chat-header">
          <div className="avatar">M</div>
          <div className="who">
            <span className="name">{headerName}</span>
            <span className="status"><span className="dot"></span>{headerTag}</span>
          </div>
          <span className="verified">✓ Verified</span>
        </div>
        <div className="chat-feed" ref={feedRef}>
          {visible.map((m, i) => <Bubble key={i + (m.kind || '') + i} msg={m} />)}
        </div>
        <div className="chat-input">
          <span className="field">Message Mica…</span>
          <span className="mic"><Icon name="mic" size={16}/></span>
        </div>
      </div>
    </div>
  );
};

window.ChatThread = ChatThread;
window.HERO_SCRIPT = HERO_SCRIPT;
window.VOICE_SCRIPT = VOICE_SCRIPT;
