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

export const responsiveRules: DevToolbarRule[] = [
  {
    id: "responsive/overflow",
    category: "responsive",
    defaultSeverity: "warning",
    description: "Checks horizontal overflow and viewport escape.",
    run: ({ document, root, window }) => {
      const issues = [];
      if (document.documentElement.scrollWidth > window.innerWidth + 2)
        issues.push(
          createIssue({
            ruleId: "responsive/document-overflow",
            category: "responsive",
            severity: "error",
            title: "Page has horizontal overflow",
            message: `Document width ${document.documentElement.scrollWidth}px exceeds viewport ${window.innerWidth}px.`,
            recommendation: "Inspect fixed widths, transforms, long text and overflowing media.",
          }),
        );
      for (const element of root.querySelectorAll("body *")) {
        if (!isVisible(element)) continue;
        const rect = element.getBoundingClientRect();
        if (rect.right > window.innerWidth + 8 || rect.left < -8) {
          issues.push(
            createIssue({
              ruleId: "responsive/element-overflow",
              category: "responsive",
              severity: "warning",
              title: "Element extends outside the viewport",
              message: `Element bounds are ${Math.round(rect.left)}px to ${Math.round(rect.right)}px in a ${window.innerWidth}px viewport.`,
              element,
              recommendation:
                "Use fluid sizing, wrapping, max-width, or an intentional scroll container.",
            }),
          );
          if (issues.length >= 20) break;
        }
      }
      return issues;
    },
  },
];
