// app/panels.jsx — 대화 히스토리 사이드바 + FAQ 등록·관리 화면
// window.RibbonPanels 로 노출.

const { useState: useStateP } = React;
const { Icon: IconP, I: IP, Spike: SpikeP } = window.RibbonChat;

// ── 히스토리 / 세션 사이드바 (실 세션: 복원·삭제) ────────────
function SessionRow({ s, active, onSelect, onDelete }) {
  const [hov, setHov] = useStateP(false);
  const rel = window.RibbonChat.relTime ? window.RibbonChat.relTime(s.ts) : '';
  return (
    <div className="rb-session" onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      onClick={() => onSelect(s)}
      style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '9px 9px', borderRadius: 'var(--radius-md)',
        background: active ? 'var(--surface-page)' : 'transparent', border: active ? '1px solid var(--border-hairline)' : '1px solid transparent', cursor: 'pointer', marginBottom: 1 }}>
      <IconP d={IP.history} size={14} color={active ? 'var(--accent)' : 'var(--text-faint)'} style={{ flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12.8, fontWeight: active ? 600 : 500, color: active ? 'var(--text-heading)' : 'var(--text-body)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.title}</div>
      </div>
      {hov ? (
        <button onClick={(e) => { e.stopPropagation(); onDelete(s.id); }} title="삭제"
          style={{ flexShrink: 0, width: 22, height: 22, borderRadius: 'var(--radius-full)', border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <IconP d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v6M14 11v6" size={13} color="var(--text-faint)" /></button>
      ) : (
        <span style={{ fontSize: 10.5, color: 'var(--text-faint)', flexShrink: 0 }}>{rel}</span>
      )}
    </div>
  );
}

function HistorySidebar({ onNew, onChip, onOpenFaq, compact, sessions = [], activeId, onSelect, onDelete }) {
  const D = window.RibbonData;
  const pinned = D.FAQS.filter(f => f.pinned);
  return (
    <div style={{ width: compact ? 220 : 256, flexShrink: 0, borderRight: '1px solid var(--border-hairline)', background: 'var(--surface-soft)',
      display: 'flex', flexDirection: 'column', height: '100%', fontFamily: 'var(--font-sans)' }}>
      <div style={{ padding: '16px 14px 10px' }}>
        <button onClick={onNew} style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, height: 38,
          borderRadius: 'var(--radius-md)', border: '1px solid var(--border-hairline)', background: 'var(--surface-page)', cursor: 'pointer',
          fontSize: 13.5, fontWeight: 600, color: 'var(--text-heading)' }}>
          <IconP d={IP.plus} size={16} color="var(--accent)" />새 대화</button>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '6px 10px' }}>
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.6px', color: 'var(--text-faint)', padding: '8px 8px 6px', textTransform: 'uppercase' }}>최근 대화</div>
        {sessions.length === 0 && (
          <div style={{ fontSize: 12, color: 'var(--text-faint)', padding: '4px 9px 8px' }}>아직 저장된 대화가 없어요.</div>
        )}
        {sessions.map(s => (
          <SessionRow key={s.id} s={s} active={s.id === activeId} onSelect={onSelect || (() => {})} onDelete={onDelete || (() => {})} />
        ))}

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 8px 6px' }}>
          <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.6px', color: 'var(--text-faint)', textTransform: 'uppercase' }}>고정 질문</span>
          <button onClick={onOpenFaq} style={{ border: 'none', background: 'none', cursor: 'pointer', fontSize: 11.5, fontWeight: 600, color: 'var(--accent)', padding: 0 }}>관리</button>
        </div>
        {pinned.map(f => (
          <button key={f.id} onClick={() => onChip(f.q)} className="rb-session" style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left',
            padding: '8px 9px', borderRadius: 'var(--radius-md)', border: 'none', background: 'transparent', cursor: 'pointer', marginBottom: 1 }}>
            <IconP d={IP.spark} size={13} color="var(--accent)" style={{ flexShrink: 0 }} />
            <span style={{ fontSize: 12.5, color: 'var(--text-body)', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.q}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ── FAQ 등록·관리 화면 ──────────────────────────────────────
const CATS = ['가동률', '구매 추천', '예약', '매출', '기타'];

function FaqManager({ onClose, onChip }) {
  const [faqs, setFaqs] = useStateP(window.RibbonData.FAQS.map(f => ({ ...f })));
  const [q, setQ] = useStateP('');
  const [cat, setCat] = useStateP(CATS[0]);

  function add() {
    if (!q.trim()) return;
    setFaqs(f => [{ id: Date.now(), q: q.trim(), cat, uses: 0, pinned: false }, ...f]);
    setQ('');
  }
  function togglePin(id) { setFaqs(f => f.map(x => x.id === id ? { ...x, pinned: !x.pinned } : x)); }
  function del(id) { setFaqs(f => f.filter(x => x.id !== id)); }

  const catColor = { '가동률': 'var(--color-teal)', '구매 추천': 'var(--accent)', '예약': 'var(--color-amber)', '매출': 'var(--color-blue, #7595c4)', '기타': 'var(--text-muted)' };

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--surface-page)', zIndex: 60, display: 'flex', flexDirection: 'column', fontFamily: 'var(--font-sans)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '15px 18px', borderBottom: '1px solid var(--border-hairline)' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, letterSpacing: '-0.4px', color: 'var(--text-heading)' }}>자주 묻는 질문 관리</div>
          <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 1 }}>자주 쓰는 질문을 등록하면 시작화면·사이드바에 노출됩니다</div>
        </div>
        <button onClick={onClose} style={{ marginLeft: 'auto', width: 34, height: 34, borderRadius: 'var(--radius-full)', border: '1px solid var(--border-hairline)',
          background: 'var(--surface-page)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <IconP d={IP.x} size={17} color="var(--text-muted)" /></button>
      </div>

      {/* 새 FAQ 등록 폼 */}
      <div style={{ padding: '16px 18px', borderBottom: '1px solid var(--border-hairline)', background: 'var(--surface-soft)' }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-muted)', marginBottom: 9 }}>새 질문 등록</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input value={q} onChange={e => setQ(e.target.value)} onKeyDown={e => e.key === 'Enter' && add()} placeholder="예: 지점별 가동률 비교해줘"
            style={{ flex: 1, height: 40, padding: '0 14px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-hairline)',
              background: 'var(--surface-page)', fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--text-heading)', outline: 'none' }} />
          <select value={cat} onChange={e => setCat(e.target.value)}
            style={{ height: 40, padding: '0 12px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-hairline)',
              background: 'var(--surface-page)', fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text-body)', cursor: 'pointer' }}>
            {CATS.map(c => <option key={c}>{c}</option>)}
          </select>
          <button onClick={add} style={{ height: 40, padding: '0 18px', borderRadius: 'var(--radius-md)', border: 'none', background: 'var(--accent)',
            color: '#fff', fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
            <IconP d={IP.plus} size={15} color="#fff" />등록</button>
        </div>
      </div>

      {/* FAQ 목록 */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '10px 18px 18px' }}>
        {faqs.map(f => (
          <div key={f.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderRadius: 'var(--radius-md)',
            border: '1px solid var(--border-hairline)', marginTop: 8, background: 'var(--surface-page)' }}>
            <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.4px', color: catColor[f.cat] || 'var(--text-muted)',
              background: 'var(--surface-soft)', border: '1px solid var(--border-hairline)', padding: '3px 9px', borderRadius: 'var(--radius-pill)', flexShrink: 0 }}>{f.cat}</span>
            <button onClick={() => { onChip(f.q); onClose(); }} style={{ flex: 1, textAlign: 'left', border: 'none', background: 'none', cursor: 'pointer',
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 500, color: 'var(--text-heading)', minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.q}</button>
            <span style={{ fontSize: 11.5, color: 'var(--text-faint)', flexShrink: 0 }}>사용 {f.uses}회</span>
            <button onClick={() => togglePin(f.id)} title="고정" style={{ width: 30, height: 30, borderRadius: 'var(--radius-full)', border: 'none', cursor: 'pointer',
              background: f.pinned ? 'rgba(204,120,92,0.12)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IconP d="M12 2l2.4 7.2H22l-6 4.6 2.3 7.2-6.3-4.5-6.3 4.5L8 13.8 2 9.2h7.6z" size={15} color={f.pinned ? 'var(--accent)' : 'var(--text-faint)'} /></button>
            <button onClick={() => del(f.id)} title="삭제" style={{ width: 30, height: 30, borderRadius: 'var(--radius-full)', border: 'none', cursor: 'pointer',
              background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IconP d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v6M14 11v6" size={15} color="var(--text-faint)" /></button>
          </div>
        ))}
      </div>
    </div>
  );
}

window.RibbonPanels = { HistorySidebar, FaqManager };
