<template>
  <AppLayout>
    <div class="domains">
      <header class="page-header">
        <div>
          <h1>Custom Domains</h1>
          <p class="subtitle">Use your own domain for branded short links</p>
        </div>
        <button class="btn btn-primary" @click="showAddModal = true" :disabled="!canAddDomain">
          <svg width="20" height="20" 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>
          Add Domain
        </button>
      </header>

      <div v-if="!canAddDomain" class="upgrade-banner">
        <div class="banner-content">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
            <line x1="12" y1="8" x2="12" y2="12"/>
            <line x1="12" y1="16" x2="12.01" y2="16"/>
          </svg>
          <div>
            <strong>Custom domains require a Pro or Business plan.</strong>
            <p>Upgrade to use your own branded domains for short links.</p>
          </div>
        </div>
        <router-link to="/billing" class="btn btn-primary">Upgrade</router-link>
      </div>

      <div v-if="loading" class="loading">Loading domains...</div>

      <div v-else-if="domains.length === 0 && canAddDomain" class="empty-state">
        <div class="empty-icon">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <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>
        </div>
        <h3>No custom domains yet</h3>
        <p>Add your own domain to create branded short links.</p>
        <button class="btn btn-primary" @click="showAddModal = true">Add Domain</button>
      </div>

      <div v-else-if="domains.length > 0" class="domains-list">
        <div v-for="domain in domains" :key="domain.id" class="domain-card">
          <div class="domain-info">
            <div class="domain-status" :class="domain.status.toLowerCase()">
              {{ domain.status }}
            </div>
            <h3 class="domain-name">{{ domain.hostname }}</h3>
            <p class="domain-date">Added {{ formatDate(domain.createdAt) }}</p>
          </div>

          <div class="domain-actions">
            <template v-if="domain.status === 'Pending'">
              <button class="btn btn-secondary" @click="showVerifyInstructions(domain)">
                Verify Domain
              </button>
            </template>
            <button class="icon-btn danger" @click="confirmDelete(domain)" title="Delete">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="3,6 5,6 21,6"/>
                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <!-- Add Domain Modal -->
      <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
        <div class="modal">
          <div class="modal-header">
            <h2>Add Custom Domain</h2>
            <button class="close-btn" @click="showAddModal = false">&times;</button>
          </div>
          <form @submit.prevent="addDomain">
            <div class="form-group">
              <label for="hostname">Domain</label>
              <input
                id="hostname"
                v-model="newDomain"
                type="text"
                placeholder="links.yourdomain.com"
                required
                autofocus
              />
              <p class="form-hint">Enter the subdomain or domain you want to use for short links.</p>
            </div>
            <div v-if="error" class="error-message">{{ error }}</div>
            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="showAddModal = false">Cancel</button>
              <button type="submit" class="btn btn-primary" :disabled="adding">
                {{ adding ? 'Adding...' : 'Add Domain' }}
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Verification Instructions Modal -->
      <div v-if="showVerifyModal" class="modal-overlay" @click.self="showVerifyModal = false">
        <div class="modal modal-lg">
          <div class="modal-header">
            <h2>Verify {{ verifyingDomain?.hostname }}</h2>
            <button class="close-btn" @click="showVerifyModal = false">&times;</button>
          </div>
          <div class="verify-content">
            <div class="step">
              <div class="step-number">1</div>
              <div class="step-content">
                <h4>Add DNS TXT Record</h4>
                <p>Add the following TXT record to your domain's DNS settings:</p>
                <div class="dns-record">
                  <div class="record-row">
                    <span class="record-label">Type:</span>
                    <span class="record-value">TXT</span>
                  </div>
                  <div class="record-row">
                    <span class="record-label">Host/Name:</span>
                    <span class="record-value">_trakqr-verification</span>
                  </div>
                  <div class="record-row">
                    <span class="record-label">Value:</span>
                    <div class="record-value token">
                      {{ verifyingDomain?.verificationToken }}
                      <button class="copy-btn" @click="copyToken" title="Copy">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                          <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                          <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="step">
              <div class="step-number">2</div>
              <div class="step-content">
                <h4>Add CNAME Record</h4>
                <p>Point your domain to our servers:</p>
                <div class="dns-record">
                  <div class="record-row">
                    <span class="record-label">Type:</span>
                    <span class="record-value">CNAME</span>
                  </div>
                  <div class="record-row">
                    <span class="record-label">Host/Name:</span>
                    <span class="record-value">{{ verifyingDomain?.hostname }}</span>
                  </div>
                  <div class="record-row">
                    <span class="record-label">Value:</span>
                    <span class="record-value">cname.trakqr.com</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="step">
              <div class="step-number">3</div>
              <div class="step-content">
                <h4>Verify Ownership</h4>
                <p>DNS changes can take up to 48 hours to propagate. Once ready, click verify.</p>
              </div>
            </div>

            <div v-if="verifyError" class="error-message">{{ verifyError }}</div>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showVerifyModal = false">Close</button>
            <button class="btn btn-primary" @click="verifyDomain" :disabled="verifying">
              {{ verifying ? 'Verifying...' : 'Verify Domain' }}
            </button>
          </div>
        </div>
      </div>

      <!-- Delete Confirmation Modal -->
      <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
        <div class="modal modal-sm">
          <div class="modal-header">
            <h2>Delete Domain</h2>
            <button class="close-btn" @click="showDeleteModal = false">&times;</button>
          </div>
          <p class="delete-warning">
            Are you sure you want to delete <strong>{{ domainToDelete?.hostname }}</strong>?
            Links using this domain will stop working.
          </p>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
            <button class="btn btn-danger" @click="deleteDomain" :disabled="deleting">
              {{ deleting ? 'Deleting...' : 'Delete' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useWorkspaceStore } from '../../stores/workspace.js';
import { useDomainsStore } from '../../stores/domains.js';
import AppLayout from '../../components/layout/AppLayout.vue';

const workspaceStore = useWorkspaceStore();
const domainsStore = useDomainsStore();

const domains = computed(() => domainsStore.domains);
const loading = ref(true);
const adding = ref(false);
const verifying = ref(false);
const deleting = ref(false);
const error = ref('');
const verifyError = ref('');

const showAddModal = ref(false);
const showVerifyModal = ref(false);
const showDeleteModal = ref(false);

const newDomain = ref('');
const verifyingDomain = ref(null);
const domainToDelete = ref(null);

const canAddDomain = computed(() => workspaceStore.canUseCustomDomains);

onMounted(async () => {
  await loadDomains();
});

watch(() => workspaceStore.currentWorkspaceId, async () => {
  if (workspaceStore.currentWorkspaceId) {
    await loadDomains();
  }
});

async function loadDomains() {
  loading.value = true;
  try {
    await domainsStore.fetchDomains();
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
}

async function addDomain() {
  adding.value = true;
  error.value = '';
  try {
    const domain = await domainsStore.addDomain(newDomain.value);
    showAddModal.value = false;
    newDomain.value = '';
    // Show verification instructions for the new domain
    verifyingDomain.value = domain;
    showVerifyModal.value = true;
  } catch (err) {
    error.value = err.message;
  } finally {
    adding.value = false;
  }
}

function showVerifyInstructions(domain) {
  verifyingDomain.value = domain;
  verifyError.value = '';
  showVerifyModal.value = true;
}

async function verifyDomain() {
  verifying.value = true;
  verifyError.value = '';
  try {
    await domainsStore.verifyDomain(verifyingDomain.value.id);
    showVerifyModal.value = false;
    verifyingDomain.value = null;
  } catch (err) {
    verifyError.value = err.message;
  } finally {
    verifying.value = false;
  }
}

function confirmDelete(domain) {
  domainToDelete.value = domain;
  showDeleteModal.value = true;
}

async function deleteDomain() {
  deleting.value = true;
  try {
    await domainsStore.deleteDomain(domainToDelete.value.id);
    showDeleteModal.value = false;
    domainToDelete.value = null;
  } catch (err) {
    error.value = err.message;
  } finally {
    deleting.value = false;
  }
}

function copyToken() {
  navigator.clipboard.writeText(verifyingDomain.value?.verificationToken);
}

function formatDate(dateStr) {
  return new Date(dateStr).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  });
}
</script>

<style scoped>
.domains {
  max-width: 900px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 2rem;
}

.page-header h1 {
  font-size: 1.75rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
}

.subtitle {
  color: #6b7280;
  margin: 0;
}

.upgrade-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fef3c7;
  border: 1px solid #fcd34d;
  border-radius: 12px;
  padding: 1.25rem 1.5rem;
  margin-bottom: 2rem;
}

.banner-content {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  color: #92400e;
}

.banner-content svg {
  flex-shrink: 0;
  margin-top: 2px;
}

.banner-content strong {
  display: block;
  margin-bottom: 0.25rem;
}

.banner-content p {
  margin: 0;
  font-size: 0.875rem;
  opacity: 0.9;
}

.loading {
  text-align: center;
  padding: 3rem;
  color: #6b7280;
}

.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  color: #d1d5db;
  margin-bottom: 1rem;
}

.empty-state h3 {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
}

.empty-state p {
  color: #6b7280;
  margin: 0 0 1.5rem;
}

.domains-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.domain-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  border-radius: 12px;
  padding: 1.25rem 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.domain-status {
  display: inline-block;
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  margin-bottom: 0.5rem;
}

.domain-status.pending {
  background: #fef3c7;
  color: #92400e;
}

.domain-status.verified {
  background: #d1fae5;
  color: #065f46;
}

.domain-name {
  font-size: 1.125rem;
  font-weight: 600;
  margin: 0 0 0.25rem;
}

.domain-date {
  font-size: 0.875rem;
  color: #6b7280;
  margin: 0;
}

.domain-actions {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

/* Buttons */
.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;
  text-decoration: 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:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.icon-btn {
  width: 36px;
  height: 36px;
  border: none;
  background: transparent;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  transition: all 0.2s;
}

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

.icon-btn.danger:hover {
  background: #fee2e2;
  color: #dc2626;
}

/* Modal */
.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: 480px;
  max-height: 90vh;
  overflow-y: auto;
}

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

.modal-lg {
  max-width: 600px;
}

.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 form {
  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);
}

.form-hint {
  font-size: 0.75rem;
  color: #6b7280;
  margin: 0.5rem 0 0;
}

.verify-content {
  padding: 1.5rem;
}

.step {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.step:last-of-type {
  margin-bottom: 0;
}

.step-number {
  width: 28px;
  height: 28px;
  background: #3b82f6;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.875rem;
  font-weight: 600;
  flex-shrink: 0;
}

.step-content h4 {
  font-size: 1rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
}

.step-content p {
  font-size: 0.875rem;
  color: #6b7280;
  margin: 0 0 1rem;
}

.dns-record {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 1rem;
}

.record-row {
  display: flex;
  margin-bottom: 0.5rem;
}

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

.record-label {
  width: 100px;
  font-size: 0.75rem;
  color: #6b7280;
  flex-shrink: 0;
}

.record-value {
  font-size: 0.875rem;
  font-family: monospace;
  word-break: break-all;
}

.record-value.token {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.copy-btn {
  background: none;
  border: none;
  padding: 0.25rem;
  cursor: pointer;
  color: #6b7280;
  border-radius: 4px;
}

.copy-btn:hover {
  background: #e5e7eb;
  color: #374151;
}

.delete-warning {
  padding: 1.5rem;
  color: #374151;
  line-height: 1.5;
}

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

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

@media (max-width: 640px) {
  .page-header {
    flex-direction: column;
    gap: 1rem;
  }

  .upgrade-banner {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }

  .banner-content {
    flex-direction: column;
    align-items: center;
  }

  .domain-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
}
</style>
