import { ExternalLink, Phone, Reply } from "lucide-react";
import type { TemplateComponent } from "@/lib/types";

/** WhatsApp-style rendering of a template (or a resolved preview). */
export function TemplateBubble({
  header,
  body,
  footer,
  buttons,
}: {
  header?: string | null;
  body: string;
  footer?: string | null;
  buttons?: { type?: string; text: string }[];
}) {
  return (
    <div className="max-w-[320px] rounded-lg rounded-tl-none bg-white text-[14px] leading-snug text-[#111b21] shadow-sm">
      <div className="space-y-1.5 px-3 pb-2 pt-2.5">
        {header && <div className="font-semibold">{header}</div>}
        <div className="whitespace-pre-wrap break-words">{body || <span className="text-[#8696a0]">Message body</span>}</div>
        {footer && <div className="text-[12.5px] text-[#667781]">{footer}</div>}
      </div>
      {buttons && buttons.length > 0 && (
        <div className="divide-y divide-[#e9edef] border-t border-[#e9edef]">
          {buttons.map((b, i) => (
            <div key={i} className="flex items-center justify-center gap-1.5 py-2 text-[13.5px] font-medium text-[#027eb5]">
              {b.type === "URL" ? <ExternalLink className="size-3.5" /> : b.type === "PHONE_NUMBER" ? <Phone className="size-3.5" /> : <Reply className="size-3.5" />}
              {b.text || "Button"}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/** Chat-wallpaper frame for previews. */
export function PreviewFrame({ children }: { children: React.ReactNode }) {
  return <div className="rounded-xl bg-[#efeae2] p-4 [background-image:radial-gradient(#d9d2c5_1px,transparent_1px)] [background-size:14px_14px]">{children}</div>;
}

export function componentsToBubble(components: TemplateComponent[]) {
  const h = components.find((c) => c.type === "HEADER");
  return {
    header: h ? (h.format === "TEXT" ? (h.text ?? "") : `[${String(h.format).toLowerCase()}]`) : null,
    body: components.find((c) => c.type === "BODY")?.text ?? "",
    footer: components.find((c) => c.type === "FOOTER")?.text ?? null,
    buttons: (components.find((c) => c.type === "BUTTONS")?.buttons ?? []).map((b) => ({ type: b.type, text: b.text })),
  };
}
