<template>
  <AppLayout>
    <div class="dashboard">
      <header class="page-header">
        <h1>Dashboard</h1>
        <p class="subtitle">Overview of your workspace activity</p>
      </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"/>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
              <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
            </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 links">
            <svg width="24" height="24" 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>
          </div>
          <div class="stat-content">
            <p class="stat-value">{{ linksStore.links.length }}</p>
            <p class="stat-label">Active Links</p>
          </div>
        </div>
      </div>

      <div class="dashboard-grid">
        <section class="card chart-card">
          <div class="card-header">
            <h2>Activity</h2>
            <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>
          </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"
                :style="{ height: getBarHeight(point.clicks + point.scans) + '%' }"
                :title="`${point.date}: ${point.clicks + point.scans} events`"
              ></div>
            </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>
            <router-link to="/links" class="view-all">View all</router-link>
          </div>
          <div class="top-links" v-if="analytics?.topLinks?.length">
            <div v-for="link in analytics.topLinks.slice(0, 5)" :key="link.linkId" class="top-link">
              <div class="link-info">
                <p class="link-title">{{ link.title || link.slug }}</p>
                <p class="link-slug">/{{ link.slug }}</p>
              </div>
              <span class="link-clicks">{{ link.clicks }} clicks</span>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No links yet</p>
            <router-link to="/links" class="cta small">Create your first link</router-link>
          </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: getPercentage(device.count) + '%' }"></div>
              <span class="breakdown-label">{{ device.device }}</span>
              <span class="breakdown-value">{{ device.count }}</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>Top Referrers</h2>
          </div>
          <div class="breakdown" v-if="analytics?.referrerBreakdown?.length">
            <div v-for="ref in analytics.referrerBreakdown.slice(0, 5)" :key="ref.referrer" class="breakdown-item">
              <div class="breakdown-bar" :style="{ width: getPercentage(ref.count) + '%' }"></div>
              <span class="breakdown-label">{{ ref.referrer || 'Direct' }}</span>
              <span class="breakdown-value">{{ ref.count }}</span>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No referrer data yet</p>
          </div>
        </section>

        <section class="card">
          <div class="card-header">
            <h2>Top Countries</h2>
          </div>
          <div class="breakdown" v-if="analytics?.countryBreakdown?.length">
            <div v-for="country in analytics.countryBreakdown.slice(0, 5)" :key="country.key" class="breakdown-item">
              <div class="breakdown-bar country-bar" :style="{ width: getPercentage(country.count) + '%' }"></div>
              <span class="breakdown-label">
                <span class="country-flag">{{ getCountryFlag(country.key) }}</span>
                {{ getCountryName(country.key) }}
              </span>
              <span class="breakdown-value">{{ country.count }}</span>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No geographic data yet</p>
            <p class="hint">Country detection requires a GeoIP database</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 { useLinksStore } from '../../stores/links.js';
import { useAnalyticsStore } from '../../stores/analytics.js';

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

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

const period = ref('7d');
const analytics = computed(() => analyticsStore.analytics);

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

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

const totalEvents = computed(() => {
  if (!analytics.value?.timeSeries) return 1;
  return analytics.value.timeSeries.reduce((sum, p) => sum + p.clicks + p.scans, 0) || 1;
});

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

const getPercentage = (value) => {
  return Math.max((value / totalEvents.value) * 100, 5);
};

// Country code to flag emoji converter
const getCountryFlag = (countryCode) => {
  if (!countryCode || countryCode.length !== 2) return '';
  const codePoints = countryCode
    .toUpperCase()
    .split('')
    .map(char => 127397 + char.charCodeAt(0));
  return String.fromCodePoint(...codePoints);
};

// Country code to name mapping (common codes)
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',
  SE: 'Sweden',
  NO: 'Norway',
  DK: 'Denmark',
  FI: 'Finland',
  PL: 'Poland',
  RU: 'Russia',
  KR: 'South Korea',
  SG: 'Singapore',
  NZ: 'New Zealand',
  IE: 'Ireland',
  CH: 'Switzerland',
  AT: 'Austria',
  BE: 'Belgium',
  PT: 'Portugal',
};

const getCountryName = (countryCode) => {
  return countryNames[countryCode] || countryCode;
};

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

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

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

.page-header {
  margin-bottom: 32px;
}

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

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

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

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

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  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.links { background: #f0e6ff; color: #8b5cf6; }

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

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

.dashboard-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 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

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

.view-all {
  color: var(--accent);
  font-size: 0.9rem;
  font-weight: 500;
}

.period-selector {
  display: flex;
  gap: 4px;
  background: var(--bg);
  padding: 4px;
  border-radius: 10px;
}

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

.period-selector button.active {
  background: var(--surface);
  color: var(--ink);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

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

.chart-container {
  height: 200px;
  padding-top: 16px;
}

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

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

.chart-bar:hover {
  opacity: 0.8;
}

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

.top-link {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: var(--bg);
  border-radius: 12px;
}

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

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

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

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

.breakdown-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: var(--bg);
  border-radius: 10px;
  overflow: hidden;
}

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

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

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

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

.empty-state .hint {
  font-size: 0.85rem;
  margin-top: 8px;
}

.empty-state .cta {
  margin-top: 16px;
}

.country-bar {
  background: rgba(59, 130, 246, 0.15);
}

.country-flag {
  margin-right: 8px;
  font-size: 1.1em;
}

.cta.small {
  padding: 10px 16px;
  font-size: 0.9rem;
}

@media (max-width: 900px) {
  .dashboard-grid {
    grid-template-columns: 1fr;
  }

  .chart-card {
    grid-column: span 1;
  }
}
</style>
