import { describe, it, expect, beforeEach } from 'vitest';

// Mock DOM elements for displayError tests
const mockDocument = () => {
  const elements = {};
  global.document = {
    getElementById: (id) => elements[id] || null,
  };
  beforeEach(() => {
    elements.authError = { 
      textContent: '', 
      classList: { 
        add: () => {}, 
        remove: () => {} 
      } 
    };
    elements.authSuccess = { 
      textContent: '', 
      classList: { 
        add: () => {}, 
        remove: () => {} 
      } 
    };
  });
};

describe('safeJsonParse', () => {
  // Import the function - we'll need to make it work with Vitest
  // For now, we'll define it inline for testing
  const safeJsonParse = (text, fallback = null) => {
    try {
      if (text === undefined || text === null || text === '') {
        return fallback;
      }
      return JSON.parse(text);
    } catch (error) {
      return fallback;
    }
  };

  it('should parse valid JSON string', () => {
    const result = safeJsonParse('{"key":"value"}');
    expect(result).toEqual({ key: 'value' });
  });

  it('should return fallback for invalid JSON', () => {
    const result = safeJsonParse('invalid json');
    expect(result).toBeNull();
  });

  it('should return custom fallback when provided', () => {
    const result = safeJsonParse('invalid', 'custom fallback');
    expect(result).toBe('custom fallback');
  });

  it('should return fallback for undefined input', () => {
    const result = safeJsonParse(undefined);
    expect(result).toBeNull();
  });

  it('should return fallback for null input', () => {
    const result = safeJsonParse(null);
    expect(result).toBeNull();
  });

  it('should return fallback for empty string', () => {
    const result = safeJsonParse('');
    expect(result).toBeNull();
  });

  it('should parse valid JSON array', () => {
    const result = safeJsonParse('[1, 2, 3]');
    expect(result).toEqual([1, 2, 3]);
  });

  it('should parse nested JSON', () => {
    const result = safeJsonParse('{"user":{"name":"John","age":30}}');
    expect(result).toEqual({ user: { name: 'John', age: 30 } });
  });
});
