import { createFileRoute, Link } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { toast, Toaster } from "sonner";
import { Search, Download, Github, Heart } from "lucide-react";
import { CATEGORIES, TOOLS } from "@/lib/tools";

// Snapshot of every source file, resolved at build time by Vite.
const SOURCE_FILES = import.meta.glob(["/src/**/*.{ts,tsx,css,json,md}", "!/src/routeTree.gen.ts"], { query: "?raw", import: "default", eager: true }) as Record<string, string>;

export const Route = createFileRoute("/")({
  component: Index,
});

function Index() {
  const [q, setQ] = useState("");
  const [cat, setCat] = useState<string>("Todos");

  const filtered = useMemo(() => {
    const term = q.trim().toLowerCase();
    return TOOLS.filter((t) => (cat === "Todos" || t.category === cat) && (term === "" || t.name.toLowerCase().includes(term) || t.desc.toLowerCase().includes(term)));
  }, [q, cat]);

  const downloadSource = async () => {
    toast.info("Empacotando o código-fonte...");
    const JSZip = (await import("jszip")).default;
    const zip = new JSZip();
    for (const [path, content] of Object.entries(SOURCE_FILES)) {
      if (path.endsWith("routeTree.gen.ts")) continue;
      zip.file(path.replace(/^\//, ""), content);
    }
    zip.file("LICENSE", `MIT License\n\nCopyright (c) ${new Date().getFullYear()} C0DSXS\n\nUse com atribuição: "Baseado em C0DSXS".\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.`);
    zip.file("README.md", `# C0DSXS — Utilidades Minecraft\n\nSite open-source com ${TOOLS.length}+ utilidades. Créditos: **C0DSXS**.\n`);
    const blob = await zip.generateAsync({ type: "blob" });
    const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "C0DSXS-source.zip"; a.click();
    toast.success("Download iniciado — não esqueça de dar créditos!");
  };

  return (
    <div className="min-h-screen grid-bg">
      <Toaster theme="dark" position="top-right" />

      {/* HEADER */}
      <header className="border-b border-border/60 backdrop-blur bg-background/70 sticky top-0 z-20">
        <div className="mx-auto max-w-7xl px-4 py-4 flex items-center gap-4 flex-wrap">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-md flex items-center justify-center pixel text-lg" style={{ background: "linear-gradient(180deg, oklch(0.72 0.19 145), oklch(0.42 0.08 60))", boxShadow: "inset 0 2px 0 rgba(255,255,255,.25), 0 3px 0 rgba(0,0,0,.4)" }}>
              <span style={{ fontSize: 11 }}>C0</span>
            </div>
            <div>
              <h1 className="pixel text-lg leading-none">C0DSXS</h1>
              <p className="text-xs text-muted-foreground mt-1">Utilidades Minecraft · open-source</p>
            </div>
          </div>
          <div className="flex-1 min-w-64 relative">
            <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar utilidade..."
              className="w-full pl-10 pr-3 py-2 rounded-md bg-input border border-border mono text-sm focus:outline-none focus:ring-2 focus:ring-ring" />
          </div>
          <button onClick={downloadSource} className="mc-btn mc-btn-hover rounded-md inline-flex items-center gap-2">
            <Download className="w-4 h-4" /> Baixar código
          </button>
          <a href="https://github.com" target="_blank" rel="noreferrer" className="mc-btn mc-btn-hover rounded-md inline-flex items-center gap-2" style={{ background: "linear-gradient(180deg, oklch(0.42 0.08 60), oklch(0.32 0.06 60))", color: "#fff" }}>
            <Github className="w-4 h-4" /> GitHub
          </a>
        </div>
      </header>

      {/* HERO */}
      <section className="mx-auto max-w-7xl px-4 pt-10 pb-6">
        <div className="mc-card rounded-lg p-6 md:p-8 relative overflow-hidden">
          <div className="absolute -right-8 -bottom-8 opacity-10 text-[220px] leading-none select-none">⛏️</div>
          <h2 className="pixel text-2xl md:text-3xl">{TOOLS.length} utilidades. Zero login.</h2>
          <p className="mt-3 text-muted-foreground max-w-2xl">
            Foto de perfil, criador de modpacks, resource packs, comandos, encantamentos, MOTD com gradiente, editor de textura, mesclador de packs e muito mais.
            Tudo roda no seu navegador — sem envio de dados.
          </p>
          <div className="mt-4 flex flex-wrap gap-2 text-xs">
            <span className="mc-card rounded-md px-3 py-1">Java Edition</span>
            <span className="mc-card rounded-md px-3 py-1">Bedrock Edition</span>
            <span className="mc-card rounded-md px-3 py-1">MIT License</span>
          </div>
        </div>

        {/* AVISO DE CRÉDITOS */}
        <div className="mt-4 rounded-md border-2 border-primary/40 bg-primary/10 p-4 flex gap-3 items-start">
          <Heart className="w-5 h-5 text-primary mt-0.5 shrink-0" />
          <div className="text-sm">
            <strong className="pixel text-xs">DÊ CRÉDITOS!</strong>
            <p className="mt-1 text-muted-foreground">
              Este site é <b>100% open-source</b>. Você pode baixar todo o código-fonte e usar como quiser — apenas mantenha os créditos ao <b>C0DSXS</b> visíveis
              em qualquer projeto derivado, README ou rodapé. Minecraft é marca registrada da Mojang/Microsoft — não somos afiliados.
            </p>
          </div>
        </div>
      </section>

      {/* FILTER */}
      <section className="mx-auto max-w-7xl px-4">
        <div className="flex flex-wrap gap-2 mb-4">
          {["Todos", ...CATEGORIES].map((c) => (
            <button key={c} onClick={() => setCat(c)}
              className={`rounded-md px-3 py-1.5 text-xs pixel border transition ${cat === c ? "bg-primary text-primary-foreground border-primary" : "bg-secondary text-secondary-foreground border-border hover:bg-secondary/80"}`}
              style={{ fontSize: 10 }}>{c}</button>
          ))}
        </div>
      </section>

      {/* GRID */}
      <section className="mx-auto max-w-7xl px-4 pb-16">
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
          {filtered.map((t) => (
            <Link key={t.id} to="/tool/$id" params={{ id: t.id }}
              className="mc-card rounded-md p-4 text-left hover:brightness-125 hover:-translate-y-0.5 transition group">
              <div className="text-3xl">{t.emoji}</div>
              <div className="mt-2 pixel text-sm leading-tight" style={{ fontSize: 11 }}>{t.name}</div>
              <div className="mt-1 text-xs text-muted-foreground line-clamp-2">{t.desc}</div>
              <div className="mt-2 text-[10px] uppercase tracking-wider text-primary/80">{t.category}</div>
            </Link>
          ))}
          {filtered.length === 0 && <p className="text-muted-foreground col-span-full text-center py-16">Nenhuma ferramenta encontrada.</p>}
        </div>
      </section>

      <footer className="border-t border-border/60 py-8 text-center text-xs text-muted-foreground">
        <p className="pixel" style={{ fontSize: 10 }}>C0DSXS · Feito por fãs, para fãs.</p>
        <p className="mt-2">Não afiliado à Mojang / Microsoft. Minecraft © Mojang AB.</p>
        <p className="mt-1">Reutilize com créditos · MIT License</p>
      </footer>
    </div>
  );
}
