import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { appendEvolutionSnapshot } from '@/lib/evolution/history.collector';
import { alignEvolutionTimeline } from '@/lib/evolution/timeline.align';
import { emit, getAlignedTimeline } from '@/lib/evolution/event.bus';

function seedEvolutionReport({
  stability = 0.72,
  adaptationRate = 0.021,
  device = 'desktop',
  density = 'expanded',
  animations = 'full',
  perfMode = false,
  confidence = 1,
  ts = new Date().toISOString(),
} = {}) {
  const report = {
    lastUpdated: ts,
    phase: 8,
    lastContext: { device, perfMode, animations, density, confidence },
    metrics: { stability, adaptationRate },
    history: [],
  };
  localStorage.setItem('EVOLUTION_REPORT', JSON.stringify(report));
}

describe('🧩 Phase 8.95 — Temporal Alignment Layer', () => {
  beforeEach(() => {
    // reset كل مرة قبل كل test
    vi.useRealTimers();
    localStorage.clear();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it('aligns evolution history into a unified daily timeline', () => {
    // ✅ نفعل timers بعد reset
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2025-10-20T09:00:00Z'));
    seedEvolutionReport({ stability: 0.72, adaptationRate: 0.021 });
    appendEvolutionSnapshot();

    vi.setSystemTime(new Date('2025-10-21T09:00:00Z'));
    seedEvolutionReport({ stability: 0.74, adaptationRate: 0.022 });
    appendEvolutionSnapshot();

    const aligned = alignEvolutionTimeline('daily');
    expect(Array.isArray(aligned)).toBe(true);
    expect(aligned.length).toBeGreaterThanOrEqual(2);
    expect(aligned[0]).toHaveProperty('stability');
    expect(aligned[0]).toHaveProperty('adaptationRate');
  });

  it('computes delta and trend directions', () => {
    vi.useRealTimers();
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2025-10-20T09:00:00Z'));
    seedEvolutionReport({ stability: 0.7, adaptationRate: 0.02 });
    appendEvolutionSnapshot();

    vi.setSystemTime(new Date('2025-10-21T09:00:00Z'));
    seedEvolutionReport({ stability: 0.75, adaptationRate: 0.023 });
    appendEvolutionSnapshot();

    const timeline = alignEvolutionTimeline('daily');
    const last = timeline.at(-1);
    expect(['up', 'down', 'stable']).toContain(last?.trend);
  });

  it('updates aligned timeline automatically on evolution:update', () => {
    vi.useRealTimers();
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2025-10-20T09:00:00Z'));
    seedEvolutionReport({ stability: 0.71, adaptationRate: 0.021 });
    appendEvolutionSnapshot();

    vi.setSystemTime(new Date('2025-10-21T09:00:00Z'));
    seedEvolutionReport({ stability: 0.75, adaptationRate: 0.022 });
    emit('evolution:update');

    const cache = getAlignedTimeline();
    expect(Array.isArray(cache)).toBe(true);
    expect(cache.length).toBeGreaterThan(0);
    expect(cache[0]).toHaveProperty('t');
  });
});
