'use client';

import { useCallback, useDeferredValue, useMemo, useState } from 'react';

export const FILTERS = [
  { id: 'all', label: 'All', match: () => true },
  { id: 'artifact', label: 'Artifacts', match: (it) => it.source_type === 'artifact' },
  { id: 'document', label: 'Documents', match: (it) => it.source_type === 'file' },
  { id: 'local', label: 'Local-only', match: (it) => it.source_type === 'file' && it.local_only },
];

export function itemKey(item) {
  return `${item.source_type}-${item.id}`;
}

export function itemAuthorLabel(item) {
  if (item.source_type === 'artifact') {
    const id = item.agent_id || '';
    if (!id) return 'Agent';
    if (id === 'main-orchestrator') return 'Main agent';
    if (id === 'ops-agent') return 'Caretaker';
    return id;
  }
  return 'You';
}

export function itemSearchText(item, { sessionUnlocked } = {}) {
  const shouldExcludeBody = item.is_protected && !sessionUnlocked;
  const bodyExcerpt = shouldExcludeBody
    ? ''
    : String(item.body || item.preview || '').slice(0, 4000);
  return [
    item.title || '',
    item.name || '',
    item.path || '',
    bodyExcerpt,
    item.agent_id || '',
    itemAuthorLabel(item),
  ].join(' ').toLowerCase();
}

export function itemTitleText(item) {
  return [
    item.title || '',
    item.name || '',
    item.path || '',
  ].join(' ').toLowerCase();
}

export function useAlbumState({ items, folders, currentFolderId, rootFolderId, unlocked }) {
  const [filterId, setFilterId] = useState('all');
  const [query, setQuery] = useState('');
  const [selectedKey, setSelectedKey] = useState(null);
  const deferredQuery = useDeferredValue(query);

  const isRoot = !currentFolderId || currentFolderId === rootFolderId;
  const currentFolder = useMemo(
    () => folders.find((f) => f.id === currentFolderId) || null,
    [folders, currentFolderId],
  );
  const breadcrumb = useMemo(() => {
    if (isRoot) return [];
    const trail = [];
    const byId = new Map(folders.map((f) => [f.id, f]));
    let node = byId.get(currentFolderId);
    while (node) {
      trail.unshift(node);
      node = node.parent_id ? byId.get(node.parent_id) : null;
    }
    return trail;
  }, [folders, currentFolderId, isRoot]);
  const subFolders = useMemo(() => {
    const parentId = isRoot ? rootFolderId : currentFolderId;
    return folders.filter((f) => f.parent_id === parentId);
  }, [folders, currentFolderId, isRoot, rootFolderId]);
  const itemsInFolder = useMemo(() => items.filter((it) => {
    const f = it.folder_id || null;
    if (isRoot) return !f || f === rootFolderId;
    return f === currentFolderId;
  }), [items, currentFolderId, isRoot, rootFolderId]);
  const filteredByFilter = useMemo(() => {
    const fn = (FILTERS.find((f) => f.id === filterId) || FILTERS[0]).match;
    return itemsInFolder.filter(fn);
  }, [itemsInFolder, filterId]);
  const visible = useMemo(() => {
    const q = String(deferredQuery || '').trim().toLowerCase();
    if (!q) return filteredByFilter;
    return filteredByFilter.filter(
      (it) => itemSearchText(it, { sessionUnlocked: unlocked }).includes(q),
    );
  }, [filteredByFilter, deferredQuery, unlocked]);
  const queryLower = String(deferredQuery || '').trim().toLowerCase();
  const titleMatchesQuery = useCallback(
    (item) => Boolean(queryLower) && itemTitleText(item).includes(queryLower),
    [queryLower],
  );
  const selected = useMemo(
    () => items.find((it) => itemKey(it) === selectedKey) || null,
    [items, selectedKey],
  );

  return {
    FILTERS,
    filterId,
    setFilterId,
    query,
    setQuery,
    selectedKey,
    setSelectedKey,
    isRoot,
    currentFolder,
    breadcrumb,
    subFolders,
    itemsInFolder,
    visible,
    queryLower,
    titleMatchesQuery,
    selected,
  };
}
