// Adapted from jalcoui (MIT) — github.com/jal-co/ui
//
// Shared tokenizer for DiffViewer. Reuses the same `prism-react-renderer`
// bundle that `PrettyCode` ships — no second highlighter is loaded. We
// also re-import `PrettyCode`'s grammar-registration hook so `bash`,
// `ruby`, `java`, `php` work in diffs without duplicating the dynamic
// imports.

import { useMemo } from 'react';
import type { Language } from 'prism-react-renderer';
import { useEnsurePrismLanguages } from '../../PrettyCode/registerPrismLanguages';

/**
 * Normalize a free-form language string into a Prism language key. Falls
 * back to `text` when the key isn't one Prism knows about.
 */
export function normalizeLanguage(language: string | undefined): Language {
  if (!language) return 'text' as Language;
  const lang = language.toLowerCase();
  switch (lang) {
    case 'js':
      return 'javascript' as Language;
    case 'ts':
      return 'typescript' as Language;
    case 'py':
      return 'python' as Language;
    case 'rb':
      return 'ruby' as Language;
    case 'sh':
    case 'shell':
      return 'bash' as Language;
    case 'html':
    case 'xml':
      return 'markup' as Language;
    case 'md':
      return 'markdown' as Language;
    case 'yml':
      return 'yaml' as Language;
    case 'golang':
      return 'go' as Language;
    default:
      return lang as Language;
  }
}

/**
 * Subscribe to PrettyCode's extra-grammar loader and return the resolved
 * Prism language key. The component re-renders once `bash`/`ruby`/… are
 * registered so the first paint isn't stuck on plain text.
 */
export function useDiffLanguage(language: string | undefined): Language {
  useEnsurePrismLanguages();
  return useMemo(() => normalizeLanguage(language), [language]);
}
