// Assistant — multi-chat AI with date separators and chat management

const asstStyles = {
  // Suggestion chips
  suggestTitle: {
    font: "500 12px 'Estedad', sans-serif", color: 'var(--ink-3)',
    letterSpacing: '0.06em', textTransform: 'uppercase', margin: '12px 2px 10px',
  },
  suggestRow: { display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 18 },
  suggestCard: {
    background: 'var(--surface)', border: '1px solid var(--c-border-xs)',
    borderRadius: 14, padding: '12px 14px',
    display: 'flex', alignItems: 'center', gap: 10,
    cursor: 'pointer', textAlign: 'right', width: '100%',
  },
  suggestIcon: {
    width: 32, height: 32, borderRadius: 8,
    background: 'var(--firoozeh-soft)', color: 'var(--firoozeh-deep)',
    display: 'grid', placeItems: 'center', flex: 'none',
  },
  suggestText: { font: "400 14px/1.45 'Estedad', sans-serif", color: 'var(--ink)', flex: 1 },

  // Messages
  msgRow: { display: 'flex', marginBottom: 10 },
  me:   { justifyContent: 'flex-start' },
  them: { justifyContent: 'flex-end' },
  bubble: {
    maxWidth: '82%', padding: '10px 14px',
    font: "400 15px/1.6 'Estedad', sans-serif", borderRadius: 16,
  },
  bubbleMe:   { background: 'var(--firoozeh)', color: '#fff', borderBottomRightRadius: 4 },
  bubbleThem: {
    background: 'var(--surface)', color: 'var(--ink)',
    border: '1px solid var(--c-border-xs)', borderBottomLeftRadius: 4,
  },
  metaBelow: {
    font: "500 11px 'Estedad', sans-serif",
    color: 'var(--ink-3)', margin: '2px 8px 0',
  },

  typing: { display: 'flex', gap: 5, padding: '6px 4px' },
  dot: { width: 6, height: 6, background: 'var(--ink-3)', borderRadius: '50%' },

  // Input bar
  inputBar: {
    display: 'flex', alignItems: 'center', gap: 8, padding: 6,
    background: 'var(--surface)', border: '1px solid var(--c-border-sm)',
    borderRadius: 999, boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
  },
  inputField: {
    flex: 1, background: 'transparent', border: 'none', outline: 'none',
    font: "400 15px/1.4 'Estedad', sans-serif", color: 'var(--ink)',
    minWidth: 0, textAlign: 'right', direction: 'rtl', padding: '6px 10px',
  },
  sendBtn: {
    width: 38, height: 38, borderRadius: 999,
    background: 'var(--ink-4)', color: 'var(--paper)',
    display: 'grid', placeItems: 'center',
    border: 'none', cursor: 'pointer', flex: 'none',
    transition: 'background 120ms ease-out',
  },
  sendBtnActive: { background: 'var(--firoozeh)', color: '#fff' },

  // Header (shared between chat and list views)
  hdr: {
    display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px',
    borderBottom: '1px solid var(--c-border-xs)', flexShrink: 0, direction: 'rtl',
  },
  hdrTitle: {
    font: "500 15px 'Estedad', sans-serif", color: 'var(--ink)',
    flex: 1, textAlign: 'center', direction: 'rtl',
    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
  },
  hdrBtn: {
    width: 36, height: 36, borderRadius: 999, background: 'var(--paper-2)',
    border: 'none', cursor: 'pointer', color: 'var(--ink-2)',
    display: 'grid', placeItems: 'center', flex: 'none',
  },
  hdrBtnPrimary: { background: 'var(--firoozeh)', color: '#fff' },

  // Chat list
  chatList: { flex: 1, overflow: 'auto', direction: 'rtl' },
  chatItem: {
    display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px',
    borderBottom: '1px solid var(--c-border-xs)', cursor: 'pointer',
    transition: 'background 80ms', direction: 'rtl',
  },
  chatItemActive: { background: 'var(--firoozeh-soft)' },
  chatDot: { width: 8, height: 8, borderRadius: '50%', background: 'var(--firoozeh)', flex: 'none' },
  chatItemBody: { flex: 1, minWidth: 0 },
  chatItemTitle: { font: "500 14px/1.3 'Estedad', sans-serif", color: 'var(--ink)', marginBottom: 2 },
  chatItemPreview: {
    font: "400 12px 'Estedad', sans-serif", color: 'var(--ink-3)',
    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
  },
  chatItemMeta: {
    display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, flex: 'none',
  },
  chatItemDate: { font: "400 10.5px 'Estedad', sans-serif", color: 'var(--ink-4)', whiteSpace: 'nowrap' },
  chatItemCount: {
    font: "500 10px 'Estedad', sans-serif", color: 'var(--firoozeh-deep)',
    background: 'var(--firoozeh-soft)', padding: '1px 6px', borderRadius: 999,
  },

  // Date separator
  sep: { display: 'flex', alignItems: 'center', gap: 8, margin: '18px 0 12px', direction: 'rtl' },
  sepLine: { flex: 1, height: 1, background: 'var(--c-tint-sm)' },
  sepTxt: {
    font: "400 11px 'Estedad', sans-serif", color: 'var(--ink-3)',
    whiteSpace: 'nowrap', background: 'var(--paper-2)',
    padding: '2px 10px', borderRadius: 999,
  },
};

// ── Date helpers ─────────────────────────────────────────────────────
const insertDateSeps = msgs => {
  const result = [];
  let lastKey = null;
  for (const msg of msgs) {
    const d = new Date(msg.timestamp || 0);
    const k = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
    if (k !== lastKey) {
      result.push({ _sep: true, key: 'sep-' + k, date: d });
      lastKey = k;
    }
    result.push(msg);
  }
  return result;
};

const faDateSep = d => {
  if (!d || d.getFullYear() < 2000) return '';
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const yesterday = new Date(today.getTime() - 86400000);
  const msgDay = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  if (msgDay.getTime() === today.getTime()) return 'امروز';
  if (msgDay.getTime() === yesterday.getTime()) return 'دیروز';
  return new Intl.DateTimeFormat('fa-IR', { weekday: 'long', month: 'long', day: 'numeric' }).format(d);
};

const faDateShort = ts =>
  ts ? new Intl.DateTimeFormat('fa-IR', { month: 'long', day: 'numeric' }).format(new Date(ts)) : '';

// ── Inline markdown renderer ─────────────────────────────────────────
function renderInline(text, key) {
  const parts = [];
  const re = /(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`|\[([^\]]+)\]\((https?:\/\/[^)]+)\))/g;
  let last = 0, m, i = 0;
  while ((m = re.exec(text)) !== null) {
    if (m.index > last) parts.push(text.slice(last, m.index));
    if (m[2] != null) parts.push(<strong key={i++}>{m[2]}</strong>);
    else if (m[3] != null) parts.push(<em key={i++}>{m[3]}</em>);
    else if (m[4] != null) parts.push(
      <code key={i++} style={{ background: 'rgba(27,26,23,0.08)', borderRadius: 4, padding: '1px 5px', fontSize: '0.9em', fontFamily: 'monospace' }}>{m[4]}</code>
    );
    else if (m[5] != null) parts.push(
      <a key={i++} href={m[6]} target="_blank" rel="noopener noreferrer"
        style={{ color: 'var(--firoozeh)', textDecoration: 'underline', wordBreak: 'break-all' }}>{m[5]}</a>
    );
    last = m.index + m[0].length;
  }
  if (last < text.length) parts.push(text.slice(last));
  return parts;
}

function MarkdownBubble({ text }) {
  const lines = text.split('\n');
  const nodes = [];
  let listBuf = [], listType = null;
  let inCode = false, codeLang = '', codeBuf = [];
  let tableBuf = [];

  const flushList = () => {
    if (!listBuf.length) return;
    const Tag = listType === 'ol' ? 'ol' : 'ul';
    nodes.push(
      <Tag key={nodes.length} style={{ margin: '6px 0', paddingInlineStart: 20, lineHeight: 1.9 }}>
        {listBuf.map((item, idx) => <li key={idx}>{renderInline(item)}</li>)}
      </Tag>
    );
    listBuf = []; listType = null;
  };

  const flushTable = () => {
    if (!tableBuf.length) return;
    const rows = tableBuf.filter(r => !r.match(/^\|[-\s|:]+\|$/));
    nodes.push(
      <div key={nodes.length} style={{ overflowX: 'auto', margin: '8px 0' }}>
        <table style={{ borderCollapse: 'collapse', width: '100%', fontSize: 13, direction: 'rtl' }}>
          <tbody>
            {rows.map((row, ri) => {
              const cells = row.split('|').slice(1, -1).map(c => c.trim());
              const Tag = ri === 0 ? 'th' : 'td';
              return (
                <tr key={ri}>
                  {cells.map((cell, ci) => (
                    <Tag key={ci} style={{ border: '1px solid rgba(27,26,23,0.14)', padding: '6px 10px', textAlign: 'right', fontWeight: ri === 0 ? 600 : 400, background: ri === 0 ? 'rgba(27,26,23,0.04)' : 'transparent' }}>
                      {renderInline(cell)}
                    </Tag>
                  ))}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
    tableBuf = [];
  };

  lines.forEach((line, i) => {
    if (line.startsWith('```')) {
      if (!inCode) {
        flushList(); flushTable();
        inCode = true; codeLang = line.slice(3).trim(); codeBuf = [];
      } else {
        const code = codeBuf.join('\n');
        nodes.push(
          <div key={nodes.length} style={{ position: 'relative', margin: '8px 0' }}>
            {codeLang && <span style={{ position: 'absolute', top: 6, insetInlineEnd: 8, font: "400 11px monospace", color: 'rgba(27,26,23,0.4)' }}>{codeLang}</span>}
            <pre style={{ margin: 0, padding: '12px 14px', background: 'var(--c-tint-xs)', borderRadius: 10, overflowX: 'auto', fontFamily: 'monospace', fontSize: 13, lineHeight: 1.6, direction: 'ltr', textAlign: 'left' }}>
              <code>{code}</code>
            </pre>
          </div>
        );
        inCode = false; codeLang = ''; codeBuf = [];
      }
      return;
    }
    if (inCode) { codeBuf.push(line); return; }

    if (line.trim().startsWith('|') && line.trim().endsWith('|')) {
      flushList(); tableBuf.push(line.trim()); return;
    } else if (tableBuf.length) {
      flushTable();
    }

    const ulMatch = line.match(/^[-*•]\s+(.+)/);
    const olMatch = line.match(/^\d+[.)]\s+(.+)/);
    const h3Match = line.match(/^###\s+(.+)/);
    const h2Match = line.match(/^##\s+(.+)/);
    const h1Match = line.match(/^#\s+(.+)/);
    const hrMatch = line.match(/^---+$/);
    if (ulMatch) { if (listType === 'ol') flushList(); listType = 'ul'; listBuf.push(ulMatch[1]); }
    else if (olMatch) { if (listType === 'ul') flushList(); listType = 'ol'; listBuf.push(olMatch[1]); }
    else {
      flushList();
      if (h1Match || h2Match || h3Match) {
        const lvl = h1Match ? 1 : h2Match ? 2 : 3;
        const content = (h1Match || h2Match || h3Match)[1];
        nodes.push(<div key={i} style={{ font: `600 ${['18px','16px','14px'][lvl-1]}/1.5 'Estedad', sans-serif`, margin: '10px 0 4px', color: 'var(--ink)' }}>{renderInline(content)}</div>);
      } else if (hrMatch) {
        nodes.push(<hr key={i} style={{ border: 'none', borderTop: '1px solid var(--c-border-sm)', margin: '8px 0' }} />);
      } else if (line.trim() === '') {
        nodes.push(<div key={i} style={{ height: 6 }} />);
      } else {
        nodes.push(<p key={i} style={{ margin: '2px 0', lineHeight: 1.7 }}>{renderInline(line)}</p>);
      }
    }
  });
  flushList(); flushTable();
  return <div style={{ font: "400 15px 'Estedad', sans-serif", color: 'inherit' }}>{nodes}</div>;
}

function TypingBubble() {
  return (
    <div className="sb-message-motion" style={{ ...asstStyles.msgRow, ...asstStyles.them }}>
      <div style={{ ...asstStyles.bubble, ...asstStyles.bubbleThem, padding: '12px 14px' }}>
        <div style={asstStyles.typing}>
          {[0, 0.16, 0.32].map((d, i) => (
            <i key={i} style={{ ...asstStyles.dot, animation: `sbTyping 1.4s ease-in-out ${d}s infinite` }} />
          ))}
        </div>
      </div>
      <style>{`@keyframes sbTyping { 0%,80%,100%{opacity:.3;transform:translateY(0)} 40%{opacity:1;transform:translateY(-3px)} }`}</style>
    </div>
  );
}

function ChatInput({ onSend, disabled, maxLength = 2000 }) {
  const { Icons } = window;
  const [text, setText] = React.useState('');
  const inputRef = React.useRef(null);

  const send = () => {
    const t = text.trim().slice(0, maxLength);
    if (!t || disabled) return;
    onSend(t);
    setText('');
    inputRef.current?.focus();
  };

  const hasText = text.trim().length > 0;
  const near = text.length > maxLength - 200;
  return (
    <div style={asstStyles.inputBar}>
      <input
        ref={inputRef}
        style={asstStyles.inputField}
        value={text}
        onChange={e => setText(e.target.value.slice(0, maxLength))}
        onKeyDown={e => e.key === 'Enter' && send()}
        placeholder="پیامت رو بنویس…"
        maxLength={maxLength}
        disabled={disabled}
      />
      {near && (
        <span style={{ font: "500 11px 'Estedad', sans-serif", color: 'var(--ink-3)', alignSelf: 'center', whiteSpace: 'nowrap' }}>
          {String(maxLength - text.length).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d])}
        </span>
      )}
      <button
        style={{ ...asstStyles.sendBtn, ...(hasText && !disabled ? asstStyles.sendBtnActive : {}) }}
        onClick={send} disabled={!hasText || disabled} aria-label="ارسال"
      >
        <Icons.ArrowUp size={18} />
      </button>
    </div>
  );
}

// Read-only banner shown when viewing an archived (past-day / capped) chat
function ArchivedBar({ onStartToday }) {
  return (
    <div style={{ padding: '12px 16px calc(12px + env(safe-area-inset-bottom))', borderTop: '1px solid var(--c-border-xs)', direction: 'rtl' }}>
      <div style={{ font: "400 12.5px/1.6 'Estedad', sans-serif", color: 'var(--ink-3)', textAlign: 'center', marginBottom: 8 }}>
        این گفتگو بایگانی شده و ادامه ندارد.
      </div>
      <button onClick={onStartToday}
        style={{ width: '100%', padding: '12px', borderRadius: 12, border: 'none', cursor: 'pointer', background: 'var(--firoozeh)', color: '#fff', font: "600 14px 'Estedad', sans-serif" }}>
        شروع گفتگوی امروز
      </button>
    </div>
  );
}

// ── Chat list item ────────────────────────────────────────────────
function ChatListItem({ chat, active, archived, onSelect, onDelete }) {
  const { Icons } = window;
  const lastMsg = chat.messages[chat.messages.length - 1];
  const msgCount = chat.messages.length;
  return (
    <div
      className="sb-animated-card"
      style={{ ...asstStyles.chatItem, ...(active ? asstStyles.chatItemActive : {}), ...(archived ? { opacity: 0.72 } : {}) }}
      onClick={() => onSelect(chat.id)}
    >
      <span style={{ ...asstStyles.chatDot, background: active ? 'var(--firoozeh)' : 'var(--ink-4)' }} />
      <div style={asstStyles.chatItemBody}>
        <div style={asstStyles.chatItemTitle}>
          {chat.title || 'گفتگوی جدید'}
          {archived && <span style={{ marginRight: 6, font: "500 10px 'Estedad', sans-serif", color: 'var(--ink-3)', background: 'var(--paper-2)', padding: '2px 6px', borderRadius: 6 }}>بایگانی</span>}
        </div>
        {lastMsg && (
          <div style={asstStyles.chatItemPreview}>
            {lastMsg.from === 'me' ? 'شما: ' : ''}{lastMsg.text.slice(0, 45)}
          </div>
        )}
      </div>
      <div style={asstStyles.chatItemMeta}>
        <span style={asstStyles.chatItemDate}>{faDateShort(chat.updatedAt)}</span>
        {msgCount > 0 && (
          <span style={asstStyles.chatItemCount}>
            {String(msgCount).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d])} پیام
          </span>
        )}
      </div>
      <button
        style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-4)', padding: 4, display: 'grid', placeItems: 'center', flex: 'none' }}
        onClick={e => { e.stopPropagation(); (window.confirmAction || ((m, f) => f()))('این گفتگو حذف شود؟', () => onDelete(chat.id)); }}
        aria-label="حذف"
      >
        <Icons.Trash size={14} />
      </button>
    </div>
  );
}

// ── Chat view ─────────────────────────────────────────────────────
function ChatView({ chat, typing, onAsk, onRetry, onShowList, onNewChat, onStartToday, archived, maxInput, isDesktop }) {
  const { Icons } = window;
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [chat?.messages?.length, typing]);

  const px = isDesktop ? '24px' : '16px';
  const inputPb = isDesktop ? '20px' : '108px';
  const items = insertDateSeps(chat?.messages || []);
  const userAsked = (chat?.messages || []).some(m => m.from === 'me');

  const suggestions = [
    { q: 'سخت خوابم می‌بره، یه روتین برام بساز', Icon: Icons.Sparkle },
    { q: 'چطور می‌تونم کارهامو بهتر اولویت‌بندی کنم؟', Icon: Icons.CheckCircle },
    { q: 'می‌خوام ورزش رو شروع کنم، کمکم کن', Icon: Icons.TrendUp },
  ];

  return (
    <div className="sb-flow" style={{ height: '100%', display: 'flex', flexDirection: 'column', direction: 'rtl' }}>

      {/* Header */}
      <div style={asstStyles.hdr}>
        <button style={asstStyles.hdrBtn} onClick={onShowList} aria-label="لیست گفتگوها">
          <Icons.Filter size={16} />
        </button>
        <span style={asstStyles.hdrTitle}>{chat?.title || 'گفتگوی جدید'}</span>
        <button style={{ ...asstStyles.hdrBtn, ...asstStyles.hdrBtnPrimary }} onClick={onNewChat} aria-label="گفتگوی جدید">
          <Icons.Plus size={16} />
        </button>
      </div>

      {/* Messages */}
      <div ref={scrollRef} className="sb-flow" style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: `8px ${px} 12px`, direction: 'rtl' }}>

        {items.map((item, i) => {
          if (item._sep) {
            const label = faDateSep(item.date);
            if (!label) return null;
            return (
              <div key={item.key} style={asstStyles.sep}>
                <div style={asstStyles.sepLine} />
                <span style={asstStyles.sepTxt}>{label}</span>
                <div style={asstStyles.sepLine} />
              </div>
            );
          }
          const m = item;
          return (
            <div key={m.id || i} className="sb-message-motion">
              <div style={{ ...asstStyles.msgRow, ...(m.from === 'me' ? asstStyles.me : asstStyles.them) }}>
                <div style={{ ...asstStyles.bubble, ...(m.from === 'me' ? asstStyles.bubbleMe : asstStyles.bubbleThem),
                  ...(m.error ? { background: 'rgba(178,58,72,0.08)', border: '1px solid rgba(178,58,72,0.2)', color: 'var(--garnet)' } : {}) }}>
                  {m.from === 'me' ? m.text : <MarkdownBubble text={m.text} />}
                  {m.error && m.retry && onRetry && (
                    <button
                      onClick={() => onRetry(chat.id, m.id)}
                      style={{
                        marginTop: 8, display: 'inline-flex', alignItems: 'center', gap: 6,
                        background: 'var(--garnet)', color: '#fff', border: 'none', cursor: 'pointer',
                        borderRadius: 999, padding: '6px 14px',
                        font: "500 13px 'Estedad', sans-serif",
                      }}
                    >تلاش مجدد</button>
                  )}
                </div>
              </div>
              {m.meta && (
                <div style={{ ...asstStyles.metaBelow, textAlign: m.from === 'me' ? 'right' : 'left' }}>
                  {m.meta}
                </div>
              )}
            </div>
          );
        })}

        {typing && <TypingBubble />}

        {!userAsked && !typing && !archived && (
          <>
            <div style={asstStyles.suggestTitle}>پیشنهاد سوال</div>
            <div style={asstStyles.suggestRow}>
              {suggestions.map((s, i) => (
                <button key={i} style={asstStyles.suggestCard} onClick={() => onAsk(s.q)}>
                  <div style={asstStyles.suggestIcon}><s.Icon size={16} /></div>
                  <span style={asstStyles.suggestText}>{s.q}</span>
                </button>
              ))}
            </div>
          </>
        )}
      </div>

      {/* Input (or read-only banner for archived chats) */}
      {archived ? (
        <div style={{ flexShrink: 0, paddingBottom: isDesktop ? 0 : 96 }}>
          <ArchivedBar onStartToday={onStartToday} />
        </div>
      ) : (
        <div style={{ padding: `10px ${px} ${inputPb}`, flexShrink: 0 }}>
          <ChatInput onSend={onAsk} disabled={typing} maxLength={maxInput} />
        </div>
      )}
    </div>
  );
}

// ── Chat list view ────────────────────────────────────────────────
function ChatListView({ chats, activeChatId, onSelect, onNew, onDelete, onBack, chatArchived }) {
  const { Icons } = window;
  const sorted = [...(chats || [])].sort((a, b) => b.updatedAt - a.updatedAt);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', direction: 'rtl' }}>
      {/* Header */}
      <div style={asstStyles.hdr}>
        <button style={asstStyles.hdrBtn} onClick={onBack} aria-label="بازگشت">
          <Icons.Chev size={20} />
        </button>
        <span style={{ ...asstStyles.hdrTitle, textAlign: 'right' }}>همه گفتگوها</span>
        <button style={{ ...asstStyles.hdrBtn, ...asstStyles.hdrBtnPrimary }} onClick={() => { onNew(); onBack(); }} aria-label="گفتگوی جدید">
          <Icons.Plus size={16} />
        </button>
      </div>

      {/* List */}
      <div style={asstStyles.chatList}>
        {sorted.map(chat => (
          <ChatListItem key={chat.id} chat={chat} active={chat.id === activeChatId}
            archived={chatArchived ? chatArchived(chat) : false}
            onSelect={id => { onSelect(id); onBack(); }}
            onDelete={onDelete}
          />
        ))}
        {sorted.length === 0 && (
          <div style={{ textAlign: 'center', padding: '48px 20px', color: 'var(--ink-3)', font: "400 14px 'Estedad', sans-serif" }}>
            هنوز گفتگویی شروع نشده
          </div>
        )}
      </div>
    </div>
  );
}

// ── Main Assistant component ──────────────────────────────────────
function Assistant({ chats, activeChatId, typing, onAsk, onRetry, onNewChat, onSelectChat, onDeleteChat, onStartToday, chatArchived, maxInput, isDesktop }) {
  const [view, setView] = React.useState('chat');
  const activeChat = (chats || []).find(c => c.id === activeChatId);
  const archived = chatArchived ? chatArchived(activeChat) : false;

  if (view === 'list') {
    return (
      <ChatListView
        chats={chats}
        activeChatId={activeChatId}
        onSelect={(id) => { onSelectChat(id); setView('chat'); }}
        onNew={() => { onNewChat(); setView('chat'); }}
        onDelete={onDeleteChat}
        onBack={() => setView('chat')}
        chatArchived={chatArchived}
      />
    );
  }

  return (
    <ChatView
      chat={activeChat}
      typing={typing}
      onAsk={onAsk}
      onRetry={onRetry}
      onShowList={() => setView('list')}
      onNewChat={onNewChat}
      onStartToday={onStartToday}
      archived={archived}
      maxInput={maxInput}
      isDesktop={isDesktop}
    />
  );
}

window.Assistant = Assistant;
