"use client";

import CustomButton from "@/components/common/CustomButton";
import type { ResumeTemplateId } from "@/types/resume";

function printResume(templateId: ResumeTemplateId, filename: string) {
  const source = document.querySelector<HTMLElement>("[data-resume-document]");
  if (!source) return;
  const printWindow = window.open("", "_blank");
  if (!printWindow) return;

  const styles = Array.from(
    document.querySelectorAll('link[rel="stylesheet"], style'),
  )
    .map((node) => node.outerHTML)
    .join("");
  const landscape = templateId === "executive-landscape";
  const documentClone = source.cloneNode(true) as HTMLElement;
  documentClone
    .querySelectorAll<HTMLElement>("[data-resume-paper]")
    .forEach((paper) => {
      paper.style.display = "block";
    });

  printWindow.document.write(
    `<!doctype html><html><head><title>${filename}</title>${styles}<style>@page { size: A4 ${landscape ? "landscape" : "portrait"}; margin: 8mm; } html, body { margin: 0; background: #fff; -webkit-print-color-adjust: exact; print-color-adjust: exact; } [data-resume-document] { display: block !important; width: auto !important; max-width: none !important; height: auto !important; min-height: 0 !important; aspect-ratio: auto !important; overflow: visible !important; padding: 0 !important; box-shadow: none !important; } [data-resume-document] main { display: block !important; overflow: visible !important; padding-top: 4mm !important; } .resume-document { display: block !important; } .resume-page { display: block !important; width: auto !important; min-height: 0 !important; box-sizing: border-box; break-after: page; page-break-after: always; } .resume-page:last-child { break-after: auto; page-break-after: auto; } img { max-width: 100%; }</style></head><body>${documentClone.outerHTML}<script>window.onload = () => { window.print(); window.onafterprint = () => window.close(); };</script></body></html>`,
  );
  printWindow.document.close();
}

export function DownloadButton({
  templateId,
  filename,
}: {
  templateId: ResumeTemplateId;
  filename: string;
}) {
  return (
    <CustomButton
      btnText="Download Resume"
      className="bg-[#00A946]"
      addAnimation={false}
      onClick={() => printResume(templateId, filename)}
    />
  );
}
