import { createFileRoute, Link } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import {
  Type, Braces, Palette, KeyRound, ShieldCheck, Search, Sparkles,
  Code2, Link as LinkIcon, FileText, Hash, CaseSensitive, FileCode2,
  QrCode, Clock, Regex, type LucideIcon,
} from "lucide-react";
import { SiteHeader } from "@/components/SiteHeader";
import { SiteFooter } from "@/components/SiteFooter";
import { Input } from "@/components/ui/input";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Toolkit — 12+ Free Online Utility Tools (No Signup)" },
      { name: "description", content: "A free collection of fast, privacy-friendly online tools: JSON formatter, password generator, QR code, regex tester, Base64, UUID, Markdown preview and more. No signup, no tracking." },
      { property: "og:title", content: "Toolkit — Free in-browser utility tools" },
      { property: "og:description", content: "12+ free online tools for developers, designers and writers. Runs entirely in your browser." },
      { name: "keywords", content: "online tools, free utility tools, json formatter, password generator, qr code, regex tester, base64, uuid generator, markdown preview" },
    ],
  }),
  component: Index,
});

type Category = "Text" | "Developer" | "Design" | "Security" | "Converter";
type Tool = { to: string; title: string; description: string; category: Category; icon: LucideIcon };

const TOOLS: Tool[] = [
  { to: "/tools/word-counter", title: "Word Counter", description: "Count words, characters, sentences and reading time.", category: "Text", icon: Type },
  { to: "/tools/case-converter", title: "Case Converter", description: "Convert text between UPPER, lower, Title and camelCase.", category: "Text", icon: CaseSensitive },
  { to: "/tools/lorem-ipsum", title: "Lorem Ipsum", description: "Generate placeholder paragraphs for your designs.", category: "Text", icon: FileText },
  { to: "/tools/markdown-preview", title: "Markdown Preview", description: "Live render Markdown as you type.", category: "Text", icon: FileCode2 },

  { to: "/tools/json-formatter", title: "JSON Formatter", description: "Beautify, minify and validate JSON instantly.", category: "Developer", icon: Braces },
  { to: "/tools/regex-tester", title: "Regex Tester", description: "Test regular expressions with live highlighting.", category: "Developer", icon: Regex },
  { to: "/tools/uuid", title: "UUID Generator", description: "Generate cryptographically random UUID v4 IDs.", category: "Developer", icon: Hash },
  { to: "/tools/timestamp", title: "Timestamp Converter", description: "Convert between Unix epoch and human dates.", category: "Developer", icon: Clock },

  { to: "/tools/base64", title: "Base64 Encoder", description: "Encode and decode Base64 strings (UTF-8 safe).", category: "Converter", icon: Code2 },
  { to: "/tools/url-encoder", title: "URL Encoder", description: "Percent-encode or decode URL strings.", category: "Converter", icon: LinkIcon },

  { to: "/tools/color-converter", title: "Color Converter", description: "Convert between HEX, RGB and HSL with live preview.", category: "Design", icon: Palette },
  { to: "/tools/qr-code", title: "QR Code Generator", description: "Create QR codes from any text or URL.", category: "Design", icon: QrCode },

  { to: "/tools/password-generator", title: "Password Generator", description: "Generate strong, customizable passwords locally.", category: "Security", icon: KeyRound },
  { to: "/tools/totp-authenticator", title: "2FA Authenticator", description: "Generate TOTP 2FA codes from a Base32 secret.", category: "Security", icon: ShieldCheck },
];

const CATEGORIES: (Category | "All")[] = ["All", "Text", "Developer", "Design", "Security", "Converter"];

function Index() {
  const [q, setQ] = useState("");
  const [cat, setCat] = useState<Category | "All">("All");

  const filtered = useMemo(
    () => TOOLS.filter((t) => {
      const matchCat = cat === "All" || t.category === cat;
      const ql = q.toLowerCase();
      const matchQ = !ql || t.title.toLowerCase().includes(ql) || t.description.toLowerCase().includes(ql) || t.category.toLowerCase().includes(ql);
      return matchCat && matchQ;
    }),
    [q, cat],
  );

  return (
    <div className="flex min-h-screen flex-col bg-background">
      <SiteHeader />
      <main className="flex-1">
        <section className="border-b border-border/60" style={{ background: "var(--gradient-subtle)" }}>
          <div className="mx-auto max-w-6xl px-6 py-20 sm:py-28">
            <div className="mx-auto max-w-2xl text-center">
              <span className="inline-flex items-center gap-1.5 rounded-full border border-border/80 bg-background/60 px-3 py-1 text-xs font-medium text-muted-foreground backdrop-blur">
                <Sparkles className="h-3 w-3 text-primary" />
                {TOOLS.length} tools · runs entirely in your browser
              </span>
              <h1 className="mt-6 text-4xl font-semibold tracking-tight text-foreground sm:text-6xl">
                Tiny tools.{" "}
                <span className="bg-clip-text text-transparent" style={{ backgroundImage: "var(--gradient-primary)" }}>Big productivity.</span>
              </h1>
              <p className="mt-5 text-lg leading-relaxed text-muted-foreground">
                A focused collection of fast, free utilities for everyday work — no signup, no tracking, no fluff.
              </p>
              <div className="relative mx-auto mt-8 max-w-md">
                <Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search tools…" className="h-12 rounded-full border-border/80 bg-background pl-11 shadow-[var(--shadow-soft)]" />
              </div>
            </div>
          </div>
        </section>

        <section className="mx-auto max-w-6xl px-6 py-16">
          <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-2xl font-semibold tracking-tight">All tools</h2>
            <p className="text-sm text-muted-foreground">{filtered.length} of {TOOLS.length}</p>
          </div>

          <div className="mb-8 flex flex-wrap gap-2">
            {CATEGORIES.map((c) => (
              <button
                key={c}
                onClick={() => setCat(c)}
                className={`rounded-full border px-3.5 py-1.5 text-xs font-medium transition-colors ${
                  cat === c ? "border-primary bg-primary text-primary-foreground" : "border-border bg-background text-muted-foreground hover:text-foreground"
                }`}
              >
                {c}
              </button>
            ))}
          </div>

          {filtered.length === 0 ? (
            <p className="rounded-xl border border-dashed border-border p-12 text-center text-muted-foreground">No tools match "{q}".</p>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {filtered.map((tool) => {
                const Icon = tool.icon;
                return (
                  <Link
                    key={tool.to}
                    to={tool.to}
                    className="group relative overflow-hidden rounded-2xl border border-border/80 bg-card p-6 shadow-[var(--shadow-soft)] transition-all hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-[var(--shadow-elegant)]"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex h-11 w-11 items-center justify-center rounded-xl text-primary-foreground transition-transform group-hover:scale-110" style={{ background: "var(--gradient-primary)" }}>
                        <Icon className="h-5 w-5" />
                      </div>
                      <span className="rounded-full bg-accent/60 px-2.5 py-0.5 text-xs font-medium text-accent-foreground">{tool.category}</span>
                    </div>
                    <h3 className="mt-5 text-lg font-semibold tracking-tight text-card-foreground">{tool.title}</h3>
                    <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{tool.description}</p>
                  </Link>
                );
              })}
            </div>
          )}
        </section>

        <section className="border-t border-border/60 bg-muted/30">
          <div className="mx-auto max-w-4xl px-6 py-16">
            <h2 className="text-2xl font-semibold tracking-tight">Why Toolkit?</h2>
            <div className="mt-6 grid gap-6 sm:grid-cols-3">
              <div>
                <h3 className="font-semibold text-foreground">100% private</h3>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">Every tool runs in your browser. Your inputs never reach our servers.</p>
              </div>
              <div>
                <h3 className="font-semibold text-foreground">No signup</h3>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">No account, no email, no friction. Open the page and start working.</p>
              </div>
              <div>
                <h3 className="font-semibold text-foreground">Always free</h3>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">A growing collection of utilities maintained as a public good.</p>
              </div>
            </div>
          </div>
        </section>
      </main>
      <SiteFooter />
    </div>
  );
}
