import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
import PermissionButton from '../components/PermissionButton';
import { usePermissionStore } from '../store/permission/permissionStore';

let container: HTMLDivElement | null = null;
let root: ReturnType<typeof createRoot> | null = null;

beforeAll(() => {
  (
    globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
  ).IS_REACT_ACT_ENVIRONMENT = true;
});

async function renderPermissionButton() {
  container = document.createElement('div');
  document.body.appendChild(container);
  root = createRoot(container);
  await act(async () => {
    root?.render(<PermissionButton permission="student:edit">编辑学生</PermissionButton>);
  });
}

function readPermissionState() {
  return {
    permissions: usePermissionStore.getState().permissions,
    status: usePermissionStore.getState().status,
  };
}

afterEach(async () => {
  if (root) await act(async () => root?.unmount());
  container?.remove();
  root = null;
  container = null;
  usePermissionStore.getState().clearPermissions();
});

describe('permission state', () => {
  it('ignores cached localStorage permissions until profile verification succeeds', async () => {
    localStorage.setItem('permissions', JSON.stringify(['student:edit']));
    usePermissionStore.getState().beginPermissionVerification();

    expect(readPermissionState()).toEqual({ permissions: [], status: 'loading' });
    await renderPermissionButton();
    expect(container?.textContent).not.toContain('编辑学生');
  });

  it('renders permission actions only after verified permissions are written', async () => {
    usePermissionStore.getState().beginPermissionVerification();
    await renderPermissionButton();
    expect(container?.textContent).not.toContain('编辑学生');

    await act(async () => usePermissionStore.getState().writePermissions(['student:edit']));
    expect(container?.textContent).toContain('编辑学生');
  });

  it('keeps verified permissions while profile verification refreshes in the background', async () => {
    usePermissionStore.getState().writePermissions(['student:edit']);
    usePermissionStore.getState().beginPermissionVerification();

    expect(readPermissionState()).toEqual({ permissions: ['student:edit'], status: 'ready' });
    await renderPermissionButton();
    expect(container?.textContent).toContain('编辑学生');
  });
});
