'use client';

import { useEffect } from 'react';

const arabicIndicDigits = '٠١٢٣٤٥٦٧٨٩';
const easternArabicDigits = '۰۱۲۳۴۵۶۷۸۹';

function toEnglishDigits(value: string): string {
  return value
    .replace(/[٠-٩]/g, (digit) => String(arabicIndicDigits.indexOf(digit)))
    .replace(/[۰-۹]/g, (digit) => String(easternArabicDigits.indexOf(digit)));
}

function normalizeNumericInput(value: string): string {
  const english = toEnglishDigits(value)
    .replace(/\u066B/g, '.')
    .replace(/\u066C/g, '')
    .replace(/,/g, '');

  // Allow only digits, one optional leading minus, and one decimal separator.
  const hasLeadingMinus = english.startsWith('-');
  const unsigned = english.replace(/-/g, '');
  const sanitized = unsigned.replace(/[^0-9.]/g, '');
  const firstDot = sanitized.indexOf('.');
  const withSingleDot = firstDot === -1
    ? sanitized
    : `${sanitized.slice(0, firstDot + 1)}${sanitized.slice(firstDot + 1).replace(/\./g, '')}`;

  return `${hasLeadingMinus ? '-' : ''}${withSingleDot}`;
}

function enforceEnglishNumberAttrs(input: HTMLInputElement) {
  if (input.type !== 'number') return;
  input.setAttribute('lang', 'en');
  input.setAttribute('dir', 'ltr');
  if (!input.getAttribute('inputmode')) {
    input.setAttribute('inputmode', 'decimal');
  }
}

function enforceEnglishDateAttrs(input: HTMLInputElement) {
  if (input.type !== 'date') return;
  input.setAttribute('lang', 'en');
  input.setAttribute('dir', 'ltr');
}

export default function EnglishNumbersEnforcer() {
  useEffect(() => {
    const enforceExistingInputs = () => {
      document
        .querySelectorAll<HTMLInputElement>('input[type="number"]')
        .forEach((input) => enforceEnglishNumberAttrs(input));
      document
        .querySelectorAll<HTMLInputElement>('input[type="date"]')
        .forEach((input) => enforceEnglishDateAttrs(input));
    };

    const onInputCapture = (event: Event) => {
      const target = event.target;
      if (!(target instanceof HTMLInputElement) || target.type !== 'number') return;

      const normalized = normalizeNumericInput(target.value);
      if (normalized === target.value) return;

      const cursor = target.selectionStart;
      target.value = normalized;
      if (cursor !== null) {
        const nextCursor = Math.min(cursor, normalized.length);
        target.setSelectionRange(nextCursor, nextCursor);
      }
    };

    const onFocusCapture = (event: Event) => {
      const target = event.target;
      if (!(target instanceof HTMLInputElement)) return;
      if (target.type === 'number') {
        enforceEnglishNumberAttrs(target);
      } else if (target.type === 'date') {
        enforceEnglishDateAttrs(target);
      }
    };

    const observer = new MutationObserver(() => {
      enforceExistingInputs();
    });

    enforceExistingInputs();
    document.addEventListener('input', onInputCapture, true);
    document.addEventListener('focus', onFocusCapture, true);
    observer.observe(document.body, { childList: true, subtree: true });

    return () => {
      document.removeEventListener('input', onInputCapture, true);
      document.removeEventListener('focus', onFocusCapture, true);
      observer.disconnect();
    };
  }, []);

  return null;
}
