import { useState, useMemo } from 'react';
import { siteData } from '../data/siteData';
import { useI18n } from './useI18n';

export function useProjectFilters() {
  const { bi, lang } = useI18n();
  const projects = siteData.projects;

  const [search, setSearch] = useState('');
  const [tech, setTech] = useState('');
  const [platform, setPlatform] = useState('');
  const [status, setStatus] = useState('');
  const [sort, setSort] = useState('updated');

  const allTech = useMemo(
    () => [...new Set(projects.flatMap((p) => p.techStack))].sort(),
    [projects]
  );
  const allPlatforms = useMemo(
    () => [...new Set(projects.flatMap((p) => p.platforms))].sort(),
    [projects]
  );
  const allStatuses = useMemo(() => [...new Set(projects.map((p) => p.status))], [projects]);

  const filteredProjects = useMemo(() => {
    let result = [...projects];

    if (search) {
      const q = search.toLowerCase();
      result = result.filter(
        (p) =>
          p.name.toLowerCase().includes(q) ||
          bi(p.slogan).toLowerCase().includes(q) ||
          p.tags.some((tag) => tag.toLowerCase().includes(q)) ||
          p.techStack.some((ts) => ts.toLowerCase().includes(q))
      );
    }
    if (tech) result = result.filter((p) => p.techStack.includes(tech));
    if (platform) result = result.filter((p) => p.platforms.includes(platform));
    if (status) result = result.filter((p) => p.status === status);

    if (sort === 'name') result.sort((a, b) => a.name.localeCompare(b.name));
    else result.sort((a, b) => b.lastUpdated.localeCompare(a.lastUpdated));

    return result;
  }, [projects, search, tech, platform, status, sort, lang, bi]);

  return {
    search,
    setSearch,
    tech,
    setTech,
    platform,
    setPlatform,
    status,
    setStatus,
    sort,
    setSort,
    allTech,
    allPlatforms,
    allStatuses,
    filteredProjects,
  };
}
