<script setup>
const props = defineProps({
  customer: {
    type: Object,
    required: true
  },
  currentYear: {
    type: Number,
    default: new Date().getFullYear()
  }
})

const months = [
  { num: 1, name: 'Jan' },
  { num: 2, name: 'Feb' },
  { num: 3, name: 'Mar' },
  { num: 4, name: 'Apr' },
  { num: 5, name: 'May' },
  { num: 6, name: 'Jun' },
  { num: 7, name: 'Jul' },
  { num: 8, name: 'Aug' },
  { num: 9, name: 'Sep' },
  { num: 10, name: 'Oct' },
  { num: 11, name: 'Nov' },
  { num: 12, name: 'Dec' }
]

// Debug logging
onMounted(() => {
  console.log('=== FulfillmentCustomerCard Mounted ===')
  console.log('Customer:', props.customer.Name)
  console.log('Customer ID:', props.customer.id)
  console.log('Current Year:', props.currentYear)
  console.log('Metrics:', props.customer.metrics)
  console.log('InvoicesByMonth:', props.customer.metrics?.invoicesByMonth)
  console.log('Has invoicesByMonth:', !!props.customer.metrics?.invoicesByMonth)
  console.log('InvoicesByMonth keys:', Object.keys(props.customer.metrics?.invoicesByMonth || {}))
})

const getMonthData = (monthNum) => {
  return props.customer.metrics?.invoicesByMonth?.[monthNum] || null
}

const formatCurrency = (value) => {
  return new Intl.NumberFormat('de-DE', {
    style: 'currency',
    currency: 'EUR'
  }).format(value)
}

const getMonthColor = (monthData) => {
  if (!monthData) return 'is-light'

  const total = monthData.total
  if (total === 0) return 'is-light'
  if (total < 1000) return 'is-success is-light'
  if (total < 5000) return 'is-info'
  if (total < 10000) return 'is-primary'
  return 'is-success'
}


// Check if month is the current month
const isCurrentMonth = (monthNum) => {
  const now = new Date()
  const currentMonth = now.getMonth() + 1 // 1-12
  const currentYear = now.getFullYear()
  return props.currentYear === currentYear && monthNum === currentMonth
}

const showInvoiceDetails = ref({})

const toggleInvoiceDetails = (monthNum) => {
  showInvoiceDetails.value[monthNum] = !showInvoiceDetails.value[monthNum]
}
</script>

<template>
  <div class="customer-card">
    <!-- Header -->
    <div class="card-header">
      <div class="customer-info">
        <nuxt-link :to="`/partners/partners/${customer.id}/edit`" target="_blank" class="customer-name">
          {{ customer.Name || customer.identifier }}
        </nuxt-link>
        <span class="customer-code">{{ customer.Value || 'N/A' }}</span>
      </div>
    </div>

    <!-- Metrics Row -->
    <div class="metrics-row">
      <div class="metric-card">
        <div class="metric-icon">
          <span class="icon-euro">€</span>
        </div>
        <div class="metric-content">
          <p class="metric-label">Total Income</p>
          <p class="metric-value">{{ formatCurrency(customer.metrics?.totalIncome || 0) }}</p>
        </div>
      </div>

      <div class="metric-card highlight">
        <div class="metric-icon">
          <span class="icon-calendar">📅</span>
        </div>
        <div class="metric-content">
          <p class="metric-label">{{ currentYear }} Income</p>
          <p class="metric-value">{{ formatCurrency(customer.metrics?.yearIncome || 0) }}</p>
        </div>
      </div>

      <div class="metric-card">
        <div class="metric-icon">
          <span class="icon-document">📄</span>
        </div>
        <div class="metric-content">
          <p class="metric-label">Total Invoices</p>
          <p class="metric-value">{{ customer.metrics?.totalInvoices || 0 }}</p>
        </div>
      </div>
    </div>

    <!-- Calendar Section -->
    <div class="calendar-section">
      <div class="calendar-header">
        <h3 class="calendar-title">
          <span class="icon-calendar-days">📆</span>
          Invoice Calendar {{ currentYear }}
        </h3>
        <!-- Debug Badge -->
        <div class="debug-badge" v-if="customer.metrics?.invoicesByMonth">
          <span class="debug-count">
            {{ Object.keys(customer.metrics.invoicesByMonth).length }} months with data
          </span>
        </div>
      </div>

      <!-- Debug Info Panel (can be removed after verification) -->
      <div class="debug-panel">
        <details>
          <summary style="cursor: pointer; user-select: none; padding: 0.5rem; background: #f3f4f6; border-radius: 6px; font-size: 0.75rem; font-weight: 600;">
            🔍 Debug Info (Click to expand)
          </summary>
          <div style="padding: 0.75rem; background: #f9fafb; border-radius: 6px; margin-top: 0.5rem; font-size: 0.75rem; font-family: monospace;">
            <div><strong>Customer:</strong> {{ customer.Name }}</div>
            <div><strong>ID:</strong> {{ customer.id }}</div>
            <div><strong>Has Metrics:</strong> {{ !!customer.metrics }}</div>
            <div><strong>Has InvoicesByMonth:</strong> {{ !!customer.metrics?.invoicesByMonth }}</div>
            <div><strong>Months with data:</strong> {{ Object.keys(customer.metrics?.invoicesByMonth || {}).join(', ') || 'None' }}</div>
            <div><strong>Total Year Income:</strong> {{ formatCurrency(customer.metrics?.yearIncome || 0) }}</div>
            <div><strong>Total Invoices:</strong> {{ customer.metrics?.totalInvoices || 0 }}</div>
          </div>
        </details>
      </div>

      <div class="customer-months-grid">
        <div
          v-for="month in months"
          :key="month.num"
          class="month-cell"
          :class="{ 'is-current-month': isCurrentMonth(month.num) }"
        >
          <div class="month-name">
            {{ month.name }}
            <span v-if="isCurrentMonth(month.num)" class="current-indicator">●</span>
          </div>
          <div
            class="month-badge"
            :class="getMonthData(month.num) ? 'has-invoice' : 'no-invoice'"
            @click="getMonthData(month.num) && toggleInvoiceDetails(month.num)"
            :title="getMonthData(month.num) ? `${getMonthData(month.num).count} invoice(s) - Click to view details` : 'No invoices this month'"
          >
            <template v-if="getMonthData(month.num)">
              <span class="month-icon">✓</span>
              <span class="month-amount">{{ formatCurrency(getMonthData(month.num).total) }}</span>
              <span v-if="getMonthData(month.num).shippingTotal > 0" class="month-amount-ws">({{ formatCurrency(getMonthData(month.num).totalWithoutShipping) }})</span>
              <span class="month-count-badge">{{ getMonthData(month.num).count }}</span>
            </template>
            <template v-else>
              <span class="month-icon-empty">○</span>
              <span class="month-empty">—</span>
            </template>

            <!-- Contract Badge -->
            <div v-if="customer.contractedSigned" class="contract-badge" :title="`Contract signed: ${new Date(customer.contractedSigned).toLocaleDateString('de-DE')}`">
              <span class="contract-icon">📋</span>
              <span class="contract-text">{{ new Date(customer.contractedSigned).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' }) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Invoice Details Modal Overlay -->
    <Teleport to="body">
      <template v-for="month in months" :key="`modal-${month.num}`">
      <div
        v-if="showInvoiceDetails[month.num] && getMonthData(month.num)"
        @click.self="toggleInvoiceDetails(month.num)"
        style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 9999; padding: 1rem; backdrop-filter: blur(4px);"
      >
        <div style="background: white; border-radius: 12px; box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3); max-width: 600px; width: 100%; max-height: 80vh; display: flex; flex-direction: column;">
          <div style="display: flex; justify-content: space-between; align-items: center; padding: 1.25rem 1.5rem; border-bottom: 1px solid #e5e7eb; background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%); border-radius: 12px 12px 0 0;">
            <strong style="font-size: 1.125rem; color: #111827; font-weight: 700;">
              {{ month.name }} {{ currentYear }} - Invoices
            </strong>
            <button @click="toggleInvoiceDetails(month.num)" style="background: #f3f4f6; border: none; border-radius: 6px; padding: 0.5rem; cursor: pointer; display: flex; align-items: center; justify-content: center;">
              <span style="font-size: 1.25rem; color: #6b7280;">×</span>
            </button>
          </div>
          <div style="overflow-y: auto; flex: 1; padding: 0;">
            <ul style="list-style: none; padding: 0; margin: 0;">
              <!-- Draft Orders -->
              <li 
                v-for="order in getMonthData(month.num).orders || []" 
                :key="'order-' + order.id"
                style="padding: 1rem 1.5rem; border-bottom: 1px solid #f3f4f6; background: #fef3c7; border-left: 3px solid #f59e0b;"
              >
                <nuxt-link
                  :to="`/sales/orders/${order.id}/edit`"
                  target="_blank"
                  style="display: flex; align-items: center; gap: 0.5rem; text-decoration: none; color: #d97706; font-weight: 600; font-size: 0.875rem; margin-bottom: 0.5rem;"
                >
                  <span>📄</span>
                  <span style="flex: 1;">{{ order.documentNo }}</span>
                  <span style="font-size: 0.625rem; font-weight: 700; padding: 0.125rem 0.375rem; background: #f59e0b; color: white; border-radius: 4px;">DRAFT</span>
                  <span style="font-weight: 700; color: #10b981;">{{ formatCurrency(order.grandTotal) }}</span>
                </nuxt-link>
                <span style="font-size: 0.75rem; color: #6b7280; margin-left: 1.5rem;">
                  {{ new Date(order.dateOrdered).toLocaleDateString('de-DE') }}
                </span>
              </li>

              <!-- Invoices -->
              <li 
                v-for="invoice in getMonthData(month.num).invoices || []" 
                :key="'invoice-' + invoice.id"
                style="padding: 1rem 1.5rem; border-bottom: 1px solid #f3f4f6; transition: background 0.2s;"
                @mouseover="$event.currentTarget.style.background = '#f9fafb'"
                @mouseleave="$event.currentTarget.style.background = 'transparent'"
              >
                <nuxt-link
                  :to="`/sales/invoices/${invoice.id}/edit`"
                  target="_blank"
                  style="display: flex; align-items: center; gap: 0.5rem; text-decoration: none; color: #667eea; font-weight: 600; font-size: 0.875rem; margin-bottom: 0.5rem;"
                >
                  <span>📄</span>
                  <span style="flex: 1;">{{ invoice.documentNo }}</span>
                  <span style="font-weight: 700; color: #10b981;">{{ formatCurrency(invoice.grandTotal || invoice.totalLines) }}</span>
                </nuxt-link>
                <span style="font-size: 0.75rem; color: #6b7280; margin-left: 1.5rem;">
                  {{ new Date(invoice.dateInvoiced).toLocaleDateString('de-DE') }}
                </span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      </template>
    </Teleport>
  </div>
</template>

<style>
/* Unscoped styles for maximum visibility - no CSS conflicts */
.bulma-fulfillment-card {
  margin-bottom: 2rem !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

.fulfillment-month-grid {
  display: grid !important;
  grid-template-columns: repeat(6, 1fr) !important;
  gap: 1rem !important;
  width: 100% !important;
  min-height: 200px !important;
}

.customer-card {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  overflow: hidden;
  transition: box-shadow 0.2s;
}

.customer-card:hover {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
}

.card-header {
  padding: 1.5rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.customer-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.customer-name {
  font-size: 1.25rem;
  font-weight: 700;
  color: white;
  text-decoration: none;
  transition: opacity 0.2s;
}

.customer-name:hover {
  opacity: 0.9;
}

.customer-code {
  background: rgba(255, 255, 255, 0.25);
  padding: 0.375rem 0.75rem;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 600;
  backdrop-filter: blur(10px);
}

.metrics-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
  padding: 1.5rem;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.metric-card {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.metric-card.highlight {
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
  border: 2px solid #667eea30;
}

.metric-icon {
  width: 2.5rem;
  height: 2.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  flex-shrink: 0;
}

.metric-icon span {
  font-size: 1.5rem;
  line-height: 1;
}

.metric-content {
  flex: 1;
  min-width: 0;
}

.metric-label {
  font-size: 0.75rem;
  color: #6b7280;
  margin: 0 0 0.25rem 0;
  text-transform: uppercase;
  font-weight: 600;
  letter-spacing: 0.05em;
}

.metric-value {
  font-size: 1.125rem;
  font-weight: 700;
  color: #111827;
  margin: 0;
  line-height: 1.2;
}

.calendar-section {
  padding: 1.5rem;
  display: block !important;
  background: white;
  min-height: 200px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.calendar-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.debug-badge {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0.375rem 0.75rem;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 700;
  box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);
}

.debug-count {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.debug-panel {
  margin-bottom: 1rem;
  border: 2px dashed #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.debug-panel details[open] {
  background: #f9fafb;
}

.calendar-title span {
  font-size: 1.25rem;
  line-height: 1;
}

.customer-months-grid {
  display: grid !important;
  grid-template-columns: repeat(6, 1fr);
  gap: 1rem;
  width: 100%;
  min-height: 100px;
  background: transparent;
}

.month-count-badge {
  position: absolute;
  top: 4px;
  left: 4px;
  background: rgba(255, 255, 255, 0.9);
  color: #059669;
  font-size: 0.65rem;
  font-weight: 700;
  padding: 2px 6px;
  border-radius: 10px;
  line-height: 1;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.month-cell {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.month-cell.is-current-month {
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
  border-radius: 12px;
  padding: 0.5rem;
  box-shadow: 0 0 0 2px #667eea30;
  animation: pulse-current 2s ease-in-out infinite;
}

@keyframes pulse-current {
  0%, 100% {
    box-shadow: 0 0 0 2px #667eea30;
  }
  50% {
    box-shadow: 0 0 0 3px #667eea50;
  }
}

.month-name {
  font-size: 0.75rem;
  font-weight: 600;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.is-current-month .month-name {
  color: #667eea;
  font-weight: 700;
}

.current-indicator {
  color: #667eea;
  font-size: 0.5rem;
  animation: blink 1.5s ease-in-out infinite;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
}

.month-badge {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.25rem;
  padding: 0.75rem 0.5rem;
  border-radius: 8px;
  transition: all 0.2s;
  min-height: 70px;
  position: relative;
}

.contract-badge {
  position: absolute;
  bottom: 4px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 3px;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  padding: 3px 8px;
  border-radius: 6px;
  font-size: 0.65rem;
  font-weight: 700;
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.4);
  z-index: 10;
  white-space: nowrap;
}

.contract-icon {
  font-size: 0.75rem;
  line-height: 1;
}

.contract-text {
  line-height: 1;
}

.month-badge.has-invoice {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(16, 185, 129, 0.3);
}

.month-badge.has-invoice:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(16, 185, 129, 0.4);
}

.month-badge.no-invoice {
  background: #f3f4f6;
  color: #9ca3af;
  border: 1px dashed #d1d5db;
}

.month-icon {
  font-size: 1.5rem;
  line-height: 1;
  font-weight: bold;
}

.month-icon-empty {
  font-size: 1.5rem;
  line-height: 1;
  opacity: 0.5;
}

.month-amount {
  font-size: 0.75rem;
  font-weight: 700;
  text-align: center;
  line-height: 1.2;
}

.month-amount-ws {
  font-size: 0.625rem;
  font-weight: 500;
  text-align: center;
  line-height: 1.2;
  opacity: 0.85;
}

.month-empty {
  font-size: 1.25rem;
  opacity: 0.5;
}

/* Modal Overlay Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 1rem;
  backdrop-filter: blur(4px);
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
  max-width: 600px;
  width: 100%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
  border-radius: 12px 12px 0 0;
  flex-shrink: 0;
}

.modal-header strong {
  font-size: 1.125rem;
  color: #111827;
  font-weight: 700;
}

.modal-invoice-list {
  list-style: none;
  padding: 0;
  margin: 0;
  overflow-y: auto;
  flex: 1;
}

.modal-invoice-list li {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  transition: background 0.2s;
}

.modal-invoice-list li:hover {
  background: #f9fafb;
}

.modal-invoice-list li:last-child {
  border-bottom: none;
}

.invoice-link {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  text-decoration: none;
  color: #667eea;
  font-weight: 600;
  font-size: 0.875rem;
  transition: color 0.2s;
}

.invoice-link:hover {
  color: #764ba2;
}

.invoice-icon {
  width: 1rem;
  height: 1rem;
  flex-shrink: 0;
}

.invoice-no {
  flex: 1;
}

.invoice-amount {
  font-weight: 700;
  color: #10b981;
}

.invoice-date {
  font-size: 0.75rem;
  color: #6b7280;
  margin-left: 1.5rem;
}

.order-item {
  background: #fef3c7;
  border-left: 3px solid #f59e0b;
}

.order-link {
  color: #d97706 !important;
}

.order-link:hover {
  color: #b45309 !important;
}

.order-badge {
  font-size: 0.625rem;
  font-weight: 700;
  padding: 0.125rem 0.375rem;
  background: #f59e0b;
  color: white;
  border-radius: 4px;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

@media screen and (max-width: 1024px) {
  .customer-months-grid {
    grid-template-columns: repeat(4, 1fr);
  }

  .metrics-row {
    grid-template-columns: repeat(1, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .customer-months-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media screen and (max-width: 480px) {
  .customer-months-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .card-header {
    padding: 1rem;
  }

  .calendar-section {
    padding: 1rem;
  }

  .metrics-row {
    padding: 1rem;
  }
}
</style>
