import type { DevToolbarRule } from "./types.ts";
import { createIssue } from "./helpers.ts";

export const mediaRules: DevToolbarRule[] = [
  {
    id: "media/basics",
    category: "media",
    defaultSeverity: "warning",
    description: "Checks video, audio and iframe accessibility.",
    run: ({ root }) => {
      const issues = [];
      for (const video of root.querySelectorAll<HTMLVideoElement>("video")) {
        if (video.autoplay && !video.muted)
          issues.push(
            createIssue({
              ruleId: "media/autoplay-sound",
              category: "media",
              severity: "error",
              title: "Autoplay video is not muted",
              message: "Autoplaying sound is disruptive and commonly blocked by browsers.",
              element: video,
              recommendation: "Remove autoplay or add muted.",
            }),
          );
        if (!video.controls && !video.autoplay)
          issues.push(
            createIssue({
              ruleId: "media/no-controls",
              category: "media",
              severity: "warning",
              title: "Video has no controls",
              message: "Users may be unable to play, pause or seek.",
              element: video,
              recommendation: "Add controls or provide equivalent custom controls.",
            }),
          );
        if (!video.poster)
          issues.push(
            createIssue({
              ruleId: "media/no-poster",
              category: "media",
              severity: "suggestion",
              title: "Video has no poster",
              message: "A poster can improve perceived loading and visual quality.",
              element: video,
              recommendation: "Provide an optimized poster image.",
              confidence: "medium",
            }),
          );
        if (!video.querySelector('track[kind="captions"]'))
          issues.push(
            createIssue({
              ruleId: "media/no-captions",
              category: "media",
              severity: "warning",
              title: "Video has no captions track",
              message: "Spoken content may be inaccessible.",
              element: video,
              recommendation: "Add a captions track when the video contains speech.",
            }),
          );
      }
      for (const iframe of root.querySelectorAll<HTMLIFrameElement>("iframe:not([title])"))
        issues.push(
          createIssue({
            ruleId: "media/iframe-title",
            category: "media",
            severity: "error",
            title: "Iframe is missing a title",
            message: "Assistive technology cannot identify the embedded content.",
            element: iframe,
            recommendation: "Add a concise title attribute.",
          }),
        );
      return issues;
    },
  },
];
