<template>
  <AppLayout>
    <div class="analytics-page">
      <header class="page-header">
        <div>
          <h1>Analytics</h1>
          <p class="subtitle">Track performance across your workspace</p>
        </div>
        <div class="period-controls">
          <div class="period-selector">
            <button
              v-for="p in periods"
              :key="p.value"
              :class="{ active: period === p.value && !isCustomRange }"
              @click="setPeriod(p.value)"
            >
              {{ p.label }}
            </button>
            <button
              :class="{ active: isCustomRange }"
              @click="toggleCustomRange"
            >
              Custom
            </button>
          </div>
          <div v-if="isCustomRange" class="date-range">
            <input type="date" v-model="startDate" @change="applyCustomRange" />
            <span>to</span>
            <input type="date" v-model="endDate" @change="applyCustomRange" />
          </div>
        </div>
      </header>

      <div class="stats-grid" v-if="analytics">
        <div class="stat-card">
          <div class="stat-icon clicks">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M15 15l-2 5L9 9l11 4-5 2z"/>
            </svg>
          </div>
          <div class="stat-content">
            <p class="stat-value">{{ analytics.summary.totalClicks }}</p>
            <p class="stat-label">Total Clicks</p>
          </div>
        </div>

        <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 class="stat-card">
          <div class="stat-icon total">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
            </svg>
          </div>
          <div class="stat-content">
            <p class="stat-value">{{ analytics.summary.totalClicks + analytics.summary.totalScans }}</p>
            <p class="stat-label">Total Events</p>
          </div>
        </div>
      </div>

      <div class="analytics-grid">
        <section class="card chart-card">
          <div class="card-header">
            <h2>Event Timeline</h2>
          </div>
          <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-group"
              >
                <div
                  class="chart-bar clicks"
                  :style="{ height: getBarHeight(point.clicks) + '%' }"
                  :title="`${point.date}: ${point.clicks} clicks`"
                ></div>
                <div
                  class="chart-bar scans"
                  :style="{ height: getBarHeight(point.scans) + '%' }"
                  :title="`${point.date}: ${point.scans} scans`"
                ></div>
              </div>
            </div>
            <div class="chart-legend">
              <span class="legend-item clicks">Clicks</span>
              <span class="legend-item scans">Scans</span>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No activity data yet</p>
          </div>
        </section>

        <section class="card">
          <div class="card-header">
            <h2>Top Links</h2>
          </div>
          <div class="top-links" v-if="analytics?.topLinks?.length">
            <div v-for="(link, index) in analytics.topLinks" :key="link.linkId" class="top-link">
              <span class="rank">{{ index + 1 }}</span>
              <div class="link-info">
                <p class="link-title">{{ link.title || link.slug }}</p>
                <p class="link-slug">/{{ link.slug }}</p>
              </div>
              <div class="link-stats">
                <span class="clicks">{{ link.clicks }} clicks</span>
              </div>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No link data yet</p>
          </div>
        </section>

        <section class="card">
          <div class="card-header">
            <h2>Devices</h2>
          </div>
          <div class="breakdown" v-if="analytics?.deviceBreakdown?.length">
            <div v-for="device in analytics.deviceBreakdown" :key="device.device" class="breakdown-item">
              <div class="breakdown-bar" :style="{ width: getDevicePercentage(device.count) + '%' }"></div>
              <div class="breakdown-icon">
                <svg v-if="device.device === 'Mobile'" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="5" y="2" width="14" height="20" rx="2" ry="2"/>
                  <line x1="12" y1="18" x2="12.01" y2="18"/>
                </svg>
                <svg v-else-if="device.device === 'Desktop'" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
                  <line x1="8" y1="21" x2="16" y2="21"/>
                  <line x1="12" y1="17" x2="12" y2="21"/>
                </svg>
                <svg v-else-if="device.device === 'Tablet'" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="4" y="2" width="16" height="20" rx="2" ry="2"/>
                  <line x1="12" y1="18" x2="12.01" y2="18"/>
                </svg>
                <svg v-else width="18" height="18" 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"/>
                </svg>
              </div>
              <span class="breakdown-label">{{ device.device }}</span>
              <span class="breakdown-value">{{ device.count }}</span>
              <span class="breakdown-percent">{{ getDevicePercentage(device.count).toFixed(0) }}%</span>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No device data yet</p>
          </div>
        </section>

        <section class="card">
          <div class="card-header">
            <h2>Referrers</h2>
          </div>
          <div class="breakdown" v-if="analytics?.referrerBreakdown?.length">
            <div v-for="ref in analytics.referrerBreakdown" :key="ref.referrer" class="breakdown-item">
              <div class="breakdown-bar" :style="{ width: getReferrerPercentage(ref.count) + '%' }"></div>
              <span class="breakdown-label">{{ ref.referrer || 'Direct' }}</span>
              <span class="breakdown-value">{{ ref.count }}</span>
              <span class="breakdown-percent">{{ getReferrerPercentage(ref.count).toFixed(0) }}%</span>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No referrer data yet</p>
          </div>
        </section>
      </div>
    </div>
  </AppLayout>
</template>

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

const workspaceStore = useWorkspaceStore();
const analyticsStore = useAnalyticsStore();

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

const period = ref('7d');
const isCustomRange = ref(false);
const startDate = ref('');
const endDate = ref('');
const analytics = computed(() => analyticsStore.analytics);

const setPeriod = async (p) => {
  isCustomRange.value = false;
  period.value = p;
  await analyticsStore.fetchAnalytics(p);
};

const toggleCustomRange = () => {
  isCustomRange.value = true;
  // Set default range to last 30 days
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - 30);
  startDate.value = start.toISOString().split('T')[0];
  endDate.value = end.toISOString().split('T')[0];
  applyCustomRange();
};

const applyCustomRange = async () => {
  if (startDate.value && endDate.value) {
    await analyticsStore.fetchAnalytics(null, startDate.value, endDate.value);
  }
};

const maxEvents = computed(() => {
  if (!analytics.value?.timeSeries) return 1;
  return Math.max(...analytics.value.timeSeries.map(p => Math.max(p.clicks, p.scans)), 1);
});

const totalDeviceEvents = computed(() => {
  if (!analytics.value?.deviceBreakdown) return 1;
  return analytics.value.deviceBreakdown.reduce((sum, d) => sum + d.count, 0) || 1;
});

const totalReferrerEvents = computed(() => {
  if (!analytics.value?.referrerBreakdown) return 1;
  return analytics.value.referrerBreakdown.reduce((sum, r) => sum + r.count, 0) || 1;
});

const getBarHeight = (value) => {
  return Math.max((value / maxEvents.value) * 100, 4);
};

const getDevicePercentage = (value) => {
  return (value / totalDeviceEvents.value) * 100;
};

const getReferrerPercentage = (value) => {
  return (value / totalReferrerEvents.value) * 100;
};

onMounted(async () => {
  await analyticsStore.fetchAnalytics(period.value);
});

watch(() => workspaceStore.currentWorkspaceId, async () => {
  if (workspaceStore.currentWorkspaceId) {
    await analyticsStore.fetchAnalytics(period.value);
  }
});
</script>

<style scoped>
.analytics-page {
  max-width: 1200px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
}

.page-header h1 {
  font-size: 1.75rem;
  margin-bottom: 4px;
}

.subtitle {
  color: var(--muted);
}

.period-controls {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 12px;
}

.period-selector {
  display: flex;
  gap: 4px;
  background: var(--surface);
  padding: 4px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.period-selector button {
  padding: 10px 20px;
  border: none;
  background: transparent;
  border-radius: 10px;
  font-size: 0.9rem;
  font-weight: 500;
  color: var(--muted);
  cursor: pointer;
  transition: all 0.15s ease;
}

.period-selector button.active {
  background: var(--accent);
  color: white;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 12px;
  background: var(--surface);
  padding: 8px 12px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.date-range input[type="date"] {
  padding: 8px 12px;
  border: 1px solid var(--line);
  border-radius: 8px;
  font-size: 0.875rem;
  font-family: inherit;
  background: var(--bg);
  color: var(--ink);
}

.date-range input[type="date"]:focus {
  outline: none;
  border-color: var(--accent);
}

.date-range span {
  color: var(--muted);
  font-size: 0.875rem;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 32px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background: var(--surface);
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

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

.stat-icon.clicks { background: #fff0e6; color: var(--accent); }
.stat-icon.scans { background: #e6f0ff; color: #3b82f6; }
.stat-icon.visitors { background: #e6fff0; color: #22c55e; }
.stat-icon.total { background: #f0e6ff; color: #8b5cf6; }

.stat-value {
  font-size: 1.75rem;
  font-weight: 700;
}

.stat-label {
  color: var(--muted);
  font-size: 0.9rem;
}

.analytics-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.card {
  background: var(--surface);
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  margin-bottom: 20px;
}

.card-header h2 {
  font-size: 1.1rem;
}

.chart-card {
  grid-column: span 2;
}

.chart-container {
  height: 280px;
}

.chart {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  height: calc(100% - 40px);
}

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

.chart-bar {
  flex: 1;
  border-radius: 6px 6px 0 0;
  min-height: 8px;
  transition: height 0.3s ease;
}

.chart-bar.clicks {
  background: var(--accent);
}

.chart-bar.scans {
  background: #3b82f6;
}

.chart-legend {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.85rem;
  color: var(--muted);
}

.legend-item::before {
  content: '';
  width: 12px;
  height: 12px;
  border-radius: 3px;
}

.legend-item.clicks::before {
  background: var(--accent);
}

.legend-item.scans::before {
  background: #3b82f6;
}

.top-links {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.top-link {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: var(--bg);
  border-radius: 14px;
}

.rank {
  width: 28px;
  height: 28px;
  border-radius: 8px;
  background: var(--accent);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 0.85rem;
}

.link-info {
  flex: 1;
}

.link-title {
  font-weight: 600;
  margin-bottom: 2px;
}

.link-slug {
  font-size: 0.85rem;
  color: var(--muted);
}

.link-stats .clicks {
  font-weight: 600;
  color: var(--accent);
}

.breakdown {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.breakdown-item {
  position: relative;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  background: var(--bg);
  border-radius: 12px;
  overflow: hidden;
}

.breakdown-bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: rgba(255, 106, 61, 0.12);
  border-radius: 12px;
}

.breakdown-icon {
  position: relative;
  color: var(--muted);
}

.breakdown-label {
  position: relative;
  flex: 1;
  font-weight: 500;
}

.breakdown-value {
  position: relative;
  color: var(--muted);
  font-weight: 500;
}

.breakdown-percent {
  position: relative;
  font-size: 0.85rem;
  color: var(--muted);
  min-width: 40px;
  text-align: right;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: var(--muted);
}

@media (max-width: 900px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .analytics-grid {
    grid-template-columns: 1fr;
  }

  .chart-card {
    grid-column: span 1;
  }
}

@media (max-width: 600px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

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