<template>
  <AppLayout>
    <div class="link-detail" v-if="link">
      <header class="page-header">
        <div>
          <router-link to="/links" class="back-link">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M19 12H5"/>
              <path d="M12 19l-7-7 7-7"/>
            </svg>
            Back to Links
          </router-link>
          <h1>{{ link.title || link.slug }}</h1>
          <div class="link-meta">
            <span class="short-url" @click="copyToClipboard">
              http://localhost:42001/{{ link.slug }}
              <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>
            </span>
            <span :class="['status-badge', link.status.toLowerCase()]">{{ link.status }}</span>
          </div>
        </div>
      </header>

      <div class="stats-grid">
        <div class="stat-card">
          <p class="stat-value">{{ analytics?.summary?.totalClicks || 0 }}</p>
          <p class="stat-label">Total Clicks</p>
        </div>
        <div class="stat-card">
          <p class="stat-value">{{ analytics?.summary?.uniqueVisitors || 0 }}</p>
          <p class="stat-label">Unique Visitors</p>
        </div>
        <div class="stat-card">
          <p class="stat-value">{{ formatDate(link.createdAt) }}</p>
          <p class="stat-label">Created</p>
        </div>
      </div>

      <div class="analytics-grid">
        <section class="card chart-card">
          <div class="card-header">
            <h2>Click 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) + '%' }"
                :title="`${point.date}: ${point.clicks} clicks`"
              ></div>
            </div>
          </div>
          <div v-else class="empty-state">
            <p>No click data yet</p>
          </div>
        </section>

        <section class="card">
          <h2>Devices</h2>
          <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">
          <h2>Referrers</h2>
          <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: 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">
          <h2>Countries</h2>
          <div class="breakdown" v-if="analytics?.countryBreakdown?.length">
            <div v-for="country in analytics.countryBreakdown" :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>
          </div>
        </section>
      </div>

      <section class="card link-info-card">
        <h2>Link Details</h2>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">Destination</span>
            <a :href="link.destinationUrl" target="_blank" class="info-value link">
              {{ link.destinationUrl }}
            </a>
          </div>
          <div class="info-item" v-if="link.expiresAt">
            <span class="info-label">Expires</span>
            <span class="info-value">{{ formatDate(link.expiresAt) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">Password Protected</span>
            <span class="info-value">{{ link.hasPassword ? 'Yes' : 'No' }}</span>
          </div>
        </div>
      </section>
    </div>

    <div v-else class="loading">
      Loading...
    </div>
  </AppLayout>
</template>

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

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

const link = ref(null);
const analytics = ref(null);
const period = ref('7d');

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

const fetchData = async () => {
  const linkId = route.params.id;
  const workspaceId = workspaceStore.currentWorkspaceId;

  if (!workspaceId) return;

  try {
    link.value = await linksApi.get(workspaceId, linkId);
    await fetchAnalytics();
  } catch (err) {
    console.error('Failed to fetch link:', err);
  }
};

const fetchAnalytics = async () => {
  const linkId = route.params.id;
  const workspaceId = workspaceStore.currentWorkspaceId;

  if (!workspaceId) return;

  try {
    analytics.value = await linksApi.getAnalytics(workspaceId, linkId, period.value);
  } catch (err) {
    console.error('Failed to fetch analytics:', err);
  }
};

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

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

const totalClicks = computed(() => {
  return analytics.value?.summary?.totalClicks || 1;
});

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

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

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

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(`http://localhost:42001/${link.value.slug}`);
  } catch (err) {
    console.error('Failed to copy:', err);
  }
};

// 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
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) => countryNames[countryCode] || countryCode;

onMounted(async () => {
  await fetchData();
});
</script>

<style scoped>
.link-detail {
  max-width: 1000px;
}

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

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: var(--muted);
  font-size: 0.9rem;
  margin-bottom: 12px;
}

.back-link:hover {
  color: var(--ink);
}

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

.link-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.short-url {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--accent);
  font-weight: 500;
  cursor: pointer;
}

.status-badge {
  padding: 4px 10px;
  border-radius: 999px;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
}

.status-badge.active {
  background: #dcfce7;
  color: #16a34a;
}

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

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

.stat-value {
  font-size: 1.75rem;
  font-weight: 700;
  margin-bottom: 4px;
}

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

.analytics-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

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

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

.card h2 {
  font-size: 1.1rem;
  margin-bottom: 20px;
}

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

.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;
}

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

.chart-container {
  height: 200px;
}

.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;
}

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

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

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

.link-info-card {
  margin-top: 24px;
}

.info-grid {
  display: grid;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

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

.info-value {
  font-weight: 500;
}

.info-value.link {
  color: var(--accent);
  word-break: break-all;
}

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

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

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

.loading {
  text-align: center;
  padding: 60px;
  color: var(--muted);
}

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

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

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