// oxlint-disable-next-line no-unused-vars
import { Html } from "@elysiajs/html";
import { renderFragment } from "../../base";

export function aiHelperChatResponse(
  response: string,
  history: { role: "user" | "assistant"; content: string }[] = []
): string {
  return renderFragment(
    <>
      <ChatMessage role="assistant" content={response} />
      <input type="hidden" id="chat-history" name="history" value={JSON.stringify(history)} hx-swap-oob="outerHTML" />
    </>
  );
}

export function aiHelperGenerateResponse(
  prompt: string,
  history: { role: "user" | "assistant"; content: string }[] = []
): string {
  const assistantMessage = "I've generated a prompt based on your description! You can see it in the Current Prompt editor below. Feel free to ask me to modify it or explain any part.";

  return renderFragment(
    <>
      <textarea
        id="current-prompt"
        class="mt-3 min-h-37.5 w-full resize-y rounded-md border border-slate-700 bg-slate-800 p-3 font-mono text-xs text-slate-100 focus:border-emerald-500 focus:outline-none"
        placeholder="Paste or write your prompt here. The AI helper can see this and help you improve it."
        hx-swap-oob="outerHTML"
      >
        {prompt}
      </textarea>
      <div id="chat-messages" hx-swap-oob="beforeend">
        <ChatMessage role="assistant" content={assistantMessage} />
      </div>
      <input type="hidden" id="chat-history" name="history" value={JSON.stringify(history)} hx-swap-oob="outerHTML" />
    </>
  );
}

function ChatMessage({ role, content }: { role: "user" | "assistant"; content: string }) {
  const roleClass = role === "user"
    ? "max-w-[85%] self-end rounded-xl bg-indigo-600 px-4 py-3 text-sm leading-relaxed text-white"
    : "max-w-[85%] self-start rounded-xl bg-slate-800 px-4 py-3 text-sm leading-relaxed text-slate-200";

  return <div class={roleClass}>{renderMarkdown(content)}</div>;
}

function renderMarkdown(content: string): string {
  return escapeHtml(content)
    .replace(/```([\s\S]*?)```/g, "<pre class=\"mt-2 mb-2 overflow-x-auto rounded bg-slate-900 p-3 text-xs\">$1</pre>")
    .replace(/`([^`]+)`/g, "<code class=\"rounded bg-slate-900 px-1.5 py-0.5 text-xs\">$1</code>")
    .replace(/\n/g, "<br>");
}

function escapeHtml(text: string): string {
  return text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}
