'use client';

// Mira 右側常駐對話 dock（桌機，所有頁簽都在；手機隱藏改走 /mira/chat 單頁）
// 可收合，狀態存 localStorage。SDD: design.md §3.6.5 對話內建化

import { useEffect, useState } from 'react';
import MiraChat from './MiraChat';

const LS_KEY = 'mira-chat-dock-open';

export default function MiraChatDock() {
  const [open, setOpen] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    setOpen(localStorage.getItem(LS_KEY) === '1');
  }, []);

  const toggle = () => {
    setOpen(o => {
      const next = !o;
      localStorage.setItem(LS_KEY, next ? '1' : '0');
      return next;
    });
  };

  // SSR/首渲不輸出，避免 hydration 閃爍
  if (!mounted) return null;

  return (
    <div className={`mira-chat-dock${open ? ' is-open' : ''}`}>
      {open ? (
        <>
          <header className="mira-chat-dock-head">
            <span>💬 Mira 對話</span>
            <button type="button" className="mira-chat-dock-close" onClick={toggle} aria-label="收合對話">✕</button>
          </header>
          <MiraChat compact />
        </>
      ) : (
        <button type="button" className="mira-chat-dock-fab" onClick={toggle} title="開啟 Mira 對話">
          💬
        </button>
      )}
    </div>
  );
}
