/* EQALL Mini Demo, "Ask EQALL" autoplay chat on home page.
   Mounts into <div data-mount="chat-demo"></div>. Static HTML fallback
   is shown until React boots.
*/
(function () {
  if (typeof window === "undefined") return;
  const { useState, useEffect, useRef, useCallback } = React;

  const DEMO_SCRIPT = [
    { who: "user", text: "Remind me about Tom Buccola" },
    { who: "ai", text: "Tom Buccola is the Chief AI Officer at Elevance Health, headquartered in the Indianapolis metro area. He holds executive credentials in AI from INSEAD (Mar–May 2024) and a blockchain certificate from MIT Sloan (Nov 2021–Jan 2022), signaling strong tech-forward leadership. Reach him at tom.buccola@elevance.com or 646-555-1212. Personal note: birthday Oct 17; family includes spouse Caroline and children Siena and Valentino. Decision-maker with strategic focus on innovation, great for ROI-driven AI initiatives." },
    { who: "card-attendee", name: "Tom Buccola", role: "CAIO · Elevance Health" },
    { who: "user", text: "When did we meet last?" },
    { who: "ai", text: "Your most recent meeting with Tom Buccola was on March 30, 2026 at 3:00 PM (America/New_York time)." },
    { who: "card-meeting", title: "Tom <> John catch up", when: "Mar 30, 2026 · 3:00 PM" },
    { who: "user", text: "Summarize the last call" },
    { who: "ai", text: "Tom explored AI-native applications and agentic platforms for whole-person health. You walked through Carelon's recent staff-development announcement (March 22) as proof of momentum. You agreed to deliver a joint ROI model. Sentiment: high (8.4/10). Next step due Friday." },
    { who: "user", text: "What should I be prepared for in our next meeting?" },
    { who: "ai", text: "Tom will press on three things: (1) measurable ROI from the joint model, (2) integration risk with Carelon's existing stack, (3) timeline to first production agent. Lead with metrics, not features. Have a 30/60/90 ready. Likely questions: 'How do we measure lift?' · 'Who owns model governance?' · 'What's the rollback plan?'" }
  ];

  function AttendeeCard({ name, role }) {
    return (
      <div className="demo-card demo-card-attendee">
        <div className="demo-card-avatar demo-card-avatar-img">
          <img src="assets/tom-buccola.png" alt="Tom Buccola" />
        </div>
        <div>
          <div className="demo-card-title">{name}</div>
          <div className="demo-card-sub">{role}</div>
        </div>
      </div>
    );
  }

  function MeetingCard({ title, when }) {
    return (
      <div className="demo-card demo-card-meeting">
        <div className="demo-card-icon">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <rect x="3" y="5" width="18" height="16" rx="2" stroke="currentColor" strokeWidth="1.6" />
            <path d="M3 9h18M8 3v4M16 3v4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
          </svg>
        </div>
        <div>
          <div className="demo-card-title">{title}</div>
          <div className="demo-card-sub">{when}</div>
        </div>
      </div>
    );
  }

  function MiniDemo() {
    const [shown, setShown] = useState([]);
    const [typing, setTyping] = useState(false);
    const [draft, setDraft] = useState("");
    const scroller = useRef(null);
    const sectionRef = useRef(null);
    const startedRef = useRef(false);

    const runScript = useCallback(() => {
      let cancelled = false;
      const timers = [];
      const wait = (ms) => new Promise((res) => {
        const t = setTimeout(res, ms);
        timers.push(t);
      });

      (async () => {
        while (!cancelled) {
          setShown([]);
          await wait(600);

          for (let i = 0; i < DEMO_SCRIPT.length; i++) {
            if (cancelled) return;
            const step = DEMO_SCRIPT[i];

            if (step.who === "user") {
              setDraft("");
              for (let c = 1; c <= step.text.length; c++) {
                if (cancelled) return;
                setDraft(step.text.slice(0, c));
                await wait(22 + Math.random() * 30);
              }
              await wait(280);
              setDraft("");
              setShown((s) => [...s, step]);
              await wait(450);
            } else if (step.who === "ai") {
              setTyping(true);
              await wait(900 + Math.min(1400, step.text.length * 6));
              if (cancelled) return;
              setTyping(false);
              setShown((s) => [...s, step]);
              await wait(700);
            } else {
              setShown((s) => [...s, step]);
              await wait(1100);
            }
          }
          await wait(4000);
        }
      })();

      return () => {
        cancelled = true;
        timers.forEach(clearTimeout);
      };
    }, []);

    useEffect(() => {
      if (!sectionRef.current) return;
      const io = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting && !startedRef.current) {
            startedRef.current = true;
            sectionRef.current.__cleanup = runScript();
          }
        });
      }, { threshold: 0.25 });
      io.observe(sectionRef.current);
      return () => {
        io.disconnect();
        if (sectionRef.current && sectionRef.current.__cleanup) sectionRef.current.__cleanup();
      };
    }, [runScript]);

    useEffect(() => {
      if (scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight;
    }, [shown, typing, draft]);

    return (
      <div ref={sectionRef} className="demo-frame">
        <div className="demo-titlebar">
          <div className="traffic">
            <span className="dot" style={{ background: "#FF5F57" }}></span>
            <span className="dot" style={{ background: "#FEBC2E" }}></span>
            <span className="dot" style={{ background: "#28C840" }}></span>
          </div>
          <div style={{ flex: 1, textAlign: "center", color: "var(--on-dark-3)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.06em" }}>
            ASK EQALL®
          </div>
          <div style={{ width: 50 }}></div>
        </div>

        <div className="demo-body demo-body-single">
          <div className="demo-chat" ref={scroller}>
            {shown.map((m, i) => {
              if (m.who === "card-attendee") {
                return (
                  <div key={i} className="demo-msg ai demo-msg-card-row">
                    <div className="demo-msg-avatar-spacer" />
                    <AttendeeCard name={m.name} role={m.role} />
                  </div>
                );
              }
              if (m.who === "card-meeting") {
                return (
                  <div key={i} className="demo-msg ai demo-msg-card-row">
                    <div className="demo-msg-avatar-spacer" />
                    <MeetingCard title={m.title} when={m.when} />
                  </div>
                );
              }
              return (
                <div key={i} className={`demo-msg ${m.who}`}>
                  {m.who === "ai" && <img src="assets/avatar-ai.png" alt="EQALL" className="demo-msg-avatar demo-msg-avatar-img" />}
                  <div className="demo-msg-bubble">{m.text}</div>
                  {m.who === "user" && <img src="assets/avatar-user.png" alt="You" className="demo-msg-user-avatar demo-msg-user-avatar-img" />}
                </div>
              );
            })}
            {typing && (
              <div className="demo-msg ai">
                <img src="assets/avatar-ai.png" alt="EQALL" className="demo-msg-avatar demo-msg-avatar-img" />
                <div className="demo-msg-bubble typing">
                  <span></span><span></span><span></span>
                </div>
              </div>
            )}
          </div>

          <div className="demo-input-bar">
            <div className="demo-input">
              <span className="demo-input-prompt">Ask EQALL anything…</span>
              <span className="demo-input-text">{draft}</span>
              {draft && <span className="demo-input-caret"></span>}
            </div>
            <button className="demo-input-send" tabIndex={-1} aria-hidden="true">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M2 7h9m0 0L7.5 3.5M11 7l-3.5 3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    );
  }

  const mount = document.querySelector('[data-mount="chat-demo"]');
  if (mount && window.ReactDOM && window.React) {
    mount.innerHTML = "";
    ReactDOM.createRoot(mount).render(<MiniDemo />);
  }
})();
