// ─── 탭 보관함 시트 ──────────────────────────
// 닫힌 작업공간(탭) 목록을 표시하고 복원/삭제한다.
// 열릴 때 GET /api/history → { history: [{ tab_id, name, closed_at, parcel_count }] }
// - 복원: onRestore(tabId) 후 시트 닫힘(app.jsx 에서 switchTab(new_tab_id) 처리)
// - 삭제: window.confirm 1회 확인 → onDelete(tabId) 후 로컬 목록 즉시 제거
//
// 로컬 스타일 상수 (디자인 토큰 준수, appStyles.js 에 추가하지 않음 — 버킷 충돌 방지)
const historySheetStyles = {
  header: { display: 'flex', alignItems: 'center', gap: 8 },
  title: { flex: 1, fontSize: 17, fontWeight: 700, color: '#1A1814', letterSpacing: '-0.01em' },
  empty: {
    textAlign: 'center', color: '#8E8B82', fontSize: 14,
    padding: '32px 0',
  },
  loading: {
    textAlign: 'center', color: '#8E8B82', fontSize: 13,
    padding: '32px 0',
  },
  list: { display: 'flex', flexDirection: 'column', gap: 8 },
  item: {
    display: 'flex', alignItems: 'center', gap: 12,
    background: '#FBFAF6', border: '1px solid #E4E2DA', borderRadius: 10,
    padding: 12,
  },
  itemInfo: { flex: 1, minWidth: 0 },
  itemName: {
    fontSize: 14, fontWeight: 600, color: '#1A1814',
    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
  },
  itemMeta: {
    fontSize: 12, color: '#8E8B82', marginTop: 3,
    fontVariantNumeric: 'tabular-nums',
  },
  itemBtns: { display: 'flex', gap: 6, flexShrink: 0 },
  restoreBtn: {
    background: '#2F7D4F', color: '#FFFFFF', border: 'none',
    borderRadius: 8, padding: '6px 12px',
    fontSize: 13, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
  },
  deleteBtn: {
    background: 'transparent', color: '#C8392E',
    border: '1px solid #E4E2DA', borderRadius: 8, padding: '6px 12px',
    fontSize: 13, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
  },
};

function HistorySheet({ onRestore, onDelete, onClose }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // L-3: 현재 범위에서는 전체 반환 (추후 페이지네이션)
    // DataReads.getHistory() → 드라이버 무관 단일 리턴. supabase 드라이버는 N+1 제거(2쿼리).
    window.DataReads.getHistory()
      .then(history => { setItems(history || []); setLoading(false); })
      .catch(() => { setItems([]); setLoading(false); });
  }, []);

  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  });

  const formatClosedAt = (iso) => {
    if (!iso) return '';
    try {
      return new Date(iso).toLocaleString('ko', {
        month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit',
      });
    } catch (e) {
      return '';
    }
  };

  const handleRestore = (tabId) => {
    onRestore(tabId);
    onClose();
  };

  const handleDelete = (tabId) => {
    if (!window.confirm('이 작업공간 기록을 삭제할까요?')) return;
    onDelete(tabId);
    setItems(prev => prev.filter(it => it.tab_id !== tabId));
  };

  return (
    <BottomSheet onClose={onClose}>
      <div style={historySheetStyles.header}>
        <i data-lucide="archive" style={{ width: 18, height: 18, color: '#5C5851', flexShrink: 0 }}></i>
        <div style={historySheetStyles.title}>탭 보관함</div>
        <button style={appStyles.closeX} onClick={onClose} aria-label="닫기">
          <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
        </button>
      </div>

      {loading ? (
        <div style={historySheetStyles.loading}>불러오는 중…</div>
      ) : items.length === 0 ? (
        <div style={historySheetStyles.empty}>보관된 탭이 없습니다</div>
      ) : (
        <div style={historySheetStyles.list}>
          {items.map(it => (
            <div key={it.tab_id} style={historySheetStyles.item}>
              <div style={historySheetStyles.itemInfo}>
                <div style={historySheetStyles.itemName}>{it.name || '(이름 없음)'}</div>
                <div style={historySheetStyles.itemMeta}>
                  {formatClosedAt(it.closed_at)} · {it.parcel_count || 0}필지
                </div>
              </div>
              <div style={historySheetStyles.itemBtns}>
                <button style={historySheetStyles.restoreBtn} onClick={() => handleRestore(it.tab_id)}>
                  복원
                </button>
                <button style={historySheetStyles.deleteBtn} onClick={() => handleDelete(it.tab_id)}>
                  삭제
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </BottomSheet>
  );
}

window.HistorySheet = HistorySheet;
