"use client";

import { use } from "react";
import { ArrowLeft, FileText, Folder } from "lucide-react";
import Link from "next/link";
import { useSkill } from "@/lib/hooks";
import { Markdown } from "@/components/Markdown";

export default function SkillDetailPage({ params }: { params: Promise<{ name: string }> }) {
  const { name } = use(params);
  const { data, isLoading } = useSkill(name);

  // Strip YAML frontmatter for rendering
  let content = data?.content || "";
  if (content.startsWith("---")) {
    const end = content.indexOf("---", 3);
    if (end > 0) content = content.slice(end + 3).trim();
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <Link href="/skills" className="p-1 -ml-1 rounded-lg active:bg-white/[0.04]">
          <ArrowLeft size={20} style={{ color: "var(--text-2)" }} />
        </Link>
        <h1 className="text-[15px] font-medium" style={{ color: "var(--text-1)" }}>{name}</h1>
      </div>

      {isLoading ? (
        <div className="card p-4 animate-pulse space-y-2">
          <div className="h-4 rounded w-full" style={{ background: "var(--bg-hover)" }} />
          <div className="h-4 rounded w-3/4" style={{ background: "var(--bg-hover)" }} />
        </div>
      ) : data ? (
        <>
          {data.linked_files && Object.keys(data.linked_files).length > 0 && (
            <div className="card p-3">
              <div className="text-[11px] font-medium mb-2 flex items-center gap-1.5" style={{ color: "var(--text-2)" }}>
                <Folder size={12} /> Linked Files
              </div>
              {Object.entries(data.linked_files).map(([dir, files]) =>
                (files as string[]).map((f) => (
                  <div key={dir + "/" + f} className="flex items-center gap-2 text-[12px] py-0.5" style={{ color: "var(--text-3)" }}>
                    <FileText size={11} />
                    <span className="font-mono">{dir}/{f}</span>
                  </div>
                ))
              )}
            </div>
          )}
          <div className="card p-4 overflow-x-hidden">
            <Markdown content={content} />
          </div>
        </>
      ) : (
        <p className="text-sm py-8 text-center" style={{ color: "var(--text-3)" }}>Skill not found</p>
      )}
    </div>
  );
}
