// Live-feel Hopper chat preview — auto-plays a scripted conversation
const { useState, useEffect, useRef } = React;

const SCRIPT = [
  {
    role: 'user',
    text: 'AC out in Whitman 214. Faculty meeting at 2pm.',
    delay: 600,
  },
  {
    role: 'bot',
    typing: 1200,
    text: 'Pulling Whitman 214. Last service was the AHU-3 belt replacement in March. Want me to open a P1?',
    tool: {
      name: 'lookup_asset',
      rows: [
        ['asset', 'AHU-3 · Whitman 214'],
        ['last_pm', '2026-03-12 · belt replacement'],
        ['warranty', '7 mo remaining'],
      ],
    },
    delay: 2400,
  },
  {
    role: 'user',
    text: 'Yes. Assign Diaz, SLA 2 hours.',
    delay: 1100,
  },
  {
    role: 'bot',
    typing: 900,
    text: 'Confirm before I create it:',
    tool: {
      name: 'create_ticket — pending confirm',
      rows: [
        ['priority', 'P1'],
        ['assignee', 'M. Diaz'],
        ['sla', '2h · breach 14:32'],
        ['location', 'Whitman 214 · AHU-3'],
      ],
      confirm: true,
    },
    delay: 1800,
  },
];

function Hopper() {
  const [step, setStep] = useState(0);
  const [showTyping, setShowTyping] = useState(false);
  const [active, setActive] = useState('chat');
  const threadRef = useRef(null);

  useEffect(() => {
    if (step >= SCRIPT.length) {
      // restart loop after a pause
      const t = setTimeout(() => setStep(0), 5500);
      return () => clearTimeout(t);
    }
    const item = SCRIPT[step];
    let typingTimer, advanceTimer;
    if (item.role === 'bot' && item.typing) {
      setShowTyping(true);
      typingTimer = setTimeout(() => setShowTyping(false), item.typing);
    }
    advanceTimer = setTimeout(() => {
      setStep(s => s + 1);
    }, item.delay);
    return () => {
      clearTimeout(typingTimer);
      clearTimeout(advanceTimer);
    };
  }, [step]);

  // visible items: when step is N, show 0..N-1 plus typing for N if applicable
  const visible = SCRIPT.slice(0, step);
  const next = SCRIPT[step];
  const typingNow = next && next.role === 'bot' && showTyping;

  const sideItems = [
    { id: 'chat', label: 'New thread', active: true, icon: '◇' },
    { id: 'tickets', label: 'Tickets · 47', icon: '◫' },
    { id: 'sows', label: 'SOWs · 12', icon: '⌘' },
    { id: 'contracts', label: 'Contracts · 8', icon: '∎' },
    { id: 'pms', label: 'PM schedule', icon: '◐' },
    { id: 'photo', label: 'Photo diagnose', icon: '◉' },
  ];

  return (
    <div className="live-frame">
      <div className="live-bar">
        <div className="live-dots">
          <span className="live-dot"></span>
          <span className="live-dot"></span>
          <span className="live-dot"></span>
        </div>
        <div className="live-bar-title">app.korsys.org / hopper / threads / new</div>
        <div className="live-bar-status">Hopper online</div>
      </div>
      <div className="live-body">
        <aside className="live-side">
          <div className="live-side-head">Workspaces</div>
          {sideItems.map(it => (
            <div
              key={it.id}
              className={`live-side-item ${it.active ? 'active' : ''}`}>
              <span className="live-side-icon" style={{display:'inline-block', width:14, textAlign:'center'}}>{it.icon}</span>
              <span>{it.label}</span>
            </div>
          ))}
          <div style={{flex:1}}></div>
          <div className="live-side-head" style={{paddingBottom:14}}>Campus · Western Univ.</div>
        </aside>
        <div className="live-chat">
          <div className="live-chat-thread" ref={threadRef}>
            {visible.map((m, i) => (
              <Message key={i} m={m} />
            ))}
            {typingNow && (
              <div className="msg bot">
                <div className="msg-avatar">H</div>
                <div className="msg-bubble">
                  <div className="msg-typing">
                    <span></span><span></span><span></span>
                  </div>
                </div>
              </div>
            )}
          </div>
          <div className="live-input">
            <div className="live-input-field">Ask Hopper anything…</div>
            <div className="live-input-send">↵</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Message({ m }) {
  return (
    <div className={`msg ${m.role}`}>
      <div className="msg-avatar">{m.role === 'bot' ? 'H' : 'JM'}</div>
      <div className="msg-bubble">
        <div>{m.text}</div>
        {m.tool && (
          <div className="msg-tool">
            <div className="msg-tool-head">tool · {m.tool.name}</div>
            {m.tool.rows.map(([k, v]) => (
              <div key={k} className="msg-tool-row">
                <span className="k">{k}</span>
                <span className="v">{v}</span>
              </div>
            ))}
            {m.tool.confirm && (
              <div style={{
                marginTop: 10, display: 'flex', gap: 8,
              }}>
                <span style={{
                  background: 'var(--lime)', color: '#0a0a0c',
                  padding: '5px 12px', borderRadius: 5,
                  fontSize: 10.5, fontWeight: 600, letterSpacing: '.1em',
                  textTransform: 'uppercase',
                }}>Confirm</span>
                <span style={{
                  border: '1px solid var(--line-2)', color: 'var(--text-2)',
                  padding: '5px 12px', borderRadius: 5,
                  fontSize: 10.5, fontWeight: 600, letterSpacing: '.1em',
                  textTransform: 'uppercase',
                }}>Edit</span>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

window.Hopper = Hopper;
