<script setup>
const props = defineProps({
  title: { type: String, default: '' },
  chartType: { type: String, default: 'line' }, // line | bar | horizontal-bar | pie | stacked-bar
  data: { type: [Array, Object], default: () => ([]) },
  series: { type: Array, default: () => [] },
  categoryField: { type: String, default: 'day' },
  loading: { type: Boolean, default: false },
  height: { type: String, default: '350px' },
})

const emit = defineEmits(['chart-click'])

const isFullscreen = ref(false)
const widgetRef = ref(null)

const toggleFullscreen = async () => {
  if (!widgetRef.value) return
  if (!isFullscreen.value) {
    try {
      await widgetRef.value.requestFullscreen()
      isFullscreen.value = true
    } catch {
      // fallback: no fullscreen support
    }
  } else {
    try {
      await document.exitFullscreen()
      isFullscreen.value = false
    } catch {
      // ignore
    }
  }
}

onMounted(() => {
  document.addEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement
  })
})
</script>

<template>
  <div ref="widgetRef" class="card chart-widget" :class="{ 'is-fullscreen': isFullscreen }">
    <header class="card-header">
      <p class="card-header-title">{{ title }}</p>
      <div class="card-header-icon">
        <button class="button is-small is-ghost" @click="toggleFullscreen" :title="isFullscreen ? 'Exit Fullscreen' : 'Fullscreen'">
          <span class="icon is-small">
            <i :class="isFullscreen ? 'ti ti-arrows-minimize' : 'ti ti-arrows-maximize'"></i>
          </span>
        </button>
      </div>
    </header>
    <div class="card-content">
      <div v-if="loading" class="has-text-centered py-6">
        <span class="has-text-grey">Loading...</span>
      </div>
      <div v-else>
        <slot>
          <ClientOnly>
            <ChartsOverviewChart
              v-if="chartType === 'line' && Array.isArray(data)"
              :dataSet="data"
            />
            <ChartsHorizontalBarChart
              v-else-if="chartType === 'horizontal-bar' && typeof data === 'object' && !Array.isArray(data)"
              :data="data"
              :title="title"
            />
            <ChartsPieChart
              v-else-if="chartType === 'pie' && typeof data === 'object' && !Array.isArray(data)"
              :data="data"
              :title="title"
            />
            <ChartsStackedBarChart
              v-else-if="chartType === 'stacked-bar' && Array.isArray(data)"
              :rows="data"
              :series="series"
              :categoryField="categoryField"
            />
          </ClientOnly>
        </slot>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chart-widget {
  height: 100%;
}
.chart-widget.is-fullscreen {
  background: white;
  padding: 20px;
}
.card-header {
  box-shadow: none;
  border-bottom: 1px solid #f0f0f0;
}
.card-header-title {
  font-size: 0.9rem;
  font-weight: 600;
}
</style>
