<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useProjectStore } from '../stores/projectStore';

const projectStore = useProjectStore();
const router = useRouter();
const newProjectName = ref('');

function openProject(projectId) {
  router.push({ name: 'Editor', params: { id: projectId } });
}

function createProject() {
  if (newProjectName.value.trim()) {
    const newId = projectStore.createNewProject(newProjectName.value.trim());
    openProject(newId);
  }
}
</script>

<template>
  <div class="dashboard-container">
    <div class="dashboard">
      <h1>My Projects</h1>
      <ul v-if="Object.keys(projectStore.projects).length">
        <li v-for="project in projectStore.projects" :key="project.id" @click="openProject(project.id)">
          {{ project.name }}
        </li>
      </ul>
      <p v-else>No projects yet. Create one below!</p>
      <div class="new-project-form">
        <input type="text" v-model="newProjectName" placeholder="New project name..." @keyup.enter="createProject" />
        <button @click="createProject">Create and Open</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 5rem;
  width: 100%;
  height: 100vh;
  background-color: var(--bg-color);
}
.dashboard {
  width: 100%;
  max-width: 600px;
  background-color: var(--panel-color);
  padding: 2rem 3rem;
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
}
h1 {
  margin-top: 0;
  text-align: center;
}
ul {
  list-style: none;
  padding: 0;
  margin: 2rem 0;
}
li {
  background-color: var(--bg-color);
  padding: 1rem 1.5rem;
  border-radius: var(--border-radius);
  margin-bottom: 1rem;
  cursor: pointer;
  transition: background-color 0.2s, border-color 0.2s;
  border: 1px solid var(--border-color);
}
li:hover {
  background-color: #2a3441;
  border-color: var(--accent-color);
}
.new-project-form {
  display: flex;
  gap: 0.5rem;
  margin-top: 2rem;
}
input {
  flex-grow: 1;
  padding: 0.75rem;
  background-color: var(--bg-color);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  color: var(--text-color);
}
button {
  padding: 0.75rem 1.5rem;
  background-color: var(--accent-color);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  cursor: pointer;
}
</style>
