import Link from "next/link";
import { getContents } from "@/lib/github";
import { BookOpen, Settings } from "lucide-react";

const TAB_COLORS = [
  "#c0392b",
  "#2980b9",
  "#27ae60",
  "#8e44ad",
  "#d35400",
  "#16a085",
  "#2c3e50",
  "#b8860b",
  "#7f8c8d",
];

export default async function Home() {
  let sections = [];
  let error = null;

  try {
    const items = await getContents("");
    sections = items
      .filter((i) => i.type === "dir" && !i.name.startsWith("."))
      .sort((a, b) => a.name.localeCompare(b.name));
  } catch (e) {
    error = e.message;
  }

  return (
    <div className="min-h-screen bg-gray-50 p-6 flex flex-col">
      {/* Header */}
      <div className="max-w-4xl mx-auto w-full mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-2">
            <BookOpen size={28} className="text-indigo-600" />
            All In One
          </h1>
          <p className="text-sm text-gray-500 mt-0.5">
            Personal Knowledge Base
          </p>
        </div>
        <Link
          href="/admin"
          className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-indigo-600 transition-colors"
        >
          <Settings size={15} />
          Admin
        </Link>
      </div>

      {/* Sections grid */}
      <div className="max-w-4xl mx-auto w-full flex-1">
        {error ? (
          <div className="text-red-600 text-sm p-4 bg-red-50 border border-red-200 rounded-lg">
            <p className="font-semibold mb-1">Could not load sections</p>
            <p className="opacity-75">{error}</p>
            <p className="mt-1 text-xs opacity-60">Check your .env file</p>
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
            {sections.map((sec, i) => (
              <Link key={sec.path} href={`/browse/${sec.path}`}>
                <div
                  className="bg-white rounded-xl border border-gray-200 overflow-hidden
                                hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 cursor-pointer"
                >
                  <div
                    className="h-1"
                    style={{ background: TAB_COLORS[i % TAB_COLORS.length] }}
                  />
                  <div className="p-4">
                    <p className="text-sm font-semibold text-gray-800">
                      {sec.name}
                    </p>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}
        <p className="text-xs text-gray-400 mt-6">{sections.length} sections</p>
      </div>
    </div>
  );
}