/* global React, RIcons, GENERAL_CHAT_EXCHANGE, GENERAL_CHAT_SUGGESTION, CHAT_SESSIONS */
// Tab chat — vitals / health questions (not tied to a signed round).
// ChatSidebar is rendered by app.jsx (outside .scroll) so it spans full phone height.

const { useState, useEffect, useRef } = React;

const CARE_AGENT_LABEL = 'Care Agent';

// ─── Hamburger icon (not in RIcons set) ───────────────────
function HamburgerIcon({ size = 18 }) {
  return (
    <svg width={size} height={Math.round(size * 0.78)} viewBox="0 0 18 14" fill="none" aria-hidden="true">
      <rect y="0"  width="18" height="2" rx="1" fill="currentColor"/>
      <rect y="6"  width="13" height="2" rx="1" fill="currentColor"/>
      <rect y="12" width="18" height="2" rx="1" fill="currentColor"/>
    </svg>
  );
}

// ─── Chat Sidebar ─────────────────────────────────────────
// Rendered by app.jsx directly inside .phone-inner so it covers full height.
const SIDEBAR_GROUPS = ['Today', 'Yesterday', 'This week', 'Earlier'];

function ChatSidebar({ open, onClose, sessions, activeId, onSelect, onNew }) {
  return (
    <>
      <div className={`chat-scrim ${open ? 'open' : ''}`} onClick={onClose} aria-hidden="true" />
      <div className={`chat-sidebar ${open ? 'open' : ''}`} role="dialog" aria-label="Conversations">

        <div className="chat-sidebar-header">
          <div className="chat-sidebar-brand">
            <RIcons.Chat size={14} />
            Conversations
          </div>
          <button className="chat-sidebar-close" onClick={onClose} aria-label="Close">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
              <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>

        <div style={{ padding: '10px 14px 4px' }}>
          <button className="chat-sidebar-new" onClick={onNew}>
            <RIcons.Plus size={15} />
            New conversation
          </button>
        </div>

        <div className="chat-sidebar-list">
          {SIDEBAR_GROUPS.map(group => {
            const items = sessions.filter(s => s.group === group);
            if (!items.length) return null;
            return (
              <div key={group} className="chat-sidebar-group">
                <div className="chat-sidebar-group-label">{group}</div>
                {items.map(s => (
                  <button
                    key={s.id}
                    className={`chat-sidebar-item ${s.id === activeId ? 'active' : ''}`}
                    onClick={() => { window.haptics?.trigger('selection'); onSelect(s); onClose(); }}
                  >
                    <div className="chat-sidebar-item-icon">
                      {s.type === 'round' ? <RIcons.Seal size={12} /> : <RIcons.Sparkles size={12} />}
                    </div>
                    <div className="chat-sidebar-item-body">
                      <div className="chat-sidebar-item-title">{s.title}</div>
                      <div className="chat-sidebar-item-preview">{s.preview}</div>
                    </div>
                    <div className="chat-sidebar-item-time">{s.time}</div>
                  </button>
                ))}
              </div>
            );
          })}
        </div>

        <div className="chat-sidebar-footer">
          <div className="chat-sidebar-footer-brand">
            <RIcons.Sparkles size={11} />
            Care Agent
          </div>
          <div className="chat-sidebar-footer-sub">Conversations are private and linked to Nora's profile</div>
        </div>
      </div>
    </>
  );
}

// ─── Care Chat Screen ─────────────────────────────────────
// sidebarOpen / setSidebarOpen / activeSession / setActiveSession are lifted to app.jsx
// so the sidebar can be rendered outside .scroll at phone-inner level.
function CareChatScreen({ onAddToRound, sidebarOpen, setSidebarOpen, activeSession, setActiveSession }) {
  const [revealed, setRevealed] = useState(0);
  const [typing, setTyping] = useState(false);
  const [showSuggestion, setShowSuggestion] = useState(false);
  const threadRef = useRef(null);

  useEffect(() => {
    if (revealed >= GENERAL_CHAT_EXCHANGE.length) {
      const t = setTimeout(() => setShowSuggestion(true), 900);
      return () => clearTimeout(t);
    }
    const next = GENERAL_CHAT_EXCHANGE[revealed];
    if (next.from === 'agent') {
      setTyping(true);
      const t = setTimeout(() => { setTyping(false); setRevealed((r) => r + 1); }, 1400);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setRevealed((r) => r + 1), 650);
    return () => clearTimeout(t);
  }, [revealed]);

  useEffect(() => {
    const el = threadRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [revealed, typing, showSuggestion]);

  return (
    <div className="discuss-page care-chat-page" data-screen-label="Care chat">
      <div className="care-chat-hero">
        <div className="care-chat-top">
          <button
            className="chat-menu-btn"
            onClick={() => { window.haptics?.trigger('selection'); setSidebarOpen(true); }}
            aria-label="Open conversations"
          >
            <HamburgerIcon size={18} />
          </button>
          <h1 className="care-chat-title">Chat</h1>
          <button className="chat-newchat-btn" onClick={() => {}} aria-label="New conversation">
            <RIcons.Plus size={18} />
          </button>
        </div>

        <div className="care-chat-session-tag">
          <span className="care-chat-session-icon">
            {activeSession.type === 'round' ? <RIcons.Seal size={11} /> : <RIcons.Sparkles size={11} />}
          </span>
          <span className="care-chat-session-title">{activeSession.title}</span>
        </div>

        <div className="care-chat-vitals">
          <span className="cv-pill"><RIcons.Heart size={12} /> 118 bpm</span>
          <span className="cv-pill"><RIcons.Lungs size={12} /> 97% SpO₂</span>
          <span className="cv-pill cv-pill--muted">Updated just now</span>
        </div>
      </div>

      <div className="discuss-thread" ref={threadRef}>
        {GENERAL_CHAT_EXCHANGE.slice(0, revealed).map((m, i) => (
          <div key={i} className={`dmsg ${m.from} dmsg-in`}>
            {m.from === 'agent' && (
              <div className="dmsg-by dmsg-by--care"><RIcons.Sparkles size={10} /> {CARE_AGENT_LABEL}</div>
            )}
            <div className="dmsg-bubble">{m.text}</div>
          </div>
        ))}

        {typing && (
          <div className="dmsg agent dmsg-in">
            <div className="dmsg-by dmsg-by--care"><RIcons.Sparkles size={10} /> {CARE_AGENT_LABEL}</div>
            <div className="dmsg-bubble typing-bubble">
              <span className="tdot" /><span className="tdot" /><span className="tdot" />
            </div>
          </div>
        )}

        {showSuggestion && (
          <div className="chat-suggest-card dmsg-in">
            <div className="dmsg-by dmsg-by--care"><RIcons.Sparkles size={10} /> {CARE_AGENT_LABEL}</div>
            <div className="chat-suggest-inner">
              <div className="cs-kicker">Suggested for tomorrow&apos;s round</div>
              <p className="cs-draft">{GENERAL_CHAT_SUGGESTION.draft}</p>
              <p className="cs-note">{GENERAL_CHAT_SUGGESTION.note}</p>
              <button type="button" className="cs-cta" onClick={onAddToRound}>
                <RIcons.Plus size={15} />
                Add to tomorrow&apos;s round
              </button>
            </div>
          </div>
        )}
      </div>

      <div className="discuss-input">
        <div className="di-field">Ask about vitals or sleep…</div>
        <button type="button" className="di-send" aria-label="Send"><RIcons.ChevronRight /></button>
      </div>
    </div>
  );
}

const RChat = { CareChatScreen, ChatSidebar };
