/**
 * Detailed SEO trend modal (bars / line / candles).
 */
(function () {
	'use strict';

	var cfg = window.icommSmTrendChart || null;
	if (!cfg || !cfg.months || !cfg.months.length) {
		return;
	}

	var chart = null;
	var state = {
		type: 'line',
		metric: 'both',
		range: 'all'
	};

	function $(sel, root) {
		return (root || document).querySelector(sel);
	}

	function $all(sel, root) {
		return Array.prototype.slice.call((root || document).querySelectorAll(sel));
	}

	function sliceMonths(months) {
		var n = months.length;
		if (state.range === '6') {
			return months.slice(Math.max(0, n - 6));
		}
		if (state.range === '12') {
			return months.slice(Math.max(0, n - 12));
		}
		return months.slice();
	}

	function sliceDaily(daily, months) {
		if (!daily || !daily.length || !months.length) {
			return [];
		}
		var from = months[0].ym + '-01';
		var last = months[months.length - 1].ym;
		var y = parseInt(last.slice(0, 4), 10);
		var m = parseInt(last.slice(5, 7), 10);
		var lastDay = new Date(Date.UTC(y, m, 0)).getUTCDate();
		var to = last + '-' + String(lastDay).padStart(2, '0');
		return daily.filter(function (d) {
			return d.date >= from && d.date <= to;
		});
	}

	function sliceOhlc(ohlc, months) {
		if (!ohlc || !ohlc.length) {
			return [];
		}
		var set = {};
		months.forEach(function (m) {
			set[m.ym] = true;
		});
		return ohlc.filter(function (r) {
			return set[r.ym];
		});
	}

	function openModal() {
		var modal = $('#icomm-sm-trend-modal');
		if (!modal) {
			return;
		}
		modal.classList.add('is-open');
		modal.setAttribute('aria-hidden', 'false');
		document.body.classList.add('icomm-sm-trend-modal-open');
		renderChart();
	}

	function closeModal() {
		var modal = $('#icomm-sm-trend-modal');
		if (!modal) {
			return;
		}
		modal.classList.remove('is-open');
		modal.setAttribute('aria-hidden', 'true');
		document.body.classList.remove('icomm-sm-trend-modal-open');
		if (chart) {
			chart.destroy();
			chart = null;
		}
	}

	function setActive(group, value) {
		$all('[data-icomm-sm-chart-' + group + ']', $('#icomm-sm-trend-modal')).forEach(function (btn) {
			var on = btn.getAttribute('data-icomm-sm-chart-' + group) === value;
			btn.classList.toggle('is-active', on);
			btn.setAttribute('aria-pressed', on ? 'true' : 'false');
		});
	}

	function buildDatasets(months, daily) {
		var labels = months.map(function (m) {
			return m.label;
		});
		var clicks = months.map(function (m) {
			return Number(m.clicks) || 0;
		});
		var impr = months.map(function (m) {
			return Number(m.impressions) || 0;
		});
		var blue = '#1d4ed8';
		var orange = '#ea580c';
		var green = '#15803d';
		var red = '#b91c1c';

		if (state.type === 'candles') {
			var key = state.metric === 'impressions' ? 'impressions' : 'clicks';
			var src = key === 'impressions' ? (cfg.ohlcImpressions || []) : (cfg.ohlcClicks || []);
			var ohlc = sliceOhlc(src, months);
			labels = ohlc.map(function (r) {
				return r.label;
			});
			var rangeBars = ohlc.map(function (r) {
				return [Number(r.l) || 0, Number(r.h) || 0];
			});
			var closePts = ohlc.map(function (r) {
				return Number(r.c) || 0;
			});
			var colors = ohlc.map(function (r) {
				return Number(r.c) >= Number(r.o) ? green : red;
			});
			var accent = key === 'impressions' ? orange : blue;
			return {
				labels: labels,
				datasets: [
					{
						type: 'bar',
						label: cfg.i18n.rangeDay || 'טווח יומי',
						data: rangeBars,
						backgroundColor: colors.map(function (c) {
							return c === green ? 'rgba(21,128,61,0.28)' : 'rgba(185,28,28,0.28)';
						}),
						borderColor: colors,
						borderWidth: 1.5,
						borderSkipped: false,
						barPercentage: 0.55,
						categoryPercentage: 0.7,
						yAxisID: 'y'
					},
					{
						type: 'line',
						label: cfg.i18n.close || 'סגירה',
						data: closePts,
						borderColor: accent,
						backgroundColor: accent,
						borderWidth: 2.5,
						tension: 0.25,
						pointRadius: 3,
						yAxisID: 'y'
					}
				],
				scales: {
					y: {
						beginAtZero: true,
						title: { display: true, text: key === 'impressions' ? cfg.i18n.impressions : cfg.i18n.clicks }
					}
				},
				hint: cfg.i18n.candleHint || ''
			};
		}

		if (state.type === 'line' && state.metric !== 'both' && daily && daily.length > 14) {
			var d = sliceDaily(daily, months);
			labels = d.map(function (row) {
				return row.date;
			});
			var series = d.map(function (row) {
				return Number(row[state.metric]) || 0;
			});
			var isImpr = state.metric === 'impressions';
			return {
				labels: labels,
				datasets: [
					{
						type: 'line',
						label: isImpr ? cfg.i18n.impressions : cfg.i18n.clicks,
						data: series,
						borderColor: isImpr ? orange : blue,
						backgroundColor: isImpr ? 'rgba(234,88,12,0.14)' : 'rgba(29,78,216,0.14)',
						borderWidth: 2.5,
						fill: true,
						tension: 0.3,
						pointRadius: 0,
						pointHoverRadius: 3,
						yAxisID: 'y'
					}
				],
				scales: {
					y: {
						beginAtZero: true,
						title: {
							display: true,
							text: isImpr ? cfg.i18n.impressions : cfg.i18n.clicks
						}
					}
				},
				hint: cfg.i18n.dailyHint || ''
			};
		}

		var datasets = [];
		var scales = {
			y: { beginAtZero: true, position: 'right', title: { display: true, text: cfg.i18n.clicks } }
		};

		if (state.metric === 'clicks' || state.metric === 'both') {
			datasets.push({
				type: state.type === 'bars' ? 'bar' : 'line',
				label: cfg.i18n.clicks,
				data: clicks,
				borderColor: blue,
				backgroundColor: state.type === 'bars' ? blue : 'rgba(29,78,216,0.14)',
				borderWidth: 2.5,
				fill: state.type === 'line',
				tension: 0.3,
				yAxisID: 'y',
				barPercentage: 0.7,
				categoryPercentage: 0.65
			});
		}
		if (state.metric === 'impressions' || state.metric === 'both') {
			var axis = state.metric === 'both' ? 'y1' : 'y';
			if (state.metric === 'both') {
				scales.y1 = {
					beginAtZero: true,
					position: 'left',
					grid: { drawOnChartArea: false },
					title: { display: true, text: cfg.i18n.impressions }
				};
			} else {
				scales.y.title.text = cfg.i18n.impressions;
			}
			datasets.push({
				type: state.type === 'bars' ? 'bar' : 'line',
				label: cfg.i18n.impressions,
				data: impr,
				borderColor: orange,
				backgroundColor: state.type === 'bars' ? orange : 'rgba(234,88,12,0.14)',
				borderWidth: 2.5,
				fill: state.type === 'line',
				tension: 0.3,
				yAxisID: axis,
				barPercentage: 0.7,
				categoryPercentage: 0.65
			});
		}

		return {
			labels: labels,
			datasets: datasets,
			scales: scales,
			hint: ''
		};
	}

	function renderChart() {
		if (typeof window.Chart === 'undefined') {
			var err = $('#icomm-sm-trend-chart-error');
			if (err) {
				err.hidden = false;
				err.textContent = cfg.i18n.chartMissing || 'Chart library missing';
			}
			return;
		}
		var canvas = $('#icomm-sm-trend-canvas');
		if (!canvas) {
			return;
		}
		var months = sliceMonths(cfg.months || []);
		var built = buildDatasets(months, cfg.daily || []);
		var hint = $('#icomm-sm-trend-chart-hint');
		if (hint) {
			hint.textContent = built.hint || '';
			hint.hidden = !built.hint;
		}
		if (chart) {
			chart.destroy();
			chart = null;
		}
		chart = new window.Chart(canvas.getContext('2d'), {
			type: 'bar',
			data: {
				labels: built.labels,
				datasets: built.datasets
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				locale: 'he-IL',
				interaction: { mode: 'index', intersect: false },
				plugins: {
					legend: {
						position: 'top',
						rtl: true,
						textDirection: 'rtl',
						labels: { boxWidth: 12, font: { family: 'inherit' } }
					},
					tooltip: {
						rtl: true,
						textDirection: 'rtl',
						callbacks: {
							label: function (ctx) {
								var v = ctx.raw;
								if (Array.isArray(v)) {
									return (ctx.dataset.label || '') + ': ' + v[0] + ' - ' + v[1];
								}
								return (ctx.dataset.label || '') + ': ' + v;
							}
						}
					}
				},
				scales: Object.assign(
					{
						x: {
							reverse: true,
							ticks: {
								maxRotation: 45,
								minRotation: 0,
								autoSkip: true
							}
						}
					},
					built.scales || {}
				)
			}
		});
	}

	function bind() {
		$all('[data-icomm-sm-open-trend-chart]').forEach(function (el) {
			el.addEventListener('click', function (e) {
				e.preventDefault();
				openModal();
			});
			el.addEventListener('keydown', function (e) {
				if (e.key === 'Enter' || e.key === ' ') {
					e.preventDefault();
					openModal();
				}
			});
		});
		$all('[data-icomm-sm-close-trend-chart]').forEach(function (el) {
			el.addEventListener('click', function (e) {
				e.preventDefault();
				closeModal();
			});
		});
		document.addEventListener('keydown', function (e) {
			if (e.key === 'Escape') {
				closeModal();
			}
		});

		var modal = $('#icomm-sm-trend-modal');
		if (!modal) {
			return;
		}
		modal.addEventListener('click', function (e) {
			if (e.target === modal) {
				closeModal();
			}
		});

		$all('[data-icomm-sm-chart-type]', modal).forEach(function (btn) {
			btn.addEventListener('click', function () {
				state.type = btn.getAttribute('data-icomm-sm-chart-type') || 'line';
				setActive('type', state.type);
				if (state.type === 'candles' && state.metric === 'both') {
					state.metric = 'clicks';
					setActive('metric', state.metric);
				}
				renderChart();
			});
		});
		$all('[data-icomm-sm-chart-metric]', modal).forEach(function (btn) {
			btn.addEventListener('click', function () {
				state.metric = btn.getAttribute('data-icomm-sm-chart-metric') || 'both';
				if (state.type === 'candles' && state.metric === 'both') {
					state.metric = 'clicks';
				}
				setActive('metric', state.metric);
				renderChart();
			});
		});
		$all('[data-icomm-sm-chart-range]', modal).forEach(function (btn) {
			btn.addEventListener('click', function () {
				state.range = btn.getAttribute('data-icomm-sm-chart-range') || 'all';
				setActive('range', state.range);
				renderChart();
			});
		});
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', bind);
	} else {
		bind();
	}
})();
