<?php
/** @var array $template */
/** @var array $stops    Each: sort_order, asset_name, reading_key, reading_unit, min_ok, max_ok, points[] */
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="fw-bold mb-0"><i class="fas fa-chart-line me-2 text-primary"></i>Reading trends · <?= e($template['name']) ?></h5>
    <a class="btn btn-sm btn-outline-secondary" href="<?= url('/Rounds') ?>"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<p class="text-muted small">
    Last 30 runs of this route. Each chart shows the numeric reading captured at that stop over time —
    green band is the acceptable range from the template, red points are flagged readings.
</p>

<?php if (empty($stops)): ?>
    <div class="rs-card p-4 text-center text-muted">
        No numeric reading history yet. Charts will appear once operators have walked this route a few times and entered readings.
    </div>
<?php else: ?>
    <div id="trendsApp" v-cloak>
        <div v-for="s in stops" :key="s.stop_id" class="rs-card p-3 mb-3">
            <div class="d-flex justify-content-between align-items-baseline mb-2">
                <h6 class="fw-bold mb-0">
                    #{{ s.sort_order }} · {{ s.asset_name }}
                    <small class="text-muted ms-1">{{ s.reading_key }} <span v-if="s.reading_unit">({{ s.reading_unit }})</span></small>
                </h6>
                <span class="small text-muted">{{ s.points.length }} readings · latest {{ latestFormatted(s) }}</span>
            </div>
            <div :id="'trend_' + s.stop_id" style="height:220px;"></div>
        </div>
    </div>

    <?php $this->start('scripts'); ?>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@3.53.0/dist/apexcharts.min.js"></script>
    <script>
    (function () {
        const stops = <?= json_encode(array_map(static function ($s) {
            return [
                'stop_id'      => (int) $s['stop_id'],
                'sort_order'   => (int) $s['sort_order'],
                'asset_name'   => (string) $s['asset_name'],
                'reading_key'  => (string) ($s['reading_key'] ?? ''),
                'reading_unit' => (string) ($s['reading_unit'] ?? ''),
                'min_ok'       => $s['min_ok'] !== null ? (float) $s['min_ok'] : null,
                'max_ok'       => $s['max_ok'] !== null ? (float) $s['max_ok'] : null,
                'points'       => $s['points'],
            ];
        }, $stops), JSON_UNESCAPED_UNICODE) ?>;

        Vue.createApp({
            data() { return { stops }; },
            mounted() {
                this.$nextTick(() => this.renderCharts());
            },
            methods: {
                latestFormatted(s) {
                    if (!s.points.length) return '—';
                    const p = s.points[s.points.length - 1];
                    return `${p.value}${s.reading_unit ? ' ' + s.reading_unit : ''}`;
                },
                renderCharts() {
                    for (const s of this.stops) {
                        const el = document.getElementById('trend_' + s.stop_id);
                        if (!el) continue;
                        const cfg = buildChartCfg(s);
                        new ApexCharts(el, cfg).render();
                    }
                },
            },
        }).mount('#trendsApp');

        function buildChartCfg(s) {
            const categories = s.points.map(p => (p.checked_at || '').substring(0, 16));
            const data       = s.points.map(p => p.value);
            const colors     = s.points.map(p => p.is_ok ? '#22c55e' : '#ef4444');

            // Threshold band via ApexCharts annotations
            const annotations = { yaxis: [] };
            if (s.min_ok !== null && s.max_ok !== null) {
                annotations.yaxis.push({
                    y: s.min_ok, y2: s.max_ok,
                    fillColor: '#22c55e', opacity: 0.08,
                    borderColor: 'transparent',
                    label: { text: `OK range [${s.min_ok}, ${s.max_ok}]`, position: 'right',
                             style: { color: '#22c55e', background: 'transparent', fontSize: '10px' } },
                });
            } else if (s.min_ok !== null) {
                annotations.yaxis.push({ y: s.min_ok, borderColor: '#22c55e',
                    label: { text: `min ${s.min_ok}`, style: { color: '#22c55e', background: 'transparent' } }});
            } else if (s.max_ok !== null) {
                annotations.yaxis.push({ y: s.max_ok, borderColor: '#22c55e',
                    label: { text: `max ${s.max_ok}`, style: { color: '#22c55e', background: 'transparent' } }});
            }

            return {
                chart:  { type: 'line', height: 220, toolbar: { show: false } },
                series: [{ name: s.reading_key || 'reading', data }],
                xaxis:  { categories, labels: { rotate: -35, style: { fontSize: '9px' } } },
                yaxis:  { title: { text: s.reading_unit || null } },
                colors: ['#1a4d8c'],
                stroke: { curve: 'smooth', width: 2 },
                markers:{ size: 5, colors, strokeWidth: 0 },
                grid:   { borderColor: '#eee' },
                annotations,
                tooltip:{ x: { format: 'yyyy-MM-dd HH:mm' } },
            };
        }
    })();
    </script>
    <?php $this->end(); ?>
<?php endif; ?>
