// ── TamilCharacterPicker ───────────────────────────────────────────────────────
// On-screen Tamil character insertion tool for the reviewer edit interface.
// Primary use: fixing missing pulli on pasted text. Not a full keyboard.

const TAMIL_VOWELS = ['அ', 'ஆ', 'இ', 'ஈ', 'உ', 'ஊ', 'எ', 'ஏ', 'ஐ', 'ஒ', 'ஓ', 'ஔ'];
const TAMIL_AAYTHAM = ['ஃ'];
const TAMIL_CONSONANTS_PULLI = ['க்', 'ங்', 'ச்', 'ஞ்', 'ட்', 'ண்', 'த்', 'ந்', 'ப்', 'ம்', 'ய்', 'ர்', 'ல்', 'வ்', 'ழ்', 'ள்', 'ற்', 'ன்'];
const TAMIL_CONSONANTS_PLAIN = ['க', 'ங', 'ச', 'ஞ', 'ட', 'ண', 'த', 'ந', 'ப', 'ம', 'ய', 'ர', 'ல', 'வ', 'ழ', 'ள', 'ற', 'ன'];
const TAMIL_VOWEL_SIGNS = ['ா', 'ி', 'ீ', 'ு', 'ூ', 'ெ', 'ே', 'ை', 'ொ', 'ோ', 'ௌ'];
const PULLI = '்'; // standalone pulli character

function TamilCharacterPicker({ targetRef }) {
  const [flash, setFlash] = React.useState(null);

  function insertChar(char) {
    const el = targetRef.current;
    if (!el) return;

    const start = el.selectionStart;
    const end = el.selectionEnd;
    const val = el.value;

    const proto = el.tagName.toLowerCase() === 'textarea'
      ? window.HTMLTextAreaElement.prototype
      : window.HTMLInputElement.prototype;
    const nativeInputValueSetter = Object.getOwnPropertyDescriptor(proto, 'value').set;

    const newVal = val.slice(0, start) + char + val.slice(end);
    nativeInputValueSetter.call(el, newVal);
    el.dispatchEvent(new Event('input', { bubbles: true }));

    const newPos = start + char.length;
    el.setSelectionRange(newPos, newPos);
    el.focus();

    setFlash(char);
    setTimeout(() => setFlash(null), 150);
  }

  function handleBackspace(e) {
    e.preventDefault();
    const el = targetRef.current;
    if (!el) return;

    const start = el.selectionStart;
    const end = el.selectionEnd;
    const val = el.value;

    let removeStart = start;
    if (start === end && start > 0) {
      // Use Intl.Segmenter to remove one grapheme cluster (handles combining marks correctly)
      const before = val.slice(0, start);
      if (typeof Intl !== 'undefined' && Intl.Segmenter) {
        const segs = [...new Intl.Segmenter().segment(before)];
        if (segs.length > 0) {
          const last = segs[segs.length - 1];
          removeStart = last.index;
        } else {
          removeStart = start - 1;
        }
      } else {
        removeStart = start - 1;
      }
    }

    const proto = el.tagName.toLowerCase() === 'textarea'
      ? window.HTMLTextAreaElement.prototype
      : window.HTMLInputElement.prototype;
    const nativeInputValueSetter = Object.getOwnPropertyDescriptor(proto, 'value').set;

    const newVal = val.slice(0, removeStart) + val.slice(Math.max(end, start));
    nativeInputValueSetter.call(el, newVal);
    el.dispatchEvent(new Event('input', { bubbles: true }));
    el.setSelectionRange(removeStart, removeStart);
    el.focus();
  }

  function handleSpace(e) {
    e.preventDefault();
    insertChar(' ');
  }

  function CharBtn({ char, highlight }) {
    return (
      <button
        className={`tcp-char-btn${highlight ? ' tcp-char-btn--highlight' : ''}${flash === char ? ' tcp-char-btn--flash' : ''}`}
        onMouseDown={(e) => { e.preventDefault(); insertChar(char); }}
      >
        {char}
      </button>
    );
  }

  return (
    <div className="tcp-panel">
      <div className="tcp-section">
        <div className="tcp-section-label">உயிர் எழுத்து <span className="tcp-section-label-en">(Vowels)</span></div>
        <div className="tcp-row">
          {TAMIL_VOWELS.map((c) => <CharBtn key={c} char={c} />)}
        </div>
      </div>

      <div className="tcp-section">
        <div className="tcp-section-label">ஃ <span className="tcp-section-label-en">(Aaytham)</span></div>
        <div className="tcp-row">
          {TAMIL_AAYTHAM.map((c) => <CharBtn key={c} char={c} />)}
        </div>
      </div>

      <div className="tcp-section">
        <div className="tcp-section-label">மெய் எழுத்து <span className="tcp-section-label-en">(Consonants with pulli)</span></div>
        <div className="tcp-row tcp-row--wrap">
          {TAMIL_CONSONANTS_PULLI.map((c) => <CharBtn key={c} char={c} />)}
        </div>
      </div>

      <div className="tcp-section">
        <div className="tcp-section-label tcp-section-label--secondary">
          Consonants <span className="tcp-section-label-en">(no pulli)</span>
        </div>
        <div className="tcp-row tcp-row--wrap">
          {TAMIL_CONSONANTS_PLAIN.map((c) => <CharBtn key={c} char={c} />)}
        </div>
      </div>

      <div className="tcp-section">
        <div className="tcp-section-label tcp-section-label--secondary">
          Vowel signs <span className="tcp-section-label-en">(combining)</span>
        </div>
        <div className="tcp-row">
          {TAMIL_VOWEL_SIGNS.map((c) => <CharBtn key={c} char={c} />)}
        </div>
      </div>

      <div className="tcp-section tcp-section--tools">
        <div className="tcp-section-label tcp-section-label--secondary">Tools</div>
        <div className="tcp-row">
          <button
            className="tcp-char-btn tcp-char-btn--pulli"
            title="Add pulli (்) — U+0BCD"
            onMouseDown={(e) => { e.preventDefault(); insertChar(PULLI); }}
          >
            ் <span className="tcp-pulli-label">add pulli</span>
          </button>
          <button
            className="tcp-char-btn tcp-char-btn--tool"
            onMouseDown={handleBackspace}
          >
            ⌫ Backspace
          </button>
          <button
            className="tcp-char-btn tcp-char-btn--tool"
            onMouseDown={handleSpace}
          >
            ␣ Space
          </button>
        </div>
      </div>
    </div>
  );
}
