import { GLYPH_REVEAL, GLYPH_HIDE } from '../glyphs';
import { STRENGTH_LABELS, entropyText, type Strength } from '../../setup/setup-helpers';

/// Returns a teardown fn the caller must invoke on unmount.
export function wirePasswordReveal(form: HTMLElement): () => void {
  const btn = form.querySelector<HTMLButtonElement>('#reveal-password-btn');
  const input = form.querySelector<HTMLInputElement>('#f-password');
  if (!btn || !input) return () => {};

  const handler = () => {
    if (input.type === 'password') {
      input.type = 'text';
      btn.textContent = GLYPH_HIDE;
      btn.title = 'hide';
    } else {
      input.type = 'password';
      btn.textContent = GLYPH_REVEAL;
      btn.title = 'reveal';
    }
  };
  btn.addEventListener('click', handler);

  return () => {
    btn.removeEventListener('click', handler);
    input.type = 'password';
    btn.textContent = GLYPH_REVEAL;
    btn.title = 'reveal';
  };
}

export interface PasswordStrengthOpts {
  scheduleRate: (passphrase: string, cb: (s: Strength) => void) => void;
}

export function wirePasswordStrength(form: HTMLElement, opts: PasswordStrengthOpts): void {
  const input = form.querySelector<HTMLInputElement>('#f-password');
  const row = form.querySelector<HTMLElement>('#strength-bar-row');
  if (!input || !row) return;
  const bar = row.querySelector<HTMLElement>('.strength-bar');
  const label = row.querySelector<HTMLElement>('.strength-label');
  if (!bar || !label) return;

  const update = () => {
    const v = input.value;
    if (!v) {
      row.hidden = true;
      return;
    }
    opts.scheduleRate(v, (s) => {
      if (s.score < 0) { row.hidden = true; return; }
      row.hidden = false;
      // Reset score classes, then add the current one to the bar element.
      bar.className = 'strength-bar';
      const cls = STRENGTH_LABELS[s.score]?.cls ?? 's-very-weak';
      bar.classList.add(cls);
      // Light up segments 0..score (5-segment bar).
      Array.from(bar.children).forEach((seg, i) => {
        (seg as HTMLElement).classList.toggle('lit', i <= s.score);
      });
      const text = STRENGTH_LABELS[s.score]?.text ?? '?';
      label.textContent = `${text} · ${entropyText(s.guessesLog10)}`;
    });
  };

  input.addEventListener('input', update);
  update();
}
