import { describe, expect, test } from 'bun:test';
import { parseLyrics, activeLineIndex } from './lyrics';

describe('parseLyrics', () => {
  test('plain text is not synced and keeps every line, blanks included', () => {
    const { synced, lines } = parseLyrics('first\n\n  second  \n');
    expect(synced).toBe(false);
    expect(lines.map((l) => l.text)).toEqual(['first', '', 'second', '']);
    expect(lines.every((l) => l.timeSec === undefined)).toBe(true);
  });

  test('lrc timestamps parse to seconds, with hundredths', () => {
    const { synced, lines } = parseLyrics('[00:12.50]hello\n[01:03]world');
    expect(synced).toBe(true);
    expect(lines).toEqual([
      { timeSec: 12.5, text: 'hello' },
      { timeSec: 63, text: 'world' },
    ]);
  });

  test('a single-digit fraction is tenths, not thousandths', () => {
    expect(parseLyrics('[00:01.5]x').lines[0]?.timeSec).toBe(1.5);
  });

  test('metadata tags are dropped', () => {
    const { lines } = parseLyrics('[ar:Artist]\n[ti:Title]\n[00:01.00]real');
    expect(lines).toEqual([{ timeSec: 1, text: 'real' }]);
  });

  test('several stamps on one line become several lines, sorted by time', () => {
    const { lines } = parseLyrics('[02:00.00][00:30.00]chorus\n[01:00.00]verse');
    expect(lines).toEqual([
      { timeSec: 30, text: 'chorus' },
      { timeSec: 60, text: 'verse' },
      { timeSec: 120, text: 'chorus' },
    ]);
  });

  test('an untimed line inside a synced file survives, but blanks do not', () => {
    const { lines } = parseLyrics('[00:01.00]a\n\nspoken\n');
    expect(lines.map((l) => l.text)).toEqual(['spoken', 'a']);
  });

  test('an empty timed line is kept — it is a musical rest', () => {
    expect(parseLyrics('[00:10.00]').lines).toEqual([{ timeSec: 10, text: '' }]);
  });
});

describe('activeLineIndex', () => {
  const lines = [
    { timeSec: 10, text: 'a' },
    { timeSec: 20, text: 'b' },
    { timeSec: 30, text: 'c' },
  ];

  test('-1 before the first line', () => {
    expect(activeLineIndex(lines, 0)).toBe(-1);
  });

  test('the 0.2s lookahead highlights fractionally early', () => {
    expect(activeLineIndex(lines, 9.7)).toBe(-1);
    expect(activeLineIndex(lines, 9.9)).toBe(0);
  });

  test('holds the last line past the end', () => {
    expect(activeLineIndex(lines, 25)).toBe(1);
    expect(activeLineIndex(lines, 9999)).toBe(2);
  });

  test('untimed lines never become active', () => {
    expect(activeLineIndex([{ text: 'x' }, { timeSec: 5, text: 'y' }], 60)).toBe(1);
  });
});
