import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

// Fix #7: Switching workspace must reset the local state of the settings
// sub-panels (Monaco editor content, in-progress forms, file preview). The
// react-query keys already include spaceId, so data is refetched fresh — but
// component-local state (e.g. MonacoFileEditor's localContent, which only
// resets on [subdir, filename] change, NOT on content change) would keep the
// previous workspace's text, showing stale content when the new workspace's
// AGENTS.md is empty.
//
// The robust fix is `key={spaceId}` on the per-workspace detail panels so React
// remounts them on workspace switch, deterministically clearing all local
// state. We cannot render the heavy subtree (Monaco + react-query) without a
// DOM harness in this sandbox, so we assert the keying is present in the source
// (the spec explicitly allows this when full rendering is impractical).
const here = dirname(fileURLToPath(import.meta.url));
const src = readFileSync(join(here, 'SpaceDetail.tsx'), 'utf8');

describe('SpaceDetail — per-workspace panels remount on spaceId change', () => {
  it('SpaceSettings is keyed on spaceId', () => {
    expect(src).toMatch(/<SpaceSettings\s+key=\{spaceId\}/);
  });

  it('SpaceFiles is keyed on spaceId', () => {
    expect(src).toMatch(/<SpaceFiles\s+key=\{spaceId\}/);
  });

  it('SpaceCalendar is keyed on spaceId', () => {
    expect(src).toMatch(/<SpaceCalendar\s+key=\{spaceId\}/);
  });
});
