// ─── Regression Test: Issue #354 ──────────────────────────────────────────────
// unlockAttunement crashes with ReferenceError — 'state' is undefined
//
// Bug: unlockAttunement referenced `state.attunements[attunementId]?.active`
// but `state` was not in scope. The function signature is
// `unlockAttunement(attunementId, defeatedGuardians)` — no `state` parameter.
//
// Fix: Use `_get()` to read current state instead of referencing undefined `state`.

import { describe, it, expect, beforeEach } from 'vitest';
import { useAttunementStore } from '../stores/attunementStore';

describe('Issue #354 — unlockAttunement ReferenceError', () => {
  beforeEach(() => {
    // Reset to initial state: only enchanter active
    useAttunementStore.getState().resetAttunements();
    // Clear localStorage to avoid persisted state leaking between tests
    localStorage.removeItem('mana-loop-attunements');
  });

  it('should not throw ReferenceError when checking if attunement is already active', () => {
    // This was the crash: calling unlockAttunement on an already-active attunement
    // would throw "ReferenceError: state is not defined"
    expect(() => {
      useAttunementStore.getState().unlockAttunement('enchanter', []);
    }).not.toThrow();
  });

  it('should return false when attunement is already active', () => {
    const result = useAttunementStore.getState().unlockAttunement('enchanter', []);
    expect(result).toBe(false);
  });

  it('should return false for unknown attunement', () => {
    const result = useAttunementStore.getState().unlockAttunement('unknown', []);
    expect(result).toBe(false);
  });

  it('should return false for invoker when floor 10 guardian not defeated', () => {
    const result = useAttunementStore.getState().unlockAttunement('invoker', []);
    expect(result).toBe(false);
  });

  it('should unlock invoker when floor 10 guardian is defeated', () => {
    const result = useAttunementStore.getState().unlockAttunement('invoker', [10]);
    expect(result).toBe(true);

    const state = useAttunementStore.getState();
    expect(state.attunements['invoker']?.active).toBe(true);
    expect(state.attunements['invoker']?.level).toBe(1);
  });

  it('should return false for fabricator when floor 20 guardian not defeated', () => {
    const result = useAttunementStore.getState().unlockAttunement('fabricator', [10, 30]);
    expect(result).toBe(false);
  });

  it('should unlock fabricator when floor 20 guardian is defeated', () => {
    const result = useAttunementStore.getState().unlockAttunement('fabricator', [10, 20, 30]);
    expect(result).toBe(true);

    const state = useAttunementStore.getState();
    expect(state.attunements['fabricator']?.active).toBe(true);
    expect(state.attunements['fabricator']?.level).toBe(1);
  });
});
