import type { Block } from '@templatical/types';
import type { SectionBlock } from '@templatical/types';
import type { TemplateContent } from '@templatical/types';
import type { TemplateSettings } from '@templatical/types';

export declare const ACCESSIBILITY_RULES: Rule[];

/** Options consumed only by the accessibility linter. */
export declare interface AccessibilityLintOptions {
    rules?: RuleOverrides;
    thresholds?: Partial<LintThresholds>;
}

export declare interface AnchorInfo {
    href: string;
    text: string;
    target: string | null;
    rel: string | null;
    /** True if the anchor wraps an image with non-empty alt. */
    hasImageWithAlt: boolean;
}

export declare const DEFAULT_A11Y_THRESHOLDS: LintThresholds;

export declare const DEFAULT_NON_PRODUCTION_HOSTS: string[];

export declare type Dictionary = typeof en;

/**
 * English vague-text dictionaries. Treated as the source of truth — other
 * locales annotate themselves `typeof en` so missing/extra phrases fail
 * typecheck.
 *
 * Phrases are matched case-insensitively against trimmed text content.
 */
declare const en: {
    vagueLinkText: string[];
    vagueButtonLabels: string[];
    /**
     * Action verbs that signal a linked image's alt describes the link
     * destination, not just the visual subject. Used by `img-linked-no-context`.
     * Stored lowercase; tokenized matching is case-insensitive.
     */
    linkedImageActionHints: string[];
};

/**
 * English rule messages. The source of truth — other locales annotate
 * themselves `typeof en` so missing or extra keys fail typecheck.
 *
 * Templates use `{name}` placeholders, interpolated by `formatMessage`.
 */
declare const en_2: {
    "a11y.img-missing-alt": string;
    "a11y.img-alt-is-filename": string;
    "a11y.img-alt-too-long": string;
    "a11y.img-decorative-needs-empty-alt": string;
    "a11y.img-linked-no-context": string;
    "a11y.heading-empty": string;
    "a11y.heading-skip-level": string;
    "a11y.heading-multiple-h1": string;
    "a11y.link-empty": string;
    "a11y.link-vague-text": string;
    "a11y.link-href-empty": string;
    "a11y.link-target-blank-no-rel": string;
    "a11y.link-nested-anchor": string;
    "a11y.text-all-caps": string;
    "a11y.text-justified": string;
    "a11y.text-low-contrast": string;
    "a11y.text-too-small": string;
    "a11y.button-vague-label": string;
    "a11y.button-touch-target": string;
    "a11y.button-low-contrast": string;
    "a11y.missing-preheader": string;
};

/**
 * English structure-rule messages. The source of truth — other locales
 * annotate themselves `typeof en` so missing or extra keys fail typecheck.
 *
 * Templates use `{name}` placeholders, interpolated by `formatMessage`.
 */
declare const en_3: {
    "structure.duplicate-block-id": string;
    "structure.section-column-mismatch": string;
    "structure.nested-section": string;
    "structure.empty-section": string;
    "structure.empty-column": string;
};

/**
 * English link-rule messages. The source of truth — other locales annotate
 * themselves `typeof en` so missing or extra keys fail typecheck.
 *
 * Templates use `{name}` placeholders, interpolated by `formatLinkMessage`.
 */
declare const en_4: {
    "link.javascript-protocol": string;
    "link.unsupported-protocol": string;
    "link.malformed-mailto": string;
    "link.malformed-tel": string;
    "link.localhost-or-staging": string;
    "link.relative-url": string;
};

/**
 * Extract every anchor from a TipTap-style HTML fragment. Used by
 * link-* rules. Doesn't try to be a full DOM — only the data the rules
 * need.
 *
 * Nested `<a>` is invalid HTML; htmlparser2 follows the HTML5 spec and
 * emits an implicit `</a>` when a second `<a>` opens, so anchors are
 * effectively flat siblings. We mirror that with a single in-flight
 * anchor (no stack); a defensive finalize-on-reopen handles the
 * theoretical case where the parser ever stops emitting the implicit
 * close. Detecting nested-anchor markup as its own concern lives in
 * the `a11y.link-nested-anchor` rule, which inspects the raw input
 * before this normalization.
 */
export declare function extractAnchors(html: string): AnchorInfo[];

/**
 * Strip tags and return the visible text content of an HTML fragment.
 * Used by heading-empty and other text-presence rules.
 */
export declare function extractText(html: string): string;

export declare function formatLinkMessage(locale: string, ruleId: LinkRuleMessageId, params?: Record<string, string | number>): string;

/**
 * Resolve a localized message for a rule. `params` interpolate `{name}`
 * placeholders. Falls back to English when the locale doesn't ship the
 * key (shouldn't happen — the parity test enforces it).
 */
export declare function formatMessage(locale: string, ruleId: RuleMessageId, params?: Record<string, string | number>): string;

export declare function formatStructureMessage(locale: string, ruleId: StructureRuleMessageId, params?: Record<string, string | number>): string;

/**
 * WCAG 2.1 sRGB relative-luminance contrast.
 *
 * Inputs are hex strings (`#rgb`, `#rrggbb`, optional leading `#`).
 * Returns the contrast ratio (1–21) per WCAG, or `NaN` if either input
 * cannot be parsed as an opaque solid hex color.
 *
 * The codebase uses OKLch for design tokens, but contrast math is
 * sRGB-defined; mixing the two gives incorrect results.
 */
export declare function getContrastRatio(fg: string, bg: string): number;

/**
 * Returns a dictionary that unions every registered locale. Vague phrases
 * are universally vague — a German-locale email with an English "Click here"
 * CTA, or an English email with a French "cliquez ici", is still a vague
 * CTA, so the rule must detect across languages regardless of editor locale.
 *
 * The `locale` argument is accepted for API symmetry and future use (e.g.
 * weighted matching) but currently doesn't change the returned set.
 */
export declare function getDictionary(_locale: string): Dictionary;

export declare function getLinkMessages(locale: string): LinkMessageMap;

export declare function getMessages(locale: string): MessageMap;

export declare function getStructureMessages(locale: string): StructureMessageMap;

/**
 * Whether the raw HTML contains an `<a>` opened inside another open
 * `<a>` — invalid markup that htmlparser2 silently normalizes by
 * emitting an implicit `</a>` before the inner open. `extractAnchors`
 * runs against the normalized parse and therefore can't distinguish
 * nested-from-sibling input; this helper inspects the raw text so the
 * `a11y.link-nested-anchor` rule can flag the structural problem.
 *
 * Tokenization here ignores anchor-like tokens inside HTML comments,
 * which is enough for TipTap email-template HTML. CDATA, `<script>`,
 * and attribute-value occurrences aren't expected in this surface.
 */
export declare function hasNestedAnchors(html: string): boolean;

/**
 * `true` when no linter would run for the given options — either the
 * global `disabled` flag is set, or every per-tool key is `false`.
 *
 * The editor uses this to skip lazy-loading `@templatical/quality`, hide
 * the Issues sidebar tab, and suppress inline canvas badges. Headless
 * callers can use it to short-circuit before any linter call.
 */
export declare function isLintFullyDisabled(options: LintOptions | undefined): boolean;

export declare function isOpaqueHex(input: string | undefined | null): boolean;

export declare const LINK_RULES: Rule[];

export declare type LinkMessageMap = typeof en_4;

export declare type LinkRuleMessageId = keyof LinkMessageMap;

/** Options consumed only by the links linter. */
export declare interface LinksLintOptions {
    rules?: RuleOverrides;
    /**
     * Host patterns that should flag as "staging / non-production".
     * Each entry is a glob-style pattern matched against the URL host.
     * `*` matches any run of characters (including `.`), so `*.staging.*`
     * matches `app.staging.example.com`.
     *
     * Default: ['localhost', '127.0.0.1', '0.0.0.0', '*.local',
     *           '*.staging.*', '*.dev.*']
     */
    nonProductionHosts?: string[];
}

export declare function lintAccessibility(content: TemplateContent, options?: LintOptions): LintIssue[];

export declare interface LintIssue {
    /** Block id, or null for template-level issues. */
    blockId: string | null;
    ruleId: string;
    severity: Exclude<Severity, "off">;
    message: string;
    fix?: LintPatch;
}

export declare function lintLinks(content: TemplateContent, options?: LintOptions): LintIssue[];

export declare interface LintOptions {
    /**
     * Fully disable linting. When true, the editor skips lazy-loading the
     * package, hides the sidebar tab, and suppresses inline badges.
     */
    disabled?: boolean;
    /** Locale for vague-text dictionaries and message text. Falls back to `en`. */
    locale?: string;
    /**
     * Accessibility linter config. Set to `false` to disable the whole
     * `lintAccessibility` linter without enumerating its rules.
     */
    accessibility?: false | AccessibilityLintOptions;
    /**
     * Structure linter config. Set to `false` to disable the whole
     * `lintStructure` linter without enumerating its rules.
     */
    structure?: false | StructureLintOptions;
    /**
     * Links linter config. Set to `false` to disable the whole `lintLinks`
     * linter without enumerating its rules.
     */
    links?: false | LinksLintOptions;
}

export declare interface LintPatch {
    description: string;
    apply: (ctx: LintPatchContext) => void;
}

export declare interface LintPatchContext {
    updateBlock: (blockId: string, patch: Partial<Block>) => void;
    updateSettings: (patch: Partial<TemplateSettings>) => void;
    removeBlock: (blockId: string) => void;
}

export declare function lintStructure(content: TemplateContent, options?: LintOptions): LintIssue[];

/**
 * Run every linter in the package — accessibility, structure, and links —
 * against `content` and return the merged issue list.
 *
 * This is the single entry point callers should prefer. CI guards, the
 * editor's live linter, and headless consumers all funnel through here, so
 * a new linter category is picked up everywhere by registering it in this
 * one fan-out — no consumer has to learn about the new function.
 *
 * Per-category options (`options.accessibility`, `options.structure`,
 * `options.links`) and the global `options.disabled` flag are forwarded
 * unchanged; each sub-linter already short-circuits when its category is
 * `false`, so the per-tool calls below are cheap no-ops when disabled.
 *
 * Issue order is stable: accessibility first, then structure, then links.
 */
export declare function lintTemplate(content: TemplateContent, options?: LintOptions): LintIssue[];

export declare interface LintThresholds {
    altMaxLength: number;
    minFontSize: number;
    allCapsMinLength: number;
    minTouchTargetPx: number;
}

export declare type MessageMap = typeof en_2;

export declare function parseHex(input: string | undefined | null): Rgb | null;

export declare interface ResolvedLinksOptions {
    nonProductionHosts: string[];
}

export declare interface ResolvedOptions {
    locale: string;
    rules: RuleOverrides;
    thresholds: LintThresholds;
    links: ResolvedLinksOptions;
    /** Returns the effective severity for a rule (override or default). */
    severity: (ruleId: string) => Severity;
}

declare interface Rgb {
    r: number;
    g: number;
    b: number;
}

export declare interface Rule {
    meta: RuleMeta;
    /** Block-level rule. Returns a hit or null. */
    block?: (block: Block, ctx: WalkContext, opts: ResolvedOptions) => RuleHit | null;
    /** Template-level rule. Runs once after the walk. */
    template?: (content: TemplateContent, opts: ResolvedOptions) => RuleHit[];
}

/**
 * What a rule emits per match. The orchestrator combines this with the
 * rule's `meta` (for `ruleId` + default severity) and resolves the
 * localized message via the active locale's message map.
 */
export declare interface RuleHit {
    blockId: string | null;
    /** Interpolation values for the rule's localized message template. */
    params?: Record<string, string | number>;
    fix?: LintPatch;
}

export declare type RuleMessageId = keyof MessageMap;

export declare interface RuleMeta {
    /** Stable identifier — used for severity overrides and message lookup. */
    id: string;
    /** Default severity when no override is supplied. */
    severity: Exclude<Severity, "off">;
}

/**
 * Per-rule severity override. Set a rule to `'off'` to disable it.
 * Keys are the full prefixed rule IDs (`a11y.*`, `structure.*`, `link.*`)
 * so a value copied from `LintIssue.ruleId` pastes straight in.
 */
export declare type RuleOverrides = Record<string, Severity>;

export declare type Severity = "error" | "warning" | "info" | "off";

export declare const STRUCTURE_RULES: Rule[];

/** Options consumed only by the structure linter. */
export declare interface StructureLintOptions {
    rules?: RuleOverrides;
}

export declare type StructureMessageMap = typeof en_3;

export declare type StructureRuleMessageId = keyof StructureMessageMap;

export declare const SUPPORTED_DICTIONARY_LOCALES: string[];

export declare const SUPPORTED_LINK_MESSAGE_LOCALES: string[];

export declare const SUPPORTED_MESSAGE_LOCALES: string[];

export declare const SUPPORTED_STRUCTURE_MESSAGE_LOCALES: string[];

export declare interface UrlOccurrence {
    url: string;
    blockId: string;
    source: UrlSource;
    /** Anchor text or block-derived label, if applicable. */
    label?: string;
}

export declare type UrlSource = "anchor" | "button" | "image-link" | "video" | "menu-item" | "social-icon";

export declare type Visitor = (block: Block, ctx: WalkContext) => void;

/**
 * Pure traversal of the block tree. Calls `visit` once per block in
 * document order, providing a `WalkContext` that includes the resolved
 * background color (nearest opaque ancestor) and structural refs.
 *
 * Sections cannot nest (renderer enforces this), so the walker doesn't
 * descend into a section that lives inside a column. Wrappers are descended
 * so composed layout trees are fully visited. Custom blocks are visited but
 * not descended into.
 */
export declare function walkBlocks(content: TemplateContent, visit: Visitor): void;

export declare interface WalkContext {
    parent: Block | null;
    section: SectionBlock | null;
    columnIndex: number | null;
    depth: number;
    /**
     * Nearest opaque ancestor background, or template settings background.
     * Hex string, lowercased.
     */
    resolvedBackgroundColor: string;
    /**
     * Document-level default text color (`settings.textColor`), lowercased hex.
     * A text block that doesn't set its own `color` inherits this, so contrast
     * rules resolve the effective color against it.
     */
    resolvedTextColor: string;
}

/**
 * Visit every URL-bearing field in the template tree.
 *
 * Sources covered:
 *  - anchor      — `<a href>` inside `title.content`, `paragraph.content`,
 *                  `html.content` (parsed via extractAnchors)
 *  - button      — `button.url`
 *  - image-link  — `image.linkUrl` (only when present + non-empty)
 *  - video       — `video.url`
 *  - menu-item   — `menu.items[i].url`
 *  - social-icon — `social.icons[i].url`
 *
 * Each rule iterates this list once and decides per occurrence.
 */
export declare function walkUrls(content: TemplateContent): UrlOccurrence[];

export { }
