/* Desk UI Kit — Channels subsystem: Slack-like rooms where agents talk.
   Exposes window.ChannelsView; loaded before Workspace.jsx. */
(() => {
  const { useState, useEffect, useRef, useCallback } = React;
  const CH = window.DESK_CHANNELS;

  function CIco({ name, size = 16 }) {
    return <i data-lucide={name} style={{ width: size, height: size }} />;
  }

  const byId = (id) => CH.members.find((m) => m.id === id) || { id, name: id, ava: '??', tone: 'c1', tag: 'agent' };

  /* @mentions and `code` spans rendered inline */
  function renderText(text) {
    const parts = text.split(/(@[\w-]+|`[^`]+`)/g);
    return parts.map((p, i) => {
      if (/^@/.test(p)) return <span key={i} className="mention">{p}</span>;
      if (/^`/.test(p)) return <code key={i}>{p.slice(1, -1)}</code>;
      return p;
    });
  }

  function nowStamp() {
    const d = new Date();
    return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
  }

  function ChannelsView() {
    const [chans, setChans] = useState(() => JSON.parse(JSON.stringify(CH.channels)));
    const [active, setActive] = useState('deploy');
    const [draft, setDraft] = useState('');
    const [typing, setTyping] = useState(null); // { who, chan }
    const scrollRef = useRef(null);
    const timers = useRef([]);
    const activeRef = useRef('deploy');
    const replyIdx = useRef({});
    activeRef.current = active;
    const chan = chans.find((c) => c.id === active) || chans[0];

    useEffect(() => { try { window.lucide && window.lucide.createIcons(); } catch (e) {} });
    useEffect(() => {
      const el = scrollRef.current;
      if (el) el.scrollTop = el.scrollHeight;
    }, [chans, typing, active]);

    const post = useCallback((chanId, who, text) => {
      setChans((cs) => cs.map((c) => c.id === chanId
        ? { ...c, msgs: [...c.msgs, { who, t: nowStamp(), text }], unread: chanId === activeRef.current ? 0 : c.unread + 1 }
        : c));
    }, []);

    /* ambient scripted traffic */
    useEffect(() => {
      (CH.drip || []).forEach((d) => {
        timers.current.push(setTimeout(() => setTyping({ who: d.who, chan: d.chan }), Math.max(0, d.delay - 1000)));
        timers.current.push(setTimeout(() => { setTyping(null); post(d.chan, d.who, d.text); }, d.delay));
      });
      return () => timers.current.forEach(clearTimeout);
    }, [post]);

    const send = () => {
      const text = draft.trim();
      if (!text) return;
      setDraft('');
      post(active, 'human', text);
      const m = text.match(/@([\w-]+)/);
      let responder = m ? CH.members.find((x) => x.id === m[1] && x.id !== 'human') : null;
      if (!responder) responder = byId(CH.defaultResponder);
      const pool = CH.replies[responder.id] || CH.replies[CH.defaultResponder];
      replyIdx.current[responder.id] = ((replyIdx.current[responder.id] || 0) + 1) % pool.length;
      const reply = pool[replyIdx.current[responder.id]];
      const chanAt = active;
      timers.current.push(setTimeout(() => setTyping({ who: responder.id, chan: chanAt }), 650));
      timers.current.push(setTimeout(() => { setTyping(null); post(chanAt, responder.id, reply); }, 1900 + Math.random() * 900));
    };

    const openChan = (id) => {
      setActive(id);
      setChans((cs) => cs.map((x) => x.id === id ? { ...x, unread: 0 } : x));
    };

    return (
      <div className="subsystemPanels">
        <div className="agentsSidebar">
          <div className="sidebarHeader">
            <span className="railTitle"><CIco name="messages-square" size={13} /> Channels</span>
            <button className="thinButton"><CIco name="plus" size={12} /></button>
          </div>
          <div className="projectTree">
            <div className="gitGroupHeader">Rooms · {chans.length}</div>
            {chans.map((c) => (
              <div key={c.id} className={`chanRow ${active === c.id ? 'selected' : ''}`} onClick={() => openChan(c.id)}>
                <span className="hash">#</span><span>{c.name}</span>
                {c.unread ? <span className="chanUnread">{c.unread}</span> : null}
              </div>
            ))}
            <div className="gitGroupHeader">Members · {CH.members.length}</div>
            {CH.members.map((m) => (
              <div key={m.id} className="memberRow">
                <span className={`statusDot2 ${m.status}`} />
                <span>{m.name}</span>
                <small>{m.tag}</small>
              </div>
            ))}
          </div>
        </div>
        <div className="subsystemSurface">
          <div className="subsystemHeader">
            <CIco name="hash" size={13} /> {chan.name}
            <span style={{ color: 'var(--text-dim)', textTransform: 'none', letterSpacing: 0.4 }}>{chan.topic}</span>
            <span className="layoutBadge">4 agents · 1 human</span>
          </div>
          <div className="chatWrap">
            <div className="chatScroll" ref={scrollRef}>
              <div className="dayDivider"><span>today</span></div>
              {chan.msgs.map((msg, i) => {
                const m = byId(msg.who);
                const prev = chan.msgs[i - 1];
                const grouped = !!prev && prev.who === msg.who;
                return (
                  <div key={i} className="chatMsg">
                    {grouped
                      ? <span className="chatGutterTime">{msg.t}</span>
                      : <span className={`chatAva ${m.tone}`}>{m.ava}</span>}
                    <div>
                      {!grouped ? (
                        <div className="chatHead">
                          <b className={m.id === 'human' ? 'human' : ''}>{m.name}</b>
                          <span className="agentTag">{m.tag}</span>
                          <time>{msg.t}</time>
                        </div>
                      ) : null}
                      <div className="chatBody">{renderText(msg.text)}</div>
                    </div>
                  </div>
                );
              })}
              {typing && typing.chan === active ? (
                <div className="typingRow">
                  <span className="typingDots"><i></i><i></i><i></i></span>
                  {byId(typing.who).name} is typing…
                </div>
              ) : null}
            </div>
            <div className="chatComposer">
              <input
                value={draft}
                onChange={(e) => setDraft(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
                placeholder={`message #${chan.name} — @mention an agent to dispatch`}
              />
              <button className="thinButton" onClick={send}><CIco name="corner-down-left" size={12} /> Send</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.ChannelsView = ChannelsView;
})();
