import { useEffect, useRef, useState } from 'react'; import { correctionFieldHints, fieldLabelMatches, revealCorrectionTarget, } from '@/lib/field-corrections'; type Correction = { message: string; targets: { id: string; label: string }[] }; let nextId = 0; function labelOf( control: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, ) { const label = control.labels?.[0]; if (label) { const copy = label.cloneNode(true) as HTMLElement; copy.querySelectorAll( 'input,select,textarea,button,[role="alert"],.sr-only', ).forEach((n) => n.remove()); return ( copy.textContent?.replace(/\s+/g, ' ').trim() || control.getAttribute('aria-label') || '' ); } return control.getAttribute('aria-label') || ''; } /** Maps live, existing messages to real controls; no inferred financial validations. */ export default function PortalCorrections() { const marker = useRef(null); const [items, setItems] = useState([]); const previous = useRef(''); useEffect(() => { const root = marker.current?.closest('#portal-content'); if (!root) return; let pending = 0; const collect = () => { pending = 0; const controls = [ ...root.querySelectorAll< HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement >('input:not([type="hidden"]),select,textarea'), ].filter( (c) => !c.disabled && !c.closest('[hidden],[aria-hidden="true"]'), ); const names = controls.map((c) => ({ control: c, label: labelOf(c), })); const target = (c: (typeof controls)[number], label: string) => { if (!c.id) c.id = `portal-correction-field-${++nextId}`; const group = c.closest('fieldset,[role="group"]'); const context = group?.querySelector('legend')?.textContent?.trim() || group?.getAttribute('aria-label') || ''; return { id: c.id, label: context ? `${label} — ${context}` : label, }; }; const grouped = new Map(); const add = (message: string, targets: Correction['targets']) => { if (!message || !targets.length) return; const item = grouped.get(message) ?? { message, targets: [] }; for (const t of targets) if (!item.targets.some((a) => a.id === t.id)) item.targets.push(t); grouped.set(message, item); }; for (const { control, label } of names) { if (control.getAttribute('aria-invalid') !== 'true') continue; const messages = ( control.getAttribute('aria-describedby') ?? '' ) .split(/\s+/) .map((id) => document.getElementById(id)?.textContent?.trim(), ) .filter(Boolean); const local = control .closest('label') ?.querySelector('[role="alert"]') ?.textContent?.trim(); add( messages.join(' ') || local || 'Confira o valor indicado.', [target(control, label || 'Campo indicado')], ); } for (const node of root.querySelectorAll( '[data-correction-message],[role="alert"]', )) { if ( node.closest( '[data-correction-summary],[hidden],[aria-hidden="true"]', ) ) continue; const message = node.dataset.correctionMessage || node.textContent?.replace(/\s+/g, ' ').trim() || ''; if (!message) continue; const hints = correctionFieldHints(message); const matches = names.filter( ({ label }) => label && hints.some((h) => fieldLabelMatches(label, h)), ); // Restrict explicit product/parcel diagnostics to the matching real group, if present. const index = /produto\s+(\d+)|parcela\s+(\d+)/i.exec(message); const indexed = index ? matches.filter(({ control }) => { const group = control.closest( 'fieldset,[role="group"],[aria-label]', ); const name = group?.getAttribute('aria-label') || group?.querySelector('legend')?.textContent || ''; return new RegExp( `(?:produto|parcela)\\s+${index[1] || index[2]}\\b`, 'i', ).test(name); }) : []; add( message, (indexed.length ? indexed : matches).map( ({ control, label }) => target(control, label), ), ); } const next = [...grouped.values()]; const serial = JSON.stringify(next); if (serial !== previous.current) { previous.current = serial; setItems(next); } }; const schedule = () => { if (!pending) pending = requestAnimationFrame(collect); }; const observer = new MutationObserver((records) => { if ( records.some( (r) => !( r.target instanceof Element ? r.target : r.target.parentElement )?.closest('[data-correction-summary]'), ) ) schedule(); }); observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['aria-invalid', 'aria-describedby', 'hidden'], }); root.addEventListener('input', schedule); root.addEventListener('change', schedule); collect(); return () => { observer.disconnect(); root.removeEventListener('input', schedule); root.removeEventListener('change', schedule); if (pending) cancelAnimationFrame(pending); }; }, []); return (
{items.length > 0 && (

Falta preencher ou corrigir

Use as ligações para abrir a secção e chegar ao campo indicado.

)}
); }