"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";

async function fetchProjects() {
  const res = await fetch("/api/projects?status=open");
  return res.json();
}

export default function DashboardPage() {
  const { data: projects, isLoading } = useQuery({ queryKey: ["projects"], queryFn: fetchProjects });

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b px-6 py-4 flex items-center justify-between">
        <h1 className="text-xl font-bold">Freelancer Match</h1>
        <nav className="flex gap-4">
          <Link href="/projects" className="text-gray-600 hover:text-blue-600">Проекты</Link>
          <Link href="/ai-match" className="text-gray-600 hover:text-blue-600">AI-матчинг</Link>
        </nav>
      </header>

      {/* Content */}
      <main className="container mx-auto px-4 py-8">
        <h2 className="text-2xl font-bold mb-6">Добро пожаловать!</h2>

        {isLoading ? (
          <p>Загрузка...</p>
        ) : projects && projects.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
            {projects.map((project) => (
              <Link key={project.id} href={`/projects/${project.id}`} className="p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition">
                <h3 className="font-semibold mb-2">{project.title}</h3>
                <p className="text-gray-600 text-sm line-clamp-2">{project.description}</p>
                {project.budget_max && (
                  <div className="mt-3 text-green-600 font-medium">
                    до {project.budget_max.toLocaleString()}₽
                  </div>
                )}
              </Link>
            ))}
          </div>
        ) : (
          <p className="text-gray-500">Нет доступных проектов</p>
        )}
      </main>
    </div>
  );
}
