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

export const Route = createFileRoute("/tools/markdown-preview")({
  head: () => ({
    meta: [
      { title: "Markdown Preview — Live Markdown Renderer" },
      { name: "description", content: "Write Markdown and see a live rendered preview. Supports headings, lists, links, code, and emphasis." },
      { property: "og:title", content: "Markdown Preview" },
      { property: "og:description", content: "Live preview your Markdown as you type." },
    ],
  }),
  component: MdTool,
});

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

function renderMd(src: string): string {
  const lines = src.split("\n");
  const out: string[] = [];
  let inCode = false;
  let inList = false;
  for (const raw of lines) {
    if (raw.startsWith("```")) {
      if (inCode) { out.push("</code></pre>"); inCode = false; }
      else { out.push('<pre class="rounded-md bg-muted p-3 overflow-x-auto"><code>'); inCode = true; }
      continue;
    }
    if (inCode) { out.push(escapeHtml(raw)); continue; }
    let line = escapeHtml(raw);
    line = line.replace(/`([^`]+)`/g, '<code class="rounded bg-muted px-1">$1</code>');
    line = line.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
    line = line.replace(/\*([^*]+)\*/g, "<em>$1</em>");
    line = line.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="text-primary underline" rel="noopener noreferrer" target="_blank">$1</a>');
    const h = line.match(/^(#{1,6})\s+(.*)$/);
    if (h) { if (inList) { out.push("</ul>"); inList = false; } out.push(`<h${h[1].length} class="font-semibold mt-4">${h[2]}</h${h[1].length}>`); continue; }
    if (/^\s*[-*]\s+/.test(line)) {
      if (!inList) { out.push('<ul class="list-disc pl-6">'); inList = true; }
      out.push(`<li>${line.replace(/^\s*[-*]\s+/, "")}</li>`); continue;
    }
    if (inList) { out.push("</ul>"); inList = false; }
    if (line.trim() === "") out.push("<br/>");
    else out.push(`<p>${line}</p>`);
  }
  if (inList) out.push("</ul>");
  if (inCode) out.push("</code></pre>");
  return out.join("\n");
}

function MdTool() {
  const [src, setSrc] = useState("# Hello\n\nType **Markdown** here and see it *rendered* live.\n\n- One\n- Two\n\n`code` and [a link](https://lovable.dev).");
  const html = useMemo(() => renderMd(src), [src]);
  return (
    <ToolShell title="Markdown Preview" description="A simple Markdown editor with live preview. Supports headings, bold, italic, links, lists, inline code and code blocks.">
      <div className="grid gap-4 md:grid-cols-2">
        <Textarea value={src} onChange={(e) => setSrc(e.target.value)} className="min-h-[400px] font-mono text-sm" />
        <div className="prose-sm min-h-[400px] space-y-2 rounded-md border border-border p-4 text-sm" dangerouslySetInnerHTML={{ __html: html }} />
      </div>
    </ToolShell>
  );
}
