// Participant characterization. Lock updateDoc patch shape for participant ops.

import React from 'react';
import { screen, fireEvent, waitFor, within } from '@testing-library/react';
import '@testing-library/jest-dom';
import { getCalls } from '../__mocks__/firebase/_mock-db';
import { setupReady, addMonsterViaUI, getParticipantForm, startCombatViaUI } from './testHelpers';

function findCallsEnc() {
  return getCalls().filter(c => c.fn === 'updateDoc' && c.path.includes('/encounters/'));
}
function lastEncCall() {
  const calls = findCallsEnc();
  return calls[calls.length - 1];
}
// First participant list item (the participant card <li>).
function firstParticipantItem() {
  const list = screen.getByText('Victim') ||
    [...document.querySelectorAll('li')].find(li => li.querySelector('[title="Remove"]'));
  return list.closest('li');
}

describe('Participant -> Firebase', () => {
  test('addMonster: updateDoc appends participant with full shape', async () => {
    await setupReady();
    await addMonsterViaUI('Goblin', 7, 2);
    const call = lastEncCall();
    expect(call.data.participants).toHaveLength(1);
    const p = call.data.participants[0];
    expect(p).toMatchObject({
      name: 'Goblin', type: 'monster', maxHp: 7, currentHp: 7,
      isActive: true, status: 'conscious', deathSaveSuccesses: 0, deathSaveFailures: 0, conditions: [],
    });
    expect(p).not.toHaveProperty('isNpc');
    expect(p).toHaveProperty('id');
    expect(p).toHaveProperty('initiative');
  });

  test('addMonster: initiative = d20 roll (1-20) + mod', async () => {
    await setupReady();
    await addMonsterViaUI('Orc', 12, 3);
    const p = lastEncCall().data.participants[0];
    expect(p.initiative).toBeGreaterThanOrEqual(4);
    expect(p.initiative).toBeLessThanOrEqual(23);
  });

  test('addMonster as NPC: type npc', async () => {
    await setupReady();
    const form = within(getParticipantForm());
    fireEvent.change(form.getByPlaceholderText('e.g., Dire Wolf'), { target: { value: 'Guard' } });
    fireEvent.click(form.getByLabelText(/Is NPC/i));
    fireEvent.click(form.getByRole('button', { name: /Add to Encounter/i }));
    await waitFor(() => {
      const p = lastEncCall()?.data?.participants?.[0];
      return p && p.name === 'Guard';
    });
    expect(lastEncCall().data.participants[0].type).toBe('npc');
    expect(lastEncCall().data.participants[0]).not.toHaveProperty('isNpc');
  });

  test('deleteParticipant: updateDoc removes participant', async () => {
    await setupReady();
    await addMonsterViaUI('Victim', 10, 0);
    fireEvent.click(screen.getByTitle('Remove'));
    fireEvent.click(await screen.findByRole('button', { name: /Confirm/i }));
    await waitFor(() => (lastEncCall()?.data?.participants?.length === 0));
    expect(lastEncCall().data.participants).toEqual([]);
  });

  test('toggleActive: updateDoc flips isActive', async () => {
    await setupReady();
    await addMonsterViaUI('Toggle', 10, 0);
    fireEvent.click(screen.getByRole('button', { name: 'Disable participant' }));
    await waitFor(() => lastEncCall()?.data?.participants?.[0]?.isActive === false);
    expect(lastEncCall().data.participants[0].isActive).toBe(false);
  });

  test('applyDamage: updateDoc reduces currentHp, clamps 0', async () => {
    await setupReady();
    await addMonsterViaUI('Hurt', 10, 0);
    await startCombatViaUI();
    fireEvent.change(screen.getByPlaceholderText('HP'), { target: { value: '3' } });
    fireEvent.click(screen.getByTitle('Damage'));
    await waitFor(() => lastEncCall()?.data?.participants?.[0]?.currentHp === 7);
    expect(lastEncCall().data.participants[0].currentHp).toBe(7);
  });

  test('damage to 0 marks non-NPC monster dead and inactive', async () => {
    await setupReady();
    await addMonsterViaUI('Doom', 5, 0);
    await startCombatViaUI();
    fireEvent.change(screen.getByPlaceholderText('HP'), { target: { value: '5' } });
    fireEvent.click(screen.getByTitle('Damage'));
    await waitFor(() => lastEncCall()?.data?.participants?.[0]?.currentHp === 0);
    const p = lastEncCall().data.participants[0];
    expect(p.currentHp).toBe(0);
    expect(p.status).toBe('dead');
    expect(p.isActive).toBe(false);
  });

  test('normal heal does not revive dead non-NPC monster', async () => {
    await setupReady();
    await addMonsterViaUI('Revive', 5, 0);
    await startCombatViaUI();
    fireEvent.change(screen.getByPlaceholderText('HP'), { target: { value: '5' } });
    fireEvent.click(screen.getByTitle('Damage'));
    await waitFor(() => lastEncCall()?.data?.participants?.[0]?.currentHp === 0);
    fireEvent.change(screen.getByPlaceholderText('HP'), { target: { value: '3' } });
    fireEvent.click(screen.getByTitle(/Heal/i));
    await waitFor(() => lastEncCall()?.data?.participants?.[0]?.status === 'dead');
    const p = lastEncCall().data.participants[0];
    expect(p.currentHp).toBe(0);
    expect(p.status).toBe('dead');
  });

  test('toggleCondition: updateDoc adds condition to array', async () => {
    await setupReady();
    await addMonsterViaUI('Cond', 10, 0);
    fireEvent.click(screen.getByRole('button', { name: 'Open conditions' }));
    await waitFor(() => screen.getByRole('button', { name: /Blinded/i }));
    fireEvent.click(screen.getByRole('button', { name: /Blinded/i }));
    await waitFor(() => {
      const p = lastEncCall()?.data?.participants?.[0];
      return p && p.conditions?.includes('blinded');
    });
    expect(lastEncCall().data.participants[0].conditions).toContain('blinded');
  });
});
