import type { CheckLink, CheckResult, CheckStatus, EdmCheck } from "../types";
import { EXPECTED_SOCIAL, socialPlatform } from "../htmlUtils";

export const socialMediaCheck: EdmCheck = {
  id: "socialMedia",
  label: "Social media check",
  description:
    "Detects links to social platforms by their domain (Facebook, Instagram, TikTok, YouTube). Flags any of these four that are missing and any social link with no icon image. Extra platforms are allowed and previewed.",
  run: ({ doc }): CheckResult => {
    const links: CheckLink[] = [];
    const found = new Set<string>();
    let iconless = 0;

    for (const a of Array.from(doc.querySelectorAll("a"))) {
      const href = a.getAttribute("href") ?? "";
      const platform = href ? socialPlatform(href) : null;
      if (!platform) continue;
      found.add(platform);
      const hasIcon = a.querySelector("img") !== null;
      if (!hasIcon) iconless++;
      links.push({
        label: hasIcon ? platform : `${platform} (no icon image)`,
        href,
        present: true,
        isMergeTag: false,
      });
    }

    const missing = EXPECTED_SOCIAL.filter((p) => !found.has(p));
    const messages: string[] = [
      `Found ${found.size}/${EXPECTED_SOCIAL.length} expected platforms${links.length > found.size ? ` (${links.length} social links total)` : ""}.`,
    ];
    let status: CheckStatus = "pass";
    if (missing.length) {
      messages.push(`Missing: ${missing.join(", ")}.`);
      status = "warning";
    }
    if (iconless) {
      messages.push(`${iconless} social link(s) have no <img> icon.`);
      status = "warning";
    }
    if (!links.length) {
      messages.push("No social media links found at all.");
      status = "warning";
    }

    return { status, messages, links };
  },
};
