import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { ToolShell } from "@/components/ToolShell";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";

export const Route = createFileRoute("/tools/url-encoder")({
  head: () => ({
    meta: [
      { title: "URL Encoder & Decoder — Online Tool" },
      { name: "description", content: "Percent-encode or decode URLs and query strings instantly. Free, private, in-browser." },
      { property: "og:title", content: "URL Encoder & Decoder" },
      { property: "og:description", content: "Encode special characters in URLs or decode them back to readable text." },
    ],
  }),
  component: UrlTool,
});

function UrlTool() {
  const [input, setInput] = useState("");
  const [output, setOutput] = useState("");
  const [error, setError] = useState<string | null>(null);

  return (
    <ToolShell title="URL Encoder / Decoder" description="Safely encode strings for use in URLs and query parameters, or decode percent-encoded URLs back to readable form.">
      <div className="space-y-4">
        <Textarea value={input} onChange={(e) => setInput(e.target.value)} placeholder="Paste URL or text…" className="min-h-[140px] font-mono text-sm" />
        <div className="flex gap-2">
          <Button onClick={() => { setOutput(encodeURIComponent(input)); setError(null); }}>Encode</Button>
          <Button variant="outline" onClick={() => { try { setOutput(decodeURIComponent(input)); setError(null); } catch { setError("Invalid encoded string."); } }}>Decode</Button>
        </div>
        {error && <p className="text-sm text-destructive">{error}</p>}
        <Textarea value={output} readOnly className="min-h-[140px] font-mono text-sm" />
      </div>
    </ToolShell>
  );
}
