<script lang="ts">
import { page } from "$app/stores";
import type { Task } from "$lib/server/services/tasks";
import TaskEdit from "$lib/ui/Tasks/TaskEdit.svelte";
import TaskView from "$lib/ui/Tasks/TaskView.svelte";
import type { PageProps } from "./$types";

let { data, form }: PageProps = $props();

// The editing state is now derived directly from the URL query parameter.
let isEditing = $derived($page.url.searchParams.get("edit") === "true");

// --- Data Transformation for TaskView ---
const parentTask: Task | null =
  (data.parent?.status === "ok" && data.parent.data)
    ? data.parent.data[0] ?? null
    : null;
const childrenTask: Task[] =
  (data.children.status === "ok" && data.children.data)
    ? data.children.data
    : [];

const task = data.task;
const parent = {
  prefix: parentTask?.type.prefix ?? null,
  taskId: parentTask?.taskId ?? null,
  description: parentTask?.description ?? null,
};
const children = childrenTask.map(x => ({
  prefix: x.type.prefix,
  taskId: x.taskId,
  description: x.description,
  status: x.status,
}));
</script>

<nav class="view-controls">
  {#if isEditing}
    <a href={$page.url.pathname} class="button">Cancel</a>
  {:else}
    <a href={`${$page.url.pathname}?edit=true`} class="button">Edit Task</a>
  {/if}
</nav>

{#if isEditing}
  <TaskEdit {task} {form} />
{:else}
  <TaskView />
{/if}

<style>
.view-controls {
  margin-bottom: 2rem;
  display: flex;
  justify-content: flex-end;
}
.button {
  /* Basic button styling for links */
  display: inline-block;
  padding: 0.5rem 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  text-decoration: none;
  color: #333;
  background-color: #f0f0f0;
}
.button:hover {
  background-color: #e0e0e0;
}
</style>
