<?php
// Serialise templates into a compact JS-safe payload for the Vue app.
$vueTemplates = array_map(static function (array $t): array {
    return [
        'id'           => (int) $t['template_id'],
        'name'         => (string) ($t['name'] ?? ''),
        'code'         => (string) ($t['code'] ?? ''),
        'description'  => (string) ($t['description'] ?? ''),
        'priority'     => (string) ($t['priority'] ?? 'medium'),
        'assetType'    => (string) ($t['asset_type_name'] ?? ''),
        'taskCount'    => (int) ($t['task_count'] ?? 0),
        'intervalDays' => (int) ($t['interval_days'] ?? 0),
        'startUrl'     => url('/Checklists/start/' . (int) $t['template_id']),
    ];
}, $templates ?? []);
?>
<div id="checklistsApp" v-cloak>
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="fw-bold mb-0"><i class="fas fa-clipboard-list me-2 text-primary"></i>Available Checklists</h5>
        <div class="btn-group btn-group-sm" role="group" aria-label="View mode">
            <button type="button" class="btn"
                    :class="viewMode === 'grid' ? 'btn-primary' : 'btn-outline-secondary'"
                    @click="setView('grid')">
                <i class="fas fa-th-large me-1"></i>Grid
            </button>
            <button type="button" class="btn"
                    :class="viewMode === 'list' ? 'btn-primary' : 'btn-outline-secondary'"
                    @click="setView('list')">
                <i class="fas fa-list me-1"></i>List
            </button>
        </div>
    </div>

    <p class="text-muted small">
        Every published PM template can be run ad-hoc — e.g. the <em>Daily Generator Checklist</em>
        or the <em>Daily Power, Lighting &amp; Grounding Sweep</em>.
        You can also let the system auto-schedule them via
        <a href="<?= url('/PmTemplates') ?>" class="text-decoration-none">PM Templates → Schedules</a>.
    </p>

    <?php if (!empty($flash)): ?><div class="alert alert-info py-2 small"><?= e($flash) ?></div><?php endif; ?>

    <div class="mb-3">
        <input type="search" class="form-control form-control-sm" placeholder="Filter checklists…" v-model="search">
    </div>

    <template v-if="!filtered.length">
        <div class="rs-card p-4 text-center">
            <p class="text-muted mb-2" v-if="search">No checklists match your filter.</p>
            <p class="text-muted mb-2" v-else>No published checklists yet.</p>
            <a href="<?= url('/PmTemplates/create') ?>" class="btn btn-sm btn-primary"><i class="fas fa-plus me-1"></i>Create the first one</a>
        </div>
    </template>

    <!-- ── GRID VIEW ────────────────────────────────────────────────── -->
    <div v-else-if="viewMode === 'grid'" class="row g-3">
        <div v-for="t in filtered" :key="t.id" class="col-md-6 col-xl-4">
            <div class="rs-card h-100 p-3 d-flex flex-column">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="fw-bold mb-1">{{ t.name }}</h6>
                        <code v-if="t.code" class="small text-muted">{{ t.code }}</code>
                    </div>
                    <span class="badge bg-secondary text-uppercase" style="font-size:.6rem;">{{ t.priority }}</span>
                </div>
                <p v-if="t.description" class="small text-muted mb-2">{{ t.description }}</p>
                <ul class="list-unstyled small text-muted mb-3">
                    <li><i class="fas fa-cogs me-1"></i>{{ t.assetType ? 'Applies to ' + t.assetType : 'Any asset' }}</li>
                    <li><i class="fas fa-list me-1"></i>{{ t.taskCount }} task{{ t.taskCount === 1 ? '' : 's' }}</li>
                    <li><i class="fas fa-calendar me-1"></i>Every {{ t.intervalDays }} day{{ t.intervalDays === 1 ? '' : 's' }}</li>
                </ul>
                <div class="mt-auto d-flex gap-2">
                    <a class="btn btn-sm btn-primary flex-fill" :href="t.startUrl">
                        <i class="fas fa-play me-1"></i>Start
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- ── LIST VIEW ────────────────────────────────────────────────── -->
    <div v-else class="rs-card p-0">
        <table class="table table-hover mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Checklist</th>
                    <th>Code</th>
                    <th>Applies to</th>
                    <th class="text-center">Tasks</th>
                    <th class="text-center">Interval</th>
                    <th class="text-center">Priority</th>
                    <th class="text-end" style="width:110px;"></th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="t in filtered" :key="t.id">
                    <td>
                        <strong>{{ t.name }}</strong>
                        <div v-if="t.description" class="small text-muted">{{ t.description }}</div>
                    </td>
                    <td><code v-if="t.code" class="small text-muted">{{ t.code }}</code><span v-else class="text-muted">—</span></td>
                    <td class="small">{{ t.assetType || 'Any asset' }}</td>
                    <td class="text-center small">{{ t.taskCount }}</td>
                    <td class="text-center small">{{ t.intervalDays }}d</td>
                    <td class="text-center"><span class="badge bg-secondary text-uppercase" style="font-size:.6rem;">{{ t.priority }}</span></td>
                    <td class="text-end">
                        <a class="btn btn-sm btn-primary" :href="t.startUrl"><i class="fas fa-play me-1"></i>Start</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<?php $this->start('scripts'); ?>
<script>
(function () {
    const templates = <?= json_encode($vueTemplates, JSON_UNESCAPED_SLASHES) ?>;
    const STORAGE_KEY = 'orchview.checklistsViewMode';

    Vue.createApp({
        data() {
            return {
                templates,
                search: '',
                viewMode: (localStorage.getItem(STORAGE_KEY) === 'list') ? 'list' : 'grid',
            };
        },
        computed: {
            filtered() {
                const q = this.search.trim().toLowerCase();
                if (!q) return this.templates;
                return this.templates.filter(t =>
                    (t.name        || '').toLowerCase().includes(q) ||
                    (t.code        || '').toLowerCase().includes(q) ||
                    (t.description || '').toLowerCase().includes(q) ||
                    (t.assetType   || '').toLowerCase().includes(q)
                );
            },
        },
        methods: {
            setView(m) {
                this.viewMode = m;
                try { localStorage.setItem(STORAGE_KEY, m); } catch (e) { /* private mode */ }
            },
        },
    }).mount('#checklistsApp');
})();
</script>
<?php $this->end(); ?>
