"use client";
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { SpinnerIcon, CheckIcon, StepXIcon, ElapsedTime } from './icons';
import { toolStepSublabel, toolStepDisplayName } from './tool-steps';
import { useDashboard } from './dashboard-context';
import { useDraftPersist } from './use-draft-persist';

const MAX_ATTACHMENTS = 8;
const DEFAULT_COMPOSER_HEIGHT = 120;
const MIN_COMPOSER_HEIGHT = 72;
const COMPOSER_HEIGHT_KEY = 'madarx:composerHeight';

function maxComposerHeight() {
  if (typeof window === 'undefined') return 520;
  return Math.max(160, Math.round(window.innerHeight * 0.72));
}
function clampComposerHeight(h) {
  return Math.min(maxComposerHeight(), Math.max(MIN_COMPOSER_HEIGHT, Math.round(h)));
}

function formatBytes(n) {
  if (!n && n !== 0) return '';
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
  return `${(n / 1024 / 1024).toFixed(1)} MB`;
}

function ChatPanel() {
  const {
    initializing,
    models,
    selectedModel,
    modelOpen,
    setModelOpen,
    usage,
    ctxLimit,
    ctxPct,
    grouped,
    pickModel,
    sessions,
    sessionId,
    openConfig,
    chat,
    mainAgent,
    setChatHidden,
    setVoiceOpen,
  } = useDashboard();

  // Composer prompt is local to ChatPanel so typing does not trigger
  // provider re-renders. This keeps CanvasSection (and every other
  // useDashboard() consumer) idle while the user composes.
  const { prompt, setPrompt } = useDraftPersist();

  const sessionsOpen = sessions.sessionsOpen;
  const setSessionsOpen = sessions.setSessionsOpen;
  const newSession = sessions.newSession;
  const openSession = sessions.openSession;
  const deleteSession = sessions.deleteSession;
  const sessionList = sessions.sessions || [];
  const feedRef = mainAgent.feedRef;
  const liveSteps = mainAgent.liveSteps;
  const busyStartTime = mainAgent.busyStartTime;
  const agentPhase = mainAgent.agentPhase;
  const busy = mainAgent.busy;
  const command = mainAgent.command;
  const stop = mainAgent.stop;
  const decideApproval = mainAgent.decideApproval;
  const hideChat = useCallback(() => setChatHidden(true), [setChatHidden]);
  const onOpenVoice = useCallback(() => setVoiceOpen(true), [setVoiceOpen]);
  const composerRef = useRef(null);
  const fileInputRef = useRef(null);
  const dragDepth = useRef(0);
  const [attachments, setAttachments] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState(null);
  const [dragOver, setDragOver] = useState(false);
  const [fullscreen, setFullscreen] = useState(false);
  const [composerHeight, setComposerHeight] = useState(DEFAULT_COMPOSER_HEIGHT);
  const [resizing, setResizing] = useState(false);

  const uploadFiles = useCallback(async (fileList) => {
    const list = Array.from(fileList || []).filter(Boolean);
    if (!list.length) return;
    setUploadError(null);
    setAttachments(prev => {
      const room = MAX_ATTACHMENTS - prev.length;
      if (room <= 0) { setUploadError(`Max ${MAX_ATTACHMENTS} files`); return prev; }
      const slice = list.slice(0, room);
      const fd = new FormData();
      slice.forEach(f => fd.append('files', f));
      setUploading(true);
      fetch('/api/orchestrator/upload', { method: 'POST', body: fd })
        .then(async res => {
          const data = await res.json().catch(() => ({}));
          if (!res.ok) { setUploadError(data.error || 'Upload failed'); return; }
          const withPreview = (data.attachments || []).map((a, i) => ({
            ...a,
            previewUrl: a.kind === 'image' && slice[i] ? URL.createObjectURL(slice[i]) : null,
          }));
          setAttachments(p => [...p, ...withPreview]);
        })
        .catch(err => setUploadError(err.message || 'Upload failed'))
        .finally(() => setUploading(false));
      return prev;
    });
  }, []);

  const removeAttachment = useCallback((id) => {
    setAttachments(prev => {
      const gone = prev.find(a => a.id === id);
      if (gone?.previewUrl) URL.revokeObjectURL(gone.previewUrl);
      return prev.filter(a => a.id !== id);
    });
  }, []);

  // Read live textarea value via ref at send-time rather than the React
  // `prompt` snapshot — avoids dropping the final keystroke under a fast
  // typing + Enter race where setPrompt has not yet flushed before the
  // submit. `command` is now ref-stable from useStreamCommand, so `send`
  // stays stable as long as `busy` is unchanged.
  const send = useCallback(() => {
    if (busy || uploading) return;
    const text = composerRef.current?.value ?? '';
    if (!text.trim() && attachments.length === 0) return;
    setPrompt('');
    const refs = attachments.map(({ id, name, mime, size, kind }) => ({ id, name, mime, size, kind }));
    command(text, refs);
    attachments.forEach(a => { if (a.previewUrl) URL.revokeObjectURL(a.previewUrl); });
    setAttachments([]);
    setUploadError(null);
  }, [busy, uploading, attachments, setPrompt, command]);

  const onPaste = useCallback((e) => {
    const items = e.clipboardData?.items;
    if (!items) return;
    const files = [];
    for (const it of items) {
      if (it.kind === 'file') { const f = it.getAsFile(); if (f) files.push(f); }
    }
    if (files.length) { e.preventDefault(); uploadFiles(files); }
  }, [uploadFiles]);

  const onDragEnter = useCallback((e) => {
    if (!e.dataTransfer?.types?.includes('Files')) return;
    e.preventDefault();
    dragDepth.current += 1;
    setDragOver(true);
  }, []);
  const onDragOver = useCallback((e) => {
    if (e.dataTransfer?.types?.includes('Files')) e.preventDefault();
  }, []);
  const onDragLeave = useCallback(() => {
    dragDepth.current = Math.max(0, dragDepth.current - 1);
    if (dragDepth.current === 0) setDragOver(false);
  }, []);
  const onDrop = useCallback((e) => {
    if (!e.dataTransfer?.files?.length) return;
    e.preventDefault();
    dragDepth.current = 0;
    setDragOver(false);
    uploadFiles(e.dataTransfer.files);
  }, [uploadFiles]);

  useEffect(() => {
    if (!fullscreen) return;
    function onKey(e) { if (e.key === 'Escape') setFullscreen(false); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [fullscreen]);

  // Restore the user's preferred input height, then keep it persisted.
  useEffect(() => {
    try {
      const saved = Number(localStorage.getItem(COMPOSER_HEIGHT_KEY));
      if (saved >= MIN_COMPOSER_HEIGHT) setComposerHeight(clampComposerHeight(saved));
    } catch {}
  }, []);
  useEffect(() => {
    try { localStorage.setItem(COMPOSER_HEIGHT_KEY, String(composerHeight)); } catch {}
  }, [composerHeight]);

  // Drag the splitter to grow/shrink the input panel (dragging up = taller).
  const onResizeStart = useCallback((e) => {
    e.preventDefault();
    const startY = e.clientY;
    const startH = composerHeight;
    setResizing(true);
    const onMove = (ev) => setComposerHeight(clampComposerHeight(startH + (startY - ev.clientY)));
    const onUp = () => {
      setResizing(false);
      window.removeEventListener('pointermove', onMove);
      window.removeEventListener('pointerup', onUp);
    };
    window.addEventListener('pointermove', onMove);
    window.addEventListener('pointerup', onUp);
  }, [composerHeight]);

  const onResizeKey = useCallback((e) => {
    if (e.key === 'ArrowUp') { e.preventDefault(); setComposerHeight(h => clampComposerHeight(h + 24)); }
    else if (e.key === 'ArrowDown') { e.preventDefault(); setComposerHeight(h => clampComposerHeight(h - 24)); }
  }, []);

  const resetComposerHeight = useCallback(() => setComposerHeight(DEFAULT_COMPOSER_HEIGHT), []);

  useEffect(() => {
    function focusComposer() {
      composerRef.current?.focus();
      composerRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' });
    }
    function createNewChat() {
      newSession();
      window.setTimeout(focusComposer, 0);
    }
    window.addEventListener('madarx:focus-composer', focusComposer);
    window.addEventListener('madarx:new-chat', createNewChat);
    return () => {
      window.removeEventListener('madarx:focus-composer', focusComposer);
      window.removeEventListener('madarx:new-chat', createNewChat);
    };
  }, [newSession]);

  return (
<div className={'chat-column' + (dragOver ? ' chat-column--dragover' : '') + (fullscreen ? ' chat-column--fullscreen' : '') + (resizing ? ' chat-column--resizing' : '')}
  onDragEnter={onDragEnter} onDragOver={onDragOver} onDragLeave={onDragLeave} onDrop={onDrop}>
  {dragOver && (
    <div className="chat-dropzone" aria-hidden="true">
      <div className="chat-dropzone-inner">
        <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 16V4M12 4L7 9M12 4l5 5"/>
          <path d="M4 16v2.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V16"/>
        </svg>
        <span>Drop files to attach</span>
      </div>
    </div>
  )}
  <section className="chat">
  <div className="chat-top">
    <div className="model-pill-wrap">
      <button className="model-pill" onClick={() => setModelOpen(o => !o)} aria-haspopup="listbox" aria-expanded={modelOpen}
        title={usage.context > 0
          ? `Context: ${(usage.context/1000).toFixed(1)}K / ${(ctxLimit/1000).toFixed(0)}K (${ctxPct}%) · cache read ${usage.cache_read || 0}`
          : 'Pick model'}>
        <span className="model-name">{models.find(m => m.id === selectedModel)?.label ?? selectedModel ?? 'Pick model'}</span>
        {usage.context > 0 ? (
          <span className="ctx-tokens">{(usage.context / 1000).toFixed(1)}K · {ctxPct}%</span>
        ) : (usage.input + usage.output) > 0 ? (
          <span className="ctx-tokens">{((usage.input + usage.output) / 1000).toFixed(1)}K ctx</span>
        ) : null}
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      {modelOpen && (
        <ul className="model-dropdown" role="listbox">
          {grouped.map(group => (
            <li key={group.engine} className="model-group">
              <span className="model-group-label">{group.label}</span>
              <ul>
                {group.items.map(m => (
                  <li key={m.id} role="option" aria-selected={m.id === selectedModel}
                      className={'model-option' + (m.id === selectedModel ? ' selected' : '')}
                      onClick={() => pickModel(m.id)}>
                    {m.engine === 'ollama' ? m.id : m.label}
                  </li>
                ))}
              </ul>
            </li>
          ))}
        </ul>
      )}
    </div>
    <div className="chat-actions">
    <div className="chat-session-menu">
      <button className="config-btn" style={{marginLeft:0}} onClick={() => setSessionsOpen(o => !o)} title="Conversations" aria-label="Conversations" aria-haspopup="listbox" aria-expanded={sessionsOpen}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="7" width="14" height="14" rx="3"/>
          <path d="M7 7V5.5A2.5 2.5 0 0 1 9.5 3H18.5A2.5 2.5 0 0 1 21 5.5V14.5A2.5 2.5 0 0 1 18.5 17H17"/>
        </svg>
      </button>
      {sessionsOpen && (
        <ul className="model-dropdown sessions-dropdown" role="listbox">
          <li className="model-option session-new-option" onClick={newSession}>
            <span>+</span> New chat
          </li>
          {sessionList.length === 0 && (
            <li className="model-option session-empty-option">No saved sessions</li>
          )}
          {sessionList.map(s => {
            const tokenStr = s.total_input_tokens + s.total_output_tokens > 0
              ? `${(((s.total_input_tokens || 0) + (s.total_output_tokens || 0)) / 1000).toFixed(1)}K`
              : '0';
            return (
              <li key={s.id} role="option" aria-selected={s.id === sessionId}
                  className={'model-option session-option' + (s.id === sessionId ? ' selected' : '')}
                  onClick={() => openSession(s.id)}>
                <span className="session-title">
                  {s.title || 'Untitled chat'}
                </span>
                <span className="session-tokens">{tokenStr}</span>
                <button
                  onClick={e => { e.stopPropagation(); deleteSession(s.id); }}
                  title="Delete session"
                  aria-label="Delete session"
                  className="session-delete-btn">
                  x
                </button>
              </li>
            );
          })}
        </ul>
      )}
    </div>
    {onOpenVoice ? (
      <button className="config-btn voice-launch" style={{marginLeft:0}} onClick={onOpenVoice} title="Open voice console" aria-label="Open voice console">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <rect x="9" y="3" width="6" height="12" rx="3"/>
          <path d="M5 11a7 7 0 0 0 14 0"/>
          <line x1="12" y1="18" x2="12" y2="21"/>
          <line x1="8" y1="21" x2="16" y2="21"/>
        </svg>
      </button>
    ) : null}
    <button
      className={'config-btn' + (fullscreen ? ' on' : '')}
      style={{marginLeft:0}}
      onClick={() => setFullscreen(f => !f)}
      title={fullscreen ? 'Exit full screen' : 'Full screen'}
      aria-label={fullscreen ? 'Exit full screen' : 'Full screen'}
      aria-pressed={fullscreen}
    >
      {fullscreen ? (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/>
        </svg>
      ) : (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
          <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>
        </svg>
      )}
    </button>
    {hideChat ? (
      <button className="config-btn" style={{marginLeft:0}} onClick={hideChat} title="Minimize" aria-label="Minimize chat">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round">
          <path d="M5 12h14"/>
        </svg>
      </button>
    ) : null}
    <button className="config-btn" style={{marginLeft:0}} onClick={openConfig} title="Settings" aria-label="Agent settings">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <line x1="4" y1="7" x2="20" y2="7"/>
        <line x1="4" y1="12" x2="20" y2="12"/>
        <line x1="4" y1="17" x2="20" y2="17"/>
        <circle cx="15" cy="7" r="2" fill="currentColor" stroke="none"/>
        <circle cx="9" cy="12" r="2" fill="currentColor" stroke="none"/>
        <circle cx="17" cy="17" r="2" fill="currentColor" stroke="none"/>
      </svg>
    </button>
    </div>
  </div>
  <div className="feed" ref={feedRef}>
    {initializing ? (
      <div className="feed-skeleton" aria-hidden="true">
        <div className="msg agent msg--skel">
          <div className="skel sk-line sk-line--w90" />
          <div className="skel sk-line sk-line--w70" />
          <div className="skel sk-line sk-line--w55" />
        </div>
        <div className="msg user msg--skel">
          <div className="skel sk-line sk-line--w65" />
          <div className="skel sk-line sk-line--w40" />
        </div>
        <div className="msg agent msg--skel">
          <div className="skel sk-line sk-line--w85" />
          <div className="skel sk-line sk-line--w50" />
        </div>
      </div>
    ) : chat.map((m, i) => {
      // Empty agent placeholder — never shown. Live activity below covers it.
      if (m.role === 'agent' && !m.text) return null;
      return (
        <div className={'msg ' + m.role + (m.streaming ? ' msg--streaming' : '')} key={i}>
          <Markdown remarkPlugins={[remarkGfm]}>{m.text}</Markdown>
          {Array.isArray(m.attachments) && m.attachments.length > 0 && (
            <div className="msg-attachments">
              {m.attachments.map(a => (
                <span key={a.id} className="msg-attach-chip" title={a.name}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M14 3v4a1 1 0 0 0 1 1h4"/>
                    <path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z"/>
                  </svg>
                  {a.name}
                </span>
              ))}
            </div>
          )}
        </div>
      );
    })}
    {liveSteps.length > 0 && (
      <div className="tool-steps">
        {liveSteps.map(step => {
          const isCli = step.name === 'claude_code_cli' || step.name === 'codex_cli';
          const sub = toolStepSublabel(step.name, step.input);
          const awaiting = step.status === 'awaiting_approval';
          return (
            <div key={step.id} className={`tool-step tool-step--${step.status}` + (isCli ? ' tool-step--cli' : '')}>
              <span className="tool-step-icon" aria-hidden="true">
                {step.status === 'running' && <SpinnerIcon />}
                {step.status === 'done' && <CheckIcon />}
                {step.status === 'approved' && <CheckIcon />}
                {(step.status === 'error' || step.status === 'denied') && <StepXIcon />}
                {awaiting && <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 4, background: '#c2452a' }} />}
              </span>
              {!isCli && <code className="tool-step-name">{toolStepDisplayName(step.name)}</code>}
              {sub && <span className="tool-step-sub">{sub}</span>}
              {awaiting && step.approval_id ? (
                <span className="tool-step-approve" style={{ marginLeft: 'auto', display: 'inline-flex', gap: 6 }}>
                  <button
                    type="button"
                    onClick={() => decideApproval(step.approval_id, 'approved', step.name)}
                    style={{ appearance: 'none', border: 0, background: '#c2452a', color: '#fff', padding: '4px 10px', borderRadius: 999, font: '600 11.5px/1 ui-sans-serif,system-ui', cursor: 'pointer' }}
                  >
                    Approve
                  </button>
                  <button
                    type="button"
                    onClick={() => decideApproval(step.approval_id, 'denied', step.name)}
                    style={{ appearance: 'none', border: '1px solid rgba(17,19,24,.16)', background: '#fff', color: '#313740', padding: '4px 10px', borderRadius: 999, font: '600 11.5px/1 ui-sans-serif,system-ui', cursor: 'pointer' }}
                  >
                    Deny
                  </button>
                </span>
              ) : null}
            </div>
          );
        })}
        {busy && busyStartTime && (agentPhase === 'synthesis' || agentPhase === 'tool') && (
          <div className="tool-step-elapsed">
            <ElapsedTime startTime={busyStartTime} />
          </div>
        )}
      </div>
    )}
    {busy && liveSteps.length === 0 && <div className="typing-indicator"><span /><span /><span /></div>}
  </div>
  </section>
  <div
    className="composer-resizer"
    role="separator"
    aria-orientation="horizontal"
    aria-label="Resize the message input"
    aria-valuenow={composerHeight}
    tabIndex={0}
    onPointerDown={onResizeStart}
    onKeyDown={onResizeKey}
    onDoubleClick={resetComposerHeight}
    title="Drag to resize · double-click to reset"
  >
    <span className="composer-resizer-grip" aria-hidden="true" />
  </div>
  <section className="composer-panel" style={{ height: composerHeight }} aria-label="Message input">
  <form className="composer" onSubmit={e => { e.preventDefault(); send(); }}>
    <input
      ref={fileInputRef}
      type="file"
      multiple
      hidden
      accept="image/png,image/jpeg,image/gif,image/webp,application/pdf,text/*,.md,.markdown,.csv,.tsv,.json,.jsonl,.log,.yaml,.yml,.xml,.html,.css,.js,.jsx,.ts,.tsx,.mjs,.cjs,.py,.rb,.go,.rs,.java,.c,.h,.cpp,.cs,.php,.sh,.sql,.toml,.ini"
      onChange={e => { uploadFiles(e.target.files); e.target.value = ''; }}
    />
    <div className="composer-field">
      {(attachments.length > 0 || uploading || uploadError) && (
        <div className="composer-attachments">
          {attachments.map(a => (
            <span key={a.id} className="attach-chip" title={`${a.name} · ${formatBytes(a.size)}`}>
              {a.previewUrl ? (
                <img className="attach-chip-thumb" src={a.previewUrl} alt="" />
              ) : (
                <svg className="attach-chip-icon" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <path d="M14 3v4a1 1 0 0 0 1 1h4"/>
                  <path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z"/>
                </svg>
              )}
              <span className="attach-chip-name">{a.name}</span>
              <button type="button" className="attach-chip-x" onClick={() => removeAttachment(a.id)} aria-label={`Remove ${a.name}`}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
              </button>
            </span>
          ))}
          {uploading && <span className="attach-uploading">Uploading…</span>}
          {uploadError && <span className="attach-error">{uploadError}</span>}
        </div>
      )}
      <textarea
        ref={composerRef}
        data-madarx-composer="true"
        value={prompt}
        onChange={e => setPrompt(e.target.value)}
        onPaste={onPaste}
        onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        placeholder="Start fresh: ask the main agent to create the first agent, report, schedule, or UI task…"
        rows={3}
      />
    </div>
    <div className="composer-actions">
      <button
        type="button"
        className="attach-btn"
        onClick={() => fileInputRef.current?.click()}
        disabled={busy}
        title="Attach files"
        aria-label="Attach files"
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21.4 11.05 12.25 20.2a5.5 5.5 0 0 1-7.78-7.78l9.2-9.2a3.67 3.67 0 0 1 5.18 5.18l-9.2 9.19a1.83 1.83 0 0 1-2.59-2.59l8.49-8.48"/>
        </svg>
      </button>
      {busy ? (
        <button
          type="button"
          className="send-btn send-btn--stop"
          onClick={e => { e.preventDefault(); if (stop) stop(); }}
          aria-label="Stop main agent"
          title="Stop main agent"
        >
          <svg width="16" height="16" viewBox="0 0 18 18" fill="none">
            <rect x="5" y="5" width="8" height="8" rx="1.5" fill="currentColor" />
          </svg>
        </button>
      ) : (
        <button className="send-btn" disabled={(!prompt.trim() && attachments.length === 0) || uploading} aria-label="Send">
          <svg width="16" height="16" viewBox="0 0 18 18" fill="none">
            <path d="M9 14V4M9 4L4.5 8.5M9 4L13.5 8.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      )}
    </div>
  </form>
  </section>
</div>
  );
}

export default memo(ChatPanel);
