<template>
	<div class="pie-chart" :style="wrapperStyle">
		<canvas ref="canvas"></canvas>
	</div>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
	name: 'PieChart',

	props: {
		labels: { type: Array, default: () => [] },
		values: { type: Array, default: () => [] },
		datasetLabel: { type: String, default: '' },
		height: { type: [Number, String], default: 240 },
		colors: { type: Array, default: () => [] },
		/** When true, renders a doughnut (ring) chart; `cutout` is applied. */
		doughnut: { type: Boolean, default: false },
		cutout: { type: [String, Number], default: '58%' },
		options: { type: Object, default: () => ({}) }
	},

	data: () => ({
		chart: null
	}),

	computed: {
		wrapperStyle: function () {
			var h = this.height;
			var px = (typeof h === 'number') ? (h + 'px') : String(h);
			return { height: px };
		},

		resolvedColors: function () {
			var base = this.colors || [];
			// Fallback palette (Chart.js-ish defaults) if caller doesn't provide colors.
			var palette = [
				'#4dc9f6', '#f67019', '#f53794', '#537bc4', '#acc236',
				'#166a8f', '#00a950', '#58595b', '#8549ba',
			];
			var out = [];
			var n = Math.max((this.labels || []).length, (this.values || []).length);
			for (var i = 0; i < n; i++) {
				out.push(base[i] || palette[i % palette.length]);
			}
			return out;
		}
	},

	watch: {
		labels: function () { this.renderChart(); },
		values: function () { this.renderChart(); },
		colors: function () { this.renderChart(); },
		doughnut: function () { this.renderChart(); },
		cutout: function () { this.renderChart(); },
		options: {
			handler: function () { this.renderChart(); },
			deep: true
		}
	},

	mounted: function () {
		this.renderChart();
	},

	beforeDestroy: function () {
		this.destroyChart();
	},

	methods: {
		destroyChart: function () {
			if (!this.chart) return;
			try { this.chart.destroy(); } catch (e) { }
			this.chart = null;
		},

		renderChart: function () {
			this.destroyChart();
			if (!this.$refs || !this.$refs.canvas) return;

			var ctx = this.$refs.canvas.getContext('2d');
			var labels = (this.labels || []).map(function (x) { return String(x); });
			var values = (this.values || []).map(function (v) { return Number(v) || 0; });

			var baseOptions = {
				responsive: true,
				maintainAspectRatio: false,
				plugins: {
					legend: { position: 'bottom' },
					tooltip: { enabled: true }
				}
			};
			if (this.doughnut) {
				baseOptions.cutout = this.cutout;
			}

			var mergedOptions = Object.assign({}, baseOptions, this.options || {});

			this.chart = new Chart(ctx, {
				type: this.doughnut ? 'doughnut' : 'pie',
				data: {
					labels: labels,
					datasets: [{
						label: this.datasetLabel,
						data: values,
						backgroundColor: this.resolvedColors,
						borderColor: '#ffffff',
						borderWidth: 1
					}]
				},
				options: mergedOptions
			});
		}
	}
};
</script>

<style scoped>
.pie-chart {
	width: 100%;
}
</style>

