<script lang="ts">
  import { invoke } from '@tauri-apps/api/core';
  import { handleError } from '../../utils/handle-error';
  import {
    getActiveGroupId, getActiveGroup, getAllGroups,
    addProject, removeProject, addGroup, removeGroup, switchGroup,
    updateProject,
  } from '../../stores/workspace.svelte';
  import { getSetting } from '../../stores/settings-store.svelte';
  import { setActiveProject } from '../../stores/settings-scope.svelte';

  let newGroupName = $state('');
  let newName = $state('');
  let newCwd = $state('');
  let iconPickerFor = $state<string | null>(null);

  let activeGroupId = $derived(getActiveGroupId());
  let activeGroup = $derived(getActiveGroup());
  let groups = $derived(getAllGroups());

  const ICONS = [
    '📁', '🚀', '🤖', '🌐', '🔧', '🎮', '📱', '💻',
    '🔬', '📊', '🎨', '🔒', '💬', '📦', '⚡', '🧪',
    '🏗️', '📝', '🎯', '💡', '🔥', '🛠️', '🧩', '🗄️',
  ];

  function handleAddGroup() {
    if (!newGroupName.trim()) return;
    addGroup({ id: crypto.randomUUID(), name: newGroupName.trim(), projects: [], agents: [] });
    newGroupName = '';
  }

  async function handleAddProject() {
    if (!newName.trim() || !newCwd.trim() || !activeGroupId) return;
    addProject(activeGroupId, {
      id: crypto.randomUUID(), name: newName.trim(), cwd: newCwd.trim(),
      icon: '📁', enabled: true,
    });
    newName = ''; newCwd = '';
  }

  async function browseDir(): Promise<string | null> {
    try { return await invoke<string | null>('pick_directory'); }
    catch (e) { handleError(e, 'settings.browseDir', 'browse for a directory'); return null; }
  }

  async function browseProjectCwd() {
    const p = await browseDir();
    if (p) newCwd = p;
  }

  async function browseExistingCwd(projectId: string) {
    const p = await browseDir();
    if (p && activeGroupId) updateProject(activeGroupId, projectId, { cwd: p });
  }
</script>

<div class="projects">
  <h3>Groups</h3>
  <div class="group-list">
    {#each groups as group}
      <div class="group-row" class:active={group.id === activeGroupId}>
        <button class="group-btn" onclick={() => switchGroup(group.id)}>{group.name}</button>
        <span class="group-count">{group.projects.length} projects</span>
        {#if groups.length > 1}
          <button class="btn-sm danger" onclick={() => removeGroup(group.id)} aria-label="Remove group">x</button>
        {/if}
      </div>
    {/each}
  </div>
  <div class="add-row">
    <input bind:value={newGroupName} placeholder="New group name" />
    <button class="btn-sm primary" onclick={handleAddGroup} disabled={!newGroupName.trim()}>Add</button>
  </div>

  {#if activeGroup}
    <h3>Projects in "{activeGroup.name}"</h3>
    {#each activeGroup.projects as project}
      <div class="project-card">
        <div class="card-top">
          <div class="icon-pick">
            <button class="icon-btn" onclick={() => iconPickerFor = iconPickerFor === project.id ? null : project.id}>
              {project.icon ?? '📁'}
            </button>
            {#if iconPickerFor === project.id}
              <div class="icon-grid">
                {#each ICONS as ic}
                  <button onclick={() => { updateProject(activeGroupId!, project.id, { icon: ic }); iconPickerFor = null; }}>{ic}</button>
                {/each}
              </div>
            {/if}
          </div>
          <input class="name-input" value={project.name}
            onchange={(e) => updateProject(activeGroupId!, project.id, { name: (e.target as HTMLInputElement).value })} />
          <label class="toggle-wrap">
            <input type="checkbox" checked={project.enabled ?? true}
              onchange={(e) => updateProject(activeGroupId!, project.id, { enabled: (e.target as HTMLInputElement).checked })} />
            <span class="toggle-label">{project.enabled !== false ? 'On' : 'Off'}</span>
          </label>
        </div>

        <div class="card-field">
          <span class="label">Path</span>
          <div class="path-row">
            <input class="path-input" value={project.cwd}
              onchange={(e) => updateProject(activeGroupId!, project.id, { cwd: (e.target as HTMLInputElement).value })} />
            <button class="btn-sm" onclick={() => browseExistingCwd(project.id)} aria-label="Browse directory">...</button>
          </div>
        </div>

        <div class="card-field">
          <span class="label">Worktrees</span>
          <label class="toggle-wrap">
            <input type="checkbox" checked={project.useWorktrees ?? false}
              onchange={(e) => updateProject(activeGroupId!, project.id, { useWorktrees: (e.target as HTMLInputElement).checked })} />
            <span class="toggle-label">Isolation</span>
          </label>
        </div>

        <div class="card-field">
          <span class="label">Sandbox</span>
          <label class="toggle-wrap">
            <input type="checkbox" checked={project.sandboxEnabled ?? false}
              onchange={(e) => updateProject(activeGroupId!, project.id, { sandboxEnabled: (e.target as HTMLInputElement).checked })} />
            <span class="toggle-label">Landlock</span>
          </label>
        </div>

        <div class="card-footer">
          <button class="btn-sm danger" onclick={() => { if (activeGroupId) removeProject(activeGroupId, project.id); }}>
            Remove Project
          </button>
        </div>
      </div>
    {/each}

    {#if (activeGroup.projects.length ?? 0) < 5}
      <div class="add-project">
        <h4>Add Project</h4>
        <input bind:value={newName} placeholder="Project name" />
        <div class="path-row">
          <input bind:value={newCwd} placeholder="/path/to/project" />
          <button class="btn-sm" onclick={browseProjectCwd} aria-label="Browse directory">...</button>
        </div>
        <button class="btn-sm primary" onclick={handleAddProject} disabled={!newName.trim() || !newCwd.trim()}>Add Project</button>
      </div>
    {:else}
      <p class="limit-notice">Maximum 5 projects per group.</p>
    {/if}
  {/if}
</div>

<style>
  .projects { display: flex; flex-direction: column; gap: 0.75rem; }
  h3 { font-size: 0.75rem; font-weight: 600; color: var(--ctp-subtext0); text-transform: uppercase; letter-spacing: 0.05em; margin: 0.5rem 0 0.125rem; }
  h4 { font-size: 0.8125rem; font-weight: 600; color: var(--ctp-text); margin: 0 0 0.375rem; }
  .group-list { display: flex; flex-direction: column; gap: 0.125rem; }
  .group-row { display: flex; align-items: center; gap: 0.5rem; padding: 0.25rem 0.5rem; border-radius: 0.25rem; border-left: 2px solid transparent; }
  .group-row.active { border-left-color: var(--ctp-blue); background: color-mix(in srgb, var(--ctp-blue) 8%, transparent); }
  .group-btn { background: none; border: none; color: var(--ctp-text); cursor: pointer; font-size: 0.8125rem; font-weight: 500; }
  .group-btn:hover { color: var(--ctp-blue); }
  .group-count { font-size: 0.6875rem; color: var(--ctp-overlay0); margin-left: auto; }
  .add-row { display: flex; gap: 0.375rem; }
  .add-row input { flex: 1; padding: 0.3125rem 0.5rem; background: var(--ctp-mantle); border: 1px solid var(--ctp-surface0); border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.8125rem; }
  .add-row input:focus { border-color: var(--ctp-blue); outline: none; }
  .project-card { background: var(--ctp-mantle); border: 1px solid var(--ctp-surface0); border-radius: 0.375rem; padding: 0.625rem; margin-bottom: 0.5rem; }
  .card-top { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem; }
  .icon-pick { position: relative; }
  .icon-btn { background: var(--ctp-surface0); border: none; border-radius: 0.25rem; padding: 0.25rem; font-size: 1rem; cursor: pointer; }
  .icon-grid { position: absolute; top: 100%; left: 0; z-index: 50; display: grid; grid-template-columns: repeat(8, 1fr); gap: 1px; background: var(--ctp-crust); border: 1px solid var(--ctp-surface0); border-radius: 0.25rem; padding: 0.25rem; }
  .icon-grid button { background: var(--ctp-mantle); border: none; font-size: 0.875rem; padding: 0.25rem; cursor: pointer; }
  .icon-grid button:hover { background: var(--ctp-surface0); }
  .name-input { flex: 1; background: transparent; border: none; border-bottom: 1px solid var(--ctp-surface0); color: var(--ctp-text); font-size: 0.875rem; font-weight: 600; padding: 0.125rem 0; }
  .name-input:focus { border-bottom-color: var(--ctp-blue); outline: none; }
  .toggle-wrap { display: flex; align-items: center; gap: 0.25rem; cursor: pointer; }
  .toggle-wrap input[type="checkbox"] { accent-color: var(--ctp-blue); }
  .toggle-label { font-size: 0.6875rem; color: var(--ctp-subtext0); }
  .card-field { display: flex; align-items: center; gap: 0.5rem; padding: 0.25rem 0; }
  .label { font-size: 0.75rem; color: var(--ctp-subtext0); min-width: 4.5rem; }
  .path-row { display: flex; gap: 0.25rem; flex: 1; }
  .path-input { flex: 1; padding: 0.25rem 0.375rem; background: var(--ctp-base); border: 1px solid var(--ctp-surface0); border-radius: 0.1875rem; color: var(--ctp-text); font-size: 0.75rem; font-family: monospace; }
  .path-input:focus { border-color: var(--ctp-blue); outline: none; }
  .card-footer { margin-top: 0.5rem; padding-top: 0.375rem; border-top: 1px solid var(--ctp-surface0); }
  .btn-sm { padding: 0.1875rem 0.5rem; background: var(--ctp-surface0); border: none; border-radius: 0.1875rem; color: var(--ctp-text); cursor: pointer; font-size: 0.75rem; }
  .btn-sm:hover { background: var(--ctp-surface1); }
  .btn-sm.primary { background: var(--ctp-blue); color: var(--ctp-base); }
  .btn-sm.primary:hover { opacity: 0.9; }
  .btn-sm.primary:disabled { opacity: 0.4; cursor: not-allowed; }
  .btn-sm.danger { color: var(--ctp-red); }
  .btn-sm.danger:hover { background: color-mix(in srgb, var(--ctp-red) 15%, transparent); }
  .add-project { background: var(--ctp-mantle); border: 1px dashed var(--ctp-surface0); border-radius: 0.375rem; padding: 0.625rem; display: flex; flex-direction: column; gap: 0.375rem; }
  .add-project input { padding: 0.3125rem 0.5rem; background: var(--ctp-base); border: 1px solid var(--ctp-surface0); border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.8125rem; }
  .add-project input:focus { border-color: var(--ctp-blue); outline: none; }
  .limit-notice { font-size: 0.75rem; color: var(--ctp-overlay0); font-style: italic; }
</style>
