<template>
  <div class="app-layout">
    <aside class="sidebar">
      <div class="sidebar-header">
        <div class="brand">
          <span class="brand-mark">TQ</span>
          <span class="brand-name">TrakQR</span>
        </div>
      </div>

      <div class="workspace-selector" v-if="workspaceStore.currentWorkspace">
        <div class="workspace-dropdown">
          <select
            :value="workspaceStore.currentWorkspace?.id"
            @change="onWorkspaceChange"
            class="workspace-select"
          >
            <option
              v-for="ws in workspaceStore.workspaces"
              :key="ws.id"
              :value="ws.id"
            >
              {{ ws.name }}
            </option>
          </select>
          <div class="workspace-actions">
            <button class="ws-action-btn" @click="showCreateWorkspace = true" title="Create workspace">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="12" y1="5" x2="12" y2="19"/>
                <line x1="5" y1="12" x2="19" y2="12"/>
              </svg>
            </button>
            <button class="ws-action-btn" @click="showWorkspaceSettings = true" title="Workspace settings">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="3"/>
                <path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <!-- Create Workspace Modal -->
      <div v-if="showCreateWorkspace" class="modal-overlay" @click.self="showCreateWorkspace = false">
        <div class="modal">
          <div class="modal-header">
            <h2>Create Workspace</h2>
            <button class="close-btn" @click="showCreateWorkspace = false">&times;</button>
          </div>
          <form @submit.prevent="createWorkspace">
            <div class="modal-body">
              <div class="form-group">
                <label for="ws-name">Workspace Name</label>
                <input
                  id="ws-name"
                  v-model="newWorkspaceName"
                  type="text"
                  placeholder="e.g., Marketing Team"
                  required
                />
              </div>
              <div v-if="wsError" class="error-message">{{ wsError }}</div>
            </div>
            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="showCreateWorkspace = false">Cancel</button>
              <button type="submit" class="btn btn-primary" :disabled="creatingWs">
                {{ creatingWs ? 'Creating...' : 'Create' }}
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Workspace Settings Modal -->
      <div v-if="showWorkspaceSettings" class="modal-overlay" @click.self="showWorkspaceSettings = false">
        <div class="modal">
          <div class="modal-header">
            <h2>Workspace Settings</h2>
            <button class="close-btn" @click="showWorkspaceSettings = false">&times;</button>
          </div>
          <form @submit.prevent="updateWorkspace">
            <div class="modal-body">
              <div class="form-group">
                <label for="ws-edit-name">Workspace Name</label>
                <input
                  id="ws-edit-name"
                  v-model="editWorkspaceName"
                  type="text"
                  required
                />
              </div>
              <div class="workspace-info">
                <div class="info-row">
                  <span class="info-label">Plan:</span>
                  <span class="info-value plan-badge" :class="workspaceStore.currentWorkspace?.plan?.toLowerCase()">
                    {{ workspaceStore.currentWorkspace?.plan }}
                  </span>
                </div>
                <div class="info-row">
                  <span class="info-label">Created:</span>
                  <span class="info-value">{{ formatDate(workspaceStore.currentWorkspace?.createdAt) }}</span>
                </div>
              </div>
              <div v-if="wsError" class="error-message">{{ wsError }}</div>
            </div>
            <div class="modal-actions split">
              <button
                type="button"
                class="btn btn-danger-outline"
                @click="confirmDeleteWorkspace"
                :disabled="workspaceStore.workspaces.length <= 1"
                :title="workspaceStore.workspaces.length <= 1 ? 'Cannot delete your only workspace' : 'Delete workspace'"
              >
                Delete
              </button>
              <div class="action-group">
                <button type="button" class="btn btn-secondary" @click="showWorkspaceSettings = false">Cancel</button>
                <button type="submit" class="btn btn-primary" :disabled="updatingWs">
                  {{ updatingWs ? 'Saving...' : 'Save' }}
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>

      <!-- Delete Workspace Confirmation -->
      <div v-if="showDeleteWorkspace" class="modal-overlay" @click.self="showDeleteWorkspace = false">
        <div class="modal modal-sm">
          <div class="modal-header">
            <h2>Delete Workspace</h2>
            <button class="close-btn" @click="showDeleteWorkspace = false">&times;</button>
          </div>
          <div class="modal-body">
            <p class="delete-warning">
              Are you sure you want to delete <strong>{{ workspaceStore.currentWorkspace?.name }}</strong>?
              All links, QR codes, and analytics data will be permanently deleted.
            </p>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showDeleteWorkspace = false">Cancel</button>
            <button class="btn btn-danger" @click="deleteWorkspace" :disabled="deletingWs">
              {{ deletingWs ? 'Deleting...' : 'Delete Workspace' }}
            </button>
          </div>
        </div>
      </div>

      <nav class="sidebar-nav">
        <router-link to="/dashboard" class="nav-item" :class="{ active: $route.name === 'dashboard' }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="7" height="7" rx="1"/>
            <rect x="14" y="3" width="7" height="7" rx="1"/>
            <rect x="3" y="14" width="7" height="7" rx="1"/>
            <rect x="14" y="14" width="7" height="7" rx="1"/>
          </svg>
          Dashboard
        </router-link>
        <router-link to="/links" class="nav-item" :class="{ active: $route.name === 'links' || $route.name === 'link-detail' }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
            <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
          </svg>
          Links
        </router-link>
        <router-link to="/qrcodes" class="nav-item" :class="{ active: $route.name?.startsWith('qrcode') }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="6" height="6"/>
            <rect x="15" y="3" width="6" height="6"/>
            <rect x="3" y="15" width="6" height="6"/>
            <rect x="15" y="15" width="6" height="6"/>
            <rect x="9" y="9" width="6" height="6"/>
          </svg>
          QR Codes
        </router-link>
        <router-link to="/analytics" class="nav-item" :class="{ active: $route.name === 'analytics' }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 20V10"/>
            <path d="M12 20V4"/>
            <path d="M6 20v-6"/>
          </svg>
          Analytics
        </router-link>
        <router-link to="/projects" class="nav-item" :class="{ active: $route.name === 'projects' }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
          </svg>
          Projects
        </router-link>
        <router-link to="/domains" class="nav-item" :class="{ active: $route.name === 'domains' }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <line x1="2" y1="12" x2="22" y2="12"/>
            <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
          </svg>
          Domains
        </router-link>
        <router-link to="/billing" class="nav-item" :class="{ active: $route.name === 'billing' }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="1" y="4" width="22" height="16" rx="2" ry="2"/>
            <line x1="1" y1="10" x2="23" y2="10"/>
          </svg>
          Billing
        </router-link>
        <router-link to="/settings" class="nav-item" :class="{ active: $route.name === 'settings' }">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="3"/>
            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
          </svg>
          Settings
        </router-link>
      </nav>

      <div class="sidebar-footer">
        <button @click="logout" class="logout-btn">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
            <polyline points="16,17 21,12 16,7"/>
            <line x1="21" y1="12" x2="9" y2="12"/>
          </svg>
          Logout
        </button>
      </div>
    </aside>

    <main class="main-content">
      <slot></slot>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../../stores/auth';
import { useWorkspaceStore } from '../../stores/workspace';

const router = useRouter();
const authStore = useAuthStore();
const workspaceStore = useWorkspaceStore();

// Workspace management state
const showCreateWorkspace = ref(false);
const showWorkspaceSettings = ref(false);
const showDeleteWorkspace = ref(false);
const newWorkspaceName = ref('');
const editWorkspaceName = ref('');
const wsError = ref('');
const creatingWs = ref(false);
const updatingWs = ref(false);
const deletingWs = ref(false);

onMounted(async () => {
  // Ensure stores are initialized (in case component mounts before App.vue init completes)
  await authStore.initialize();
  await workspaceStore.initialize();
});

watch(() => workspaceStore.currentWorkspace, (ws) => {
  if (ws) {
    editWorkspaceName.value = ws.name;
  }
}, { immediate: true });

const onWorkspaceChange = (e) => {
  const workspace = workspaceStore.workspaces.find(w => w.id === e.target.value);
  if (workspace) {
    workspaceStore.setCurrentWorkspace(workspace);
  }
};

const createWorkspace = async () => {
  creatingWs.value = true;
  wsError.value = '';
  try {
    const workspace = await workspaceStore.createWorkspace(newWorkspaceName.value);
    workspaceStore.setCurrentWorkspace(workspace);
    showCreateWorkspace.value = false;
    newWorkspaceName.value = '';
  } catch (err) {
    wsError.value = err.message;
  } finally {
    creatingWs.value = false;
  }
};

const updateWorkspace = async () => {
  updatingWs.value = true;
  wsError.value = '';
  try {
    const wsId = workspaceStore.currentWorkspace?.id;
    await workspaceStore.updateWorkspace(wsId, editWorkspaceName.value);
    showWorkspaceSettings.value = false;
  } catch (err) {
    wsError.value = err.message;
  } finally {
    updatingWs.value = false;
  }
};

const confirmDeleteWorkspace = () => {
  showWorkspaceSettings.value = false;
  showDeleteWorkspace.value = true;
};

const deleteWorkspace = async () => {
  deletingWs.value = true;
  wsError.value = '';
  try {
    const wsId = workspaceStore.currentWorkspace?.id;
    await workspaceStore.deleteWorkspace(wsId);
    showDeleteWorkspace.value = false;
  } catch (err) {
    wsError.value = err.message;
  } finally {
    deletingWs.value = false;
  }
};

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  });
};

const logout = () => {
  workspaceStore.clearAll();
  authStore.logout();
  router.push('/login');
};
</script>

<style scoped>
.app-layout {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 260px;
  background: var(--surface);
  border-right: 1px solid var(--line);
  display: flex;
  flex-direction: column;
  padding: 24px 16px;
}

.sidebar-header {
  margin-bottom: 24px;
}

.brand {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
}

.brand-mark {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 10px;
  background: var(--ink);
  color: #fff4ec;
  font-weight: 700;
  font-size: 0.9rem;
}

.brand-name {
  font-size: 1.1rem;
}

.workspace-selector {
  margin-bottom: 24px;
}

.workspace-select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid var(--line);
  border-radius: 10px;
  background: var(--bg);
  font-size: 0.9rem;
  font-family: inherit;
  cursor: pointer;
}

.sidebar-nav {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 14px;
  border-radius: 10px;
  color: var(--muted);
  font-weight: 500;
  transition: all 0.15s ease;
}

.nav-item:hover {
  background: var(--bg);
  color: var(--ink);
}

.nav-item.active {
  background: var(--accent);
  color: white;
}

.sidebar-footer {
  margin-top: auto;
  padding-top: 16px;
  border-top: 1px solid var(--line);
}

.logout-btn {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 12px 14px;
  border: none;
  border-radius: 10px;
  background: transparent;
  color: var(--muted);
  font-size: 0.95rem;
  font-weight: 500;
  font-family: inherit;
  cursor: pointer;
  transition: all 0.15s ease;
}

.logout-btn:hover {
  background: rgba(255, 0, 0, 0.08);
  color: #dc2626;
}

.main-content {
  flex: 1;
  background: var(--bg);
  padding: 32px;
  overflow-y: auto;
}

/* Workspace dropdown */
.workspace-dropdown {
  display: flex;
  gap: 8px;
}

.workspace-dropdown .workspace-select {
  flex: 1;
}

.workspace-actions {
  display: flex;
  gap: 4px;
}

.ws-action-btn {
  width: 36px;
  height: 36px;
  border: 1px solid var(--line);
  background: var(--bg);
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--muted);
  transition: all 0.15s;
}

.ws-action-btn:hover {
  background: var(--surface);
  color: var(--ink);
}

/* Modal styles */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 420px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-sm {
  max-width: 380px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h2 {
  font-size: 1.125rem;
  font-weight: 600;
  margin: 0;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  font-size: 1.5rem;
  color: #6b7280;
  cursor: pointer;
  border-radius: 6px;
}

.close-btn:hover {
  background: #f3f4f6;
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.form-group input {
  width: 100%;
  padding: 0.625rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 0.875rem;
}

.form-group input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.workspace-info {
  background: #f9fafb;
  border-radius: 8px;
  padding: 1rem;
  margin-top: 1rem;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 0.875rem;
  color: #6b7280;
}

.info-value {
  font-size: 0.875rem;
  font-weight: 500;
}

.plan-badge {
  padding: 0.125rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
}

.plan-badge.free {
  background: #e5e7eb;
  color: #374151;
}

.plan-badge.pro {
  background: #dbeafe;
  color: #1d4ed8;
}

.plan-badge.business {
  background: #fef3c7;
  color: #b45309;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e7eb;
}

.modal-actions.split {
  justify-content: space-between;
}

.action-group {
  display: flex;
  gap: 0.75rem;
}

.delete-warning {
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  padding: 1rem;
  color: #991b1b;
  line-height: 1.5;
}

.error-message {
  background: #fee2e2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  padding: 0.75rem;
  color: #dc2626;
  font-size: 0.875rem;
  margin-top: 1rem;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 1rem;
  border-radius: 8px;
  font-weight: 500;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #2563eb;
}

.btn-secondary {
  background: white;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover:not(:disabled) {
  background: #f9fafb;
}

.btn-danger {
  background: #dc2626;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #b91c1c;
}

.btn-danger-outline {
  background: white;
  color: #dc2626;
  border: 1px solid #fecaca;
}

.btn-danger-outline:hover:not(:disabled) {
  background: #fef2f2;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
