<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { apiGet } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import WorkspaceTaskPanel from "@/components/WorkspaceTaskPanel.vue";
import WorkspaceNoteEditor from "@/components/WorkspaceNoteEditor.vue";
import WorkspaceChatWidget from "@/components/WorkspaceChatWidget.vue";

const route = useRoute();
const toast = useToastStore();

const projectId = computed(() => Number(route.params.projectId));

interface Project {
  id: number;
  title: string;
  goal?: string;
}

const project = ref<Project | null>(null);
const taskPanelRef = ref<InstanceType<typeof WorkspaceTaskPanel> | null>(null);
const noteEditorRef = ref<InstanceType<typeof WorkspaceNoteEditor> | null>(null);
const activeNoteId = ref<number | null>(null);

// Panel collapse state — persisted per project (tasks + notes only; chat is now a widget)
function _panelKey(pid: number) { return `workspace_panels_${pid}`; }

function _loadPanelState(pid: number) {
  try {
    const raw = localStorage.getItem(_panelKey(pid));
    if (raw) {
      const saved = JSON.parse(raw) as Partial<{ tasks: boolean; notes: boolean }>;
      const tasks = saved.tasks ?? true;
      const notes = saved.notes ?? true;
      // Guard: at least one panel must be open
      if (!tasks && !notes) return { tasks: true, notes: true };
      return { tasks, notes };
    }
  } catch { /* ignore */ }
  return { tasks: true, notes: true };
}

const panelOpen = ref<{ tasks: boolean; notes: boolean }>({ tasks: true, notes: true });

const gridColumns = computed(() => {
  return [
    panelOpen.value.tasks ? "minmax(0, 0.85fr)" : "0px",
    panelOpen.value.notes ? "minmax(0, 2.15fr)" : "0px",
  ].join(" ");
});

function togglePanel(panel: keyof typeof panelOpen.value) {
  const open = panelOpen.value;
  const openCount = [open.tasks, open.notes].filter(Boolean).length;
  if (open[panel] && openCount <= 1) return;
  panelOpen.value[panel] = !panelOpen.value[panel];
  localStorage.setItem(_panelKey(projectId.value), JSON.stringify(panelOpen.value));
}

function onNoteChanged(noteId: number) {
  activeNoteId.value = noteId;
  noteEditorRef.value?.reload();
}

function onTaskChanged() {
  taskPanelRef.value?.reload();
}

onMounted(async () => {
  panelOpen.value = _loadPanelState(projectId.value);

  try {
    project.value = await apiGet<Project>(`/api/projects/${projectId.value}`);
  } catch {
    toast.show("Failed to load project", "error");
  }
});
</script>

<template>
  <div class="workspace-root">
    <!-- Header -->
    <header class="ws-header">
      <router-link :to="project ? `/projects/${project.id}` : '/projects'" class="ws-back">
        ← {{ project?.title ?? "Project" }}
      </router-link>
      <span class="ws-title">{{ project?.goal ?? '' }}</span>
      <div class="ws-panel-toggles">
        <button
          :class="['panel-toggle', { active: panelOpen.tasks }]"
          title="Toggle Tasks panel"
          @click="togglePanel('tasks')"
        >
          Tasks
        </button>
        <button
          :class="['panel-toggle', { active: panelOpen.notes }]"
          title="Toggle Notes panel"
          @click="togglePanel('notes')"
        >
          Notes
        </button>
      </div>
    </header>

    <!-- Two-panel body -->
    <div class="ws-body" :style="{ gridTemplateColumns: gridColumns }">
      <!-- Left: Tasks -->
      <div v-show="panelOpen.tasks" class="ws-panel">
        <Transition name="panel-fade">
          <div v-if="panelOpen.tasks" class="panel-inner">
            <WorkspaceTaskPanel
              v-if="project"
              ref="taskPanelRef"
              :project-id="project.id"
            />
          </div>
        </Transition>
      </div>

      <!-- Right: Note Editor -->
      <div v-show="panelOpen.notes" class="ws-panel ws-panel-notes">
        <Transition name="panel-fade">
          <div v-if="panelOpen.notes" class="panel-inner">
            <WorkspaceNoteEditor
              v-if="project"
              ref="noteEditorRef"
              :project-id="project.id"
              :active-note-id="activeNoteId"
            />
          </div>
        </Transition>
      </div>
    </div>

    <!-- Floating chat widget -->
    <WorkspaceChatWidget
      v-if="project"
      :project-id="projectId"
      @note-changed="onNoteChanged"
      @task-changed="onTaskChanged"
    />
  </div>
</template>

<style scoped>
.workspace-root {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background: var(--color-bg);
}

.ws-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  height: 44px;
  padding: 0 1rem;
  border-bottom: 1px solid var(--color-border);
  background: var(--color-surface);
  flex-shrink: 0;
  z-index: 10;
}

.ws-back {
  color: var(--color-primary);
  text-decoration: none;
  font-size: 0.875rem;
  white-space: nowrap;
}
.ws-back:hover {
  text-decoration: underline;
}

.ws-title {
  font-size: 0.78rem;
  color: var(--color-text-muted);
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ws-panel-toggles {
  display: flex;
  gap: 0.3rem;
}

.panel-toggle {
  background: none;
  border: 1px solid var(--color-border);
  border-radius: 5px;
  padding: 0.2rem 0.6rem;
  font-size: 0.78rem;
  cursor: pointer;
  color: var(--color-text-muted);
  transition: all 0.15s;
}

.panel-toggle.active {
  background: color-mix(in srgb, var(--color-primary) 12%, transparent);
  border-color: var(--color-primary);
  color: var(--color-primary);
}

.ws-body {
  display: grid;
  flex: 1;
  overflow: hidden;
  transition: grid-template-columns 0.2s ease;
}

.ws-panel {
  overflow: hidden;
  min-width: 0;
}

.ws-panel-notes {
  border-left: 1px solid var(--color-border);
}

.panel-inner {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-fade-enter-active,
.panel-fade-leave-active {
  transition: opacity 0.18s ease;
}
.panel-fade-enter-from,
.panel-fade-leave-to {
  opacity: 0;
}
</style>
