import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { ToolShell } from "@/components/ToolShell";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";

export const Route = createFileRoute("/tools/regex-tester")({
  head: () => ({
    meta: [
      { title: "Regex Tester — Test Regular Expressions Online" },
      { name: "description", content: "Test JavaScript regular expressions against sample text with live highlighting and match details." },
      { property: "og:title", content: "Regex Tester" },
      { property: "og:description", content: "Live test JavaScript regex patterns with highlighted matches." },
    ],
  }),
  component: RegexTool,
});

function RegexTool() {
  const [pattern, setPattern] = useState("\\b\\w+@\\w+\\.[a-z]+\\b");
  const [flags, setFlags] = useState("gi");
  const [text, setText] = useState("Contact us at hello@example.com or sales@lovable.dev anytime.");

  const { error, matches, highlighted } = useMemo(() => {
    try {
      const re = new RegExp(pattern, flags.includes("g") ? flags : flags + "g");
      const ms = Array.from(text.matchAll(re));
      let last = 0;
      let html = "";
      for (const m of ms) {
        const i = m.index ?? 0;
        html += escapeHtml(text.slice(last, i));
        html += `<mark class="rounded bg-primary/20 px-0.5">${escapeHtml(m[0])}</mark>`;
        last = i + m[0].length;
      }
      html += escapeHtml(text.slice(last));
      return { error: null as string | null, matches: ms, highlighted: html };
    } catch (e) {
      return { error: (e as Error).message, matches: [], highlighted: escapeHtml(text) };
    }
  }, [pattern, flags, text]);

  return (
    <ToolShell title="Regex Tester" description="Build and debug JavaScript regular expressions with instant feedback. Matches are highlighted as you type.">
      <div className="space-y-4">
        <div className="grid gap-3 md:grid-cols-[1fr_140px]">
          <div className="space-y-2"><Label>Pattern</Label><Input value={pattern} onChange={(e) => setPattern(e.target.value)} className="font-mono" /></div>
          <div className="space-y-2"><Label>Flags</Label><Input value={flags} onChange={(e) => setFlags(e.target.value)} className="font-mono" /></div>
        </div>
        {error && <p className="text-sm text-destructive">{error}</p>}
        <div className="space-y-2"><Label>Test text</Label><Textarea value={text} onChange={(e) => setText(e.target.value)} className="min-h-[140px] font-mono text-sm" /></div>
        <div className="rounded-md border border-border bg-muted/30 p-3 text-sm leading-relaxed" dangerouslySetInnerHTML={{ __html: highlighted }} />
        <p className="text-sm text-muted-foreground">{matches.length} match{matches.length === 1 ? "" : "es"}</p>
      </div>
    </ToolShell>
  );
}

function escapeHtml(s: string) { return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
