"use client";
import { useState } from 'react';

type Folder = { id: number; name: string };

export default function FoldersBar({ initialFolders }: { initialFolders: Folder[] }) {
  const [folders, setFolders] = useState<Folder[]>(initialFolders);
  const [creating, setCreating] = useState(false);

  async function createFolder() {
    const name = prompt('Folder name');
    if (!name) return;
    setCreating(true);
    try {
      const res = await fetch('/api/folders', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name }) });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || 'Failed to create folder');
      setFolders([...folders, { id: data.id, name: data.name }].sort((a, b) => a.name.localeCompare(b.name)));
    } catch (e: any) {
      alert(e?.message || 'Failed to create folder');
    } finally {
      setCreating(false);
    }
  }

  if (!folders.length) {
    return (
      <div className="flex items-center justify-between border-b pb-3">
        <div className="text-sm text-neutral-600 dark:text-neutral-300">No folders yet</div>
        <button onClick={createFolder} disabled={creating} className="text-sm underline">{creating ? 'Creating…' : 'New Folder'}</button>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-between border-b pb-3">
      <div className="flex gap-3 flex-wrap">
        {folders.map((f) => (
          <a key={f.id} href={`/#folder-${f.id}`} className="text-sm px-3 py-1 rounded-full border hover:bg-neutral-50 dark:hover:bg-neutral-900">
            {f.name}
          </a>
        ))}
      </div>
      <button onClick={createFolder} disabled={creating} className="text-sm underline">{creating ? 'Creating…' : 'New Folder'}</button>
    </div>
  );
}


