import '@testing-library/jest-dom/vitest';
import { fireEvent, render, screen, within } from '@testing-library/svelte';
import { describe, expect, it, vi } from 'vitest';
import ChannelContent from './ChannelContent.svelte';
import { getProjectWorkspace } from './mockData';

describe('ChannelContent', () => {
  const workspace = getProjectWorkspace(1);

  it('renders a distinctive heading or control for every channel type', () => {
    const expectedContent = {
      overview: { role: 'heading', name: 'Overview' },
      inbox: { role: 'heading', name: 'Inbox' },
      tasks: { role: 'checkbox', name: 'Mark Confirm homepage information architecture complete' },
      ai_sessions: { role: 'heading', name: 'AI Sessions' },
      notes_sources: { role: 'heading', name: 'Notes & Sources' },
      cron: { role: 'heading', name: 'Cron Plans' },
      custom_link: { role: 'link', name: 'Open external channel' },
    } as const;

    for (const type of Object.keys(expectedContent) as Array<keyof typeof expectedContent>) {
      const channel = workspace.channels.find((item) => item.type === type);
      if (!channel) throw new Error(`missing ${type}`);

      const { unmount } = render(ChannelContent, { props: { workspace, channel, onInspect: () => {} } });
      expect(screen.getByRole(expectedContent[type].role, { name: expectedContent[type].name })).toBeInTheDocument();
      unmount();
    }
  });

  it('sends selected task details to inspector', async () => {
    let inspectedTitle = '';
    const channel = workspace.channels.find((item) => item.type === 'tasks');
    if (!channel) throw new Error('missing task channel');

    render(ChannelContent, {
      props: {
        workspace,
        channel,
        onInspect: (item) => {
          inspectedTitle = item.title;
        },
      },
    });

    await fireEvent.click(screen.getByRole('button', { name: 'Inspect Confirm homepage information architecture' }));
    expect(inspectedTitle).toBe('Confirm homepage information architecture');
  });

  it('reports task completion changes to its owner', async () => {
    const channel = workspace.channels.find((item) => item.type === 'tasks');
    if (!channel) throw new Error('missing task channel');
    const onToggleTask = vi.fn();

    render(ChannelContent, { props: { workspace, channel, onInspect: () => {}, onToggleTask } });

    const completion = screen.getByRole('checkbox', { name: 'Mark Confirm homepage information architecture complete' });
    expect(completion).not.toBeChecked();

    await fireEvent.click(completion);

    expect(onToggleTask).toHaveBeenCalledWith('1-task-1');
  });
});
