<script lang="ts">
  import { getProjectWorkspace, workbenchProjects } from './mockData';
  import ChannelContent from './ChannelContent.svelte';
  import ObjectInspector from './ObjectInspector.svelte';
  import ProjectRail from './ProjectRail.svelte';
  import ProjectChannelSidebar from './ProjectChannelSidebar.svelte';
  import WorkspaceTopbar from './WorkspaceTopbar.svelte';
  import WorkspaceStatusBar from './WorkspaceStatusBar.svelte';
  import type { InspectorItem, WorkTask } from './types';

  export let currentUser: { account: string };

  let theme: 'light' | 'dark' = 'light';
  let selectedProjectID = workbenchProjects[0].id;
  let selectedItem: InspectorItem | null = null;
  let tasksByProjectID: Record<number, WorkTask[]> = Object.fromEntries(
    workbenchProjects.map((project) => [project.id, getProjectWorkspace(project.id).tasks.map((task) => ({ ...task }))]),
  );
  $: workspace = getProjectWorkspace(selectedProjectID);
  $: tasks = tasksByProjectID[selectedProjectID] ?? workspace.tasks;
  $: selectedChannelID = workspace.channels[0].id;
  $: selectedChannel = workspace.channels.find((channel) => channel.id === selectedChannelID) ?? workspace.channels[0];

  function selectProject(projectID: number) {
    selectedItem = null;
    selectedProjectID = projectID;
  }

  function selectChannel(channelID: string) {
    selectedItem = null;
    selectedChannelID = channelID;
  }

  function inspectItem(item: InspectorItem) {
    selectedItem = item;
  }

  function toggleTask(taskID: string) {
    tasksByProjectID = {
      ...tasksByProjectID,
      [selectedProjectID]: tasks.map((task) => task.id === taskID ? { ...task, completed: !task.completed } : task),
    };
  }

  function toggleTheme() {
    theme = theme === 'light' ? 'dark' : 'light';
  }
</script>

<main class="workbench-shell" aria-label="SenlinAI workbench" data-theme={theme}>
  <WorkspaceTopbar {theme} onToggleTheme={toggleTheme} />
  <div class="workbench-body">
    <ProjectRail projects={workbenchProjects} {selectedProjectID} onSelectProject={selectProject} />
    <ProjectChannelSidebar
      project={workspace.project}
      channels={workspace.channels}
      {selectedChannelID}
      tags={workspace.tags}
      recentSessions={workspace.recentSessions}
      onSelectChannel={selectChannel}
    />
    <section class="channel-stage" aria-label="Channel content">
      <ChannelContent {workspace} {tasks} channel={selectedChannel} onInspect={inspectItem} onToggleTask={toggleTask} />
    </section>
    <ObjectInspector item={selectedItem} />
  </div>
  <WorkspaceStatusBar account={currentUser.account} />
</main>
