<template>
    <ClientOnly>
        <div class="w-full" :style="{ height: `${height}px` }">
            <Line :data="chartData" :options="chartOptions" />
        </div>
        <template #fallback>
            <div :style="{ height: `${height}px` }" class="animate-pulse bg-muted rounded-xl" />
        </template>
    </ClientOnly>
</template>

<script setup lang="ts">
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Filler,
    Tooltip,
    type ChartData,
    type ChartOptions,
} from "chart.js";
import { Line } from "vue-chartjs";

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Filler, Tooltip);

const props = defineProps<{
    data: { label: string; count: number }[];
    height?: number;
}>();

const height = computed(() => props.height ?? 180);

function resolvePrimaryRgb(): string {
    if (typeof window === "undefined") return "rgb(14,165,233)";
    const raw = getComputedStyle(document.documentElement).getPropertyValue("--ui-primary").trim();
    const canvas = document.createElement("canvas");
    canvas.width = 1; canvas.height = 1;
    const ctx2 = canvas.getContext("2d");
    if (!ctx2) return "rgb(14,165,233)";
    ctx2.fillStyle = raw;
    ctx2.fillRect(0, 0, 1, 1);
    const [r, g, b] = ctx2.getImageData(0, 0, 1, 1).data;
    return `rgb(${r},${g},${b})`;
}

const primaryRgb = ref("rgb(14,165,233)");
onMounted(() => { primaryRgb.value = resolvePrimaryRgb(); });

function rgba(alpha: number) {
    return primaryRgb.value.replace("rgb(", "rgba(").replace(")", `,${alpha})`);
}

const chartData = computed<ChartData<"line">>(() => ({
    labels: props.data.map((d) => d.label),
    datasets: [
        {
            label: "Domains blockiert",
            data: props.data.map((d) => d.count),
            borderColor: primaryRgb.value,
            backgroundColor: (ctx: any) => {
                const chart = ctx.chart;
                const { ctx: c, chartArea } = chart;
                if (!chartArea) return rgba(0.3);
                const grad = c.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
                grad.addColorStop(0, rgba(0.35));
                grad.addColorStop(1, rgba(0));
                return grad;
            },
            fill: true,
            cubicInterpolationMode: "monotone" as any,
            pointRadius: 0,
            borderWidth: 2,
            tension: 0.4,
        },
    ],
}));

const chartOptions = computed<ChartOptions<"line">>(() => ({
    responsive: true,
    maintainAspectRatio: false,
    animation: { duration: 600, easing: "easeOutExpo" } as any,
    interaction: { intersect: false, mode: "index" },
    plugins: {
        legend: { display: false },
        tooltip: {
            callbacks: {
                label: (ctx) => ` ${(ctx.parsed?.y ?? 0).toLocaleString("de-DE")} Domains`,
            },
        },
    },
    scales: {
        x: {
            grid: { display: false },
            border: { display: false },
            ticks: { color: "#6b7280", font: { size: 11 }, maxTicksLimit: 6, maxRotation: 0 },
        },
        y: {
            grid: { color: "rgba(255,255,255,0.04)" },
            border: { display: false },
            ticks: {
                color: "#6b7280",
                font: { size: 11 },
                maxTicksLimit: 4,
                callback: (v: any) => (v >= 1000 ? `${Math.round(v / 1000)}k` : v),
            },
        },
    },
}));
</script>
