<template>
  <AppLayout>
    <div class="qrcode-detail">
      <header class="page-header">
        <div class="header-left">
          <router-link to="/qrcodes" class="back-link">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M19 12H5M12 19l-7-7 7-7"/>
            </svg>
            Back to QR Codes
          </router-link>
          <h1>{{ qrCode?.name || 'QR Code' }}</h1>
        </div>
        <div class="header-actions">
          <router-link :to="`/qrcodes/${id}`" class="btn btn-secondary">
            Edit Design
          </router-link>
        </div>
      </header>

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

      <template v-else-if="analytics">
        <!-- Stats Grid -->
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon scans">
              <svg width="24" height="24" 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"/>
              </svg>
            </div>
            <div class="stat-content">
              <p class="stat-value">{{ analytics.summary.totalScans }}</p>
              <p class="stat-label">Total Scans</p>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon visitors">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
                <circle cx="9" cy="7" r="4"/>
              </svg>
            </div>
            <div class="stat-content">
              <p class="stat-value">{{ analytics.summary.uniqueVisitors }}</p>
              <p class="stat-label">Unique Visitors</p>
            </div>
          </div>
        </div>

        <!-- Period Selector -->
        <div class="period-selector">
          <button
            v-for="p in periods"
            :key="p.value"
            :class="{ active: period === p.value }"
            @click="setPeriod(p.value)"
          >
            {{ p.label }}
          </button>
        </div>

        <!-- Chart -->
        <section class="card chart-card">
          <h2>Scans Over Time</h2>
          <div class="chart-container" v-if="analytics.timeSeries?.length">
            <div class="chart">
              <div
                v-for="(point, i) in analytics.timeSeries"
                :key="i"
                class="chart-bar"
                :style="{ height: getBarHeight(point.scans) + '%' }"
                :title="`${point.date}: ${point.scans} scans`"
              ></div>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No scan data for this period</p>
          </div>
        </section>

        <!-- Breakdowns -->
        <div class="breakdown-grid">
          <!-- Device Breakdown -->
          <section class="card">
            <h2>Devices</h2>
            <div v-if="Object.keys(analytics.deviceBreakdown).length" class="breakdown-list">
              <div
                v-for="(count, device) in analytics.deviceBreakdown"
                :key="device"
                class="breakdown-item"
              >
                <span class="breakdown-label">{{ device }}</span>
                <div class="breakdown-bar-container">
                  <div
                    class="breakdown-bar"
                    :style="{ width: getBreakdownPercent(count, analytics.summary.totalScans) + '%' }"
                  ></div>
                </div>
                <span class="breakdown-count">{{ count }}</span>
              </div>
            </div>
            <div v-else class="empty-state">
              <p>No device data</p>
            </div>
          </section>

          <!-- Country Breakdown -->
          <section class="card">
            <h2>Countries</h2>
            <div v-if="Object.keys(analytics.countryBreakdown).length" class="breakdown-list">
              <div
                v-for="(count, country) in analytics.countryBreakdown"
                :key="country"
                class="breakdown-item"
              >
                <span class="breakdown-label">
                  {{ getCountryFlag(country) }} {{ getCountryName(country) }}
                </span>
                <div class="breakdown-bar-container">
                  <div
                    class="breakdown-bar"
                    :style="{ width: getBreakdownPercent(count, analytics.summary.totalScans) + '%' }"
                  ></div>
                </div>
                <span class="breakdown-count">{{ count }}</span>
              </div>
            </div>
            <div v-else class="empty-state">
              <p>No country data</p>
            </div>
          </section>

          <!-- Referrer Breakdown -->
          <section class="card">
            <h2>Referrers</h2>
            <div v-if="Object.keys(analytics.referrerBreakdown).length" class="breakdown-list">
              <div
                v-for="(count, referrer) in analytics.referrerBreakdown"
                :key="referrer"
                class="breakdown-item"
              >
                <span class="breakdown-label">{{ referrer }}</span>
                <div class="breakdown-bar-container">
                  <div
                    class="breakdown-bar"
                    :style="{ width: getBreakdownPercent(count, analytics.summary.totalScans) + '%' }"
                  ></div>
                </div>
                <span class="breakdown-count">{{ count }}</span>
              </div>
            </div>
            <div v-else class="empty-state">
              <p>No referrer data</p>
            </div>
          </section>
        </div>
      </template>

      <div v-if="error" class="error-message">{{ error }}</div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { qrcodesApi } from '../../api/qrcodes.js';
import { useWorkspaceStore } from '../../stores/workspace.js';
import AppLayout from '../../components/layout/AppLayout.vue';

const route = useRoute();
const workspaceStore = useWorkspaceStore();

const id = computed(() => route.params.id);
const loading = ref(true);
const error = ref('');
const qrCode = ref(null);
const analytics = ref(null);
const period = ref('7d');

const periods = [
  { value: '24h', label: '24h' },
  { value: '7d', label: '7d' },
  { value: '30d', label: '30d' },
  { value: 'all', label: 'All' }
];

const countryNames = {
  US: 'United States', GB: 'United Kingdom', CA: 'Canada', AU: 'Australia',
  DE: 'Germany', FR: 'France', JP: 'Japan', CN: 'China', IN: 'India',
  BR: 'Brazil', MX: 'Mexico', ES: 'Spain', IT: 'Italy', NL: 'Netherlands'
};

onMounted(() => {
  loadData();
});

async function loadData() {
  loading.value = true;
  error.value = '';

  try {
    const workspaceId = workspaceStore.currentWorkspace?.id;
    if (!workspaceId) return;

    const [qrData, analyticsData] = await Promise.all([
      qrcodesApi.get(workspaceId, id.value),
      qrcodesApi.getAnalytics(workspaceId, id.value, period.value)
    ]);

    qrCode.value = qrData;
    analytics.value = analyticsData;
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
}

async function setPeriod(newPeriod) {
  period.value = newPeriod;
  loading.value = true;
  try {
    const workspaceId = workspaceStore.currentWorkspace?.id;
    analytics.value = await qrcodesApi.getAnalytics(workspaceId, id.value, newPeriod);
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
}

function getBarHeight(value) {
  if (!analytics.value?.timeSeries?.length) return 0;
  const max = Math.max(...analytics.value.timeSeries.map(p => p.scans));
  return max > 0 ? (value / max) * 100 : 0;
}

function getBreakdownPercent(count, total) {
  return total > 0 ? (count / total) * 100 : 0;
}

function getCountryFlag(code) {
  const codePoints = code
    .toUpperCase()
    .split('')
    .map(char => 127397 + char.charCodeAt(0));
  return String.fromCodePoint(...codePoints);
}

function getCountryName(code) {
  return countryNames[code] || code;
}
</script>

<style scoped>
.qrcode-detail {
  max-width: 1200px;
  margin: 0 auto;
}

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

.header-left {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  color: #6b7280;
  font-size: 0.875rem;
  text-decoration: none;
}

.back-link:hover {
  color: #374151;
}

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

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

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 1.25rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon.scans {
  background: #dbeafe;
  color: #2563eb;
}

.stat-icon.visitors {
  background: #d1fae5;
  color: #059669;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 700;
  margin: 0;
}

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

.period-selector {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}

.period-selector button {
  padding: 0.5rem 1rem;
  border: 1px solid #e5e7eb;
  background: white;
  border-radius: 8px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
}

.period-selector button:hover {
  background: #f9fafb;
}

.period-selector button.active {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.card {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 1.5rem;
}

.card h2 {
  font-size: 1rem;
  font-weight: 600;
  margin: 0 0 1rem;
}

.chart-container {
  height: 200px;
  display: flex;
  align-items: flex-end;
}

.chart {
  display: flex;
  align-items: flex-end;
  gap: 4px;
  width: 100%;
  height: 100%;
}

.chart-bar {
  flex: 1;
  background: #3b82f6;
  border-radius: 4px 4px 0 0;
  min-height: 4px;
  transition: height 0.3s ease;
}

.breakdown-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.breakdown-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.breakdown-item {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.breakdown-label {
  width: 120px;
  font-size: 0.875rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.breakdown-bar-container {
  flex: 1;
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.breakdown-bar {
  height: 100%;
  background: #3b82f6;
  border-radius: 4px;
}

.breakdown-count {
  width: 50px;
  text-align: right;
  font-size: 0.875rem;
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #6b7280;
}

.empty-state p {
  margin: 0;
}

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

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

.btn-secondary:hover {
  background: #f9fafb;
}

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

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

  .breakdown-grid {
    grid-template-columns: 1fr;
  }
}
</style>
