import type { AddressContact } from "../types";

/**
 * Generates a vCard 3.0 string for a contact and triggers a file download.
 */
export function downloadVCard(contact: AddressContact): void {
  const lines: string[] = ["BEGIN:VCARD", "VERSION:3.0"];

  // Full name — use company as fallback if no personal name
  const displayName = contact.name || contact.company || "Contact";
  lines.push(`FN:${esc(displayName)}`);

  // Structured name — try to split first/last (best-effort)
  const nameParts = displayName.trim().split(/\s+/);
  const last =
    nameParts.length > 1 ? (nameParts[nameParts.length - 1] ?? "") : "";
  const first =
    nameParts.length > 1
      ? nameParts.slice(0, -1).join(" ")
      : (nameParts[0] ?? "");
  lines.push(`N:${esc(last)};${esc(first)};;;`);

  if (contact.company) {
    lines.push(
      `ORG:${esc(contact.company)}${contact.department ? `;${esc(contact.department)}` : ""}`,
    );
  }

  if (contact.role) {
    lines.push(`TITLE:${esc(contact.role)}`);
  }

  if (contact.phone) {
    lines.push(`TEL;TYPE=WORK,VOICE:${esc(contact.phone)}`);
  }

  if (contact.phone2) {
    lines.push(`TEL;TYPE=WORK,VOICE,pref:${esc(contact.phone2)}`);
  }

  if (contact.email) {
    lines.push(`EMAIL;TYPE=WORK,INTERNET:${esc(contact.email)}`);
  }

  if (contact.email2) {
    lines.push(`EMAIL;TYPE=WORK,INTERNET,pref:${esc(contact.email2)}`);
  }

  if (contact.address) {
    // ADR: PO Box;Extended;Street;City;Region;PostCode;Country
    lines.push(`ADR;TYPE=WORK:;;${esc(contact.address)};;;;`);
  }

  if (contact.website) {
    lines.push(`URL:${esc(contact.website)}`);
  }

  if (contact.notes) {
    // Fold long notes
    lines.push(`NOTE:${esc(contact.notes)}`);
  }

  // Contact persons as additional notes
  if (contact.contactPersons && contact.contactPersons.length > 0) {
    const cpNote = contact.contactPersons
      .map(
        (cp) =>
          `${cp.name}${cp.department ? ` [${cp.department}]` : ""}${cp.role ? ` (${cp.role})` : ""}${cp.email ? ` <${cp.email}>` : ""}${cp.phone ? ` ${cp.phone}` : ""}`,
      )
      .join("; ");
    lines.push(`NOTE:Persoane contact: ${esc(cpNote)}`);
  }

  lines.push(`REV:${new Date().toISOString()}`);
  lines.push("END:VCARD");

  const vcfContent = lines.join("\r\n");
  const blob = new Blob([vcfContent], { type: "text/vcard;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${displayName
    .replace(/[^a-zA-Z0-9\s-]/g, "")
    .trim()
    .replace(/\s+/g, "_")}.vcf`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

/** Escape special characters for vCard values */
function esc(value: string): string {
  return value
    .replace(/\\/g, "\\\\")
    .replace(/,/g, "\\,")
    .replace(/;/g, "\\;")
    .replace(/\n/g, "\\n");
}
