<?php
defined('BASE_PATH') || exit;
/** @var string $mode  'create'|'edit' */
/** @var array|null $poll */
/** @var array $form */
/** @var array $errors */
$action  = $mode === 'edit' ? '/polls/' . (int)$poll['id'] . '/edit' : '/polls/create';
$backUrl = $mode === 'edit' ? '/polls/' . (int)$poll['id'] : '/polls';
// Only rows that carry a real ISO date are useful to the calendar widget.
$prefilled = array_values(array_filter(
    $form['options'],
    fn($o) => !empty($o['date']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$o['date'])
));
$presets = ['08:00', '09:00', '10:00', '12:00', '14:00', '16:00', '18:00'];
?>
<div class="page-header">
    <div class="page-header-left">
        <a href="<?= Helper::e($backUrl) ?>" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <?= t('back') ?>
        </a>
        <h1 class="page-title"><?= $mode === 'edit' ? t('mp_edit_title') : t('mp_create_title') ?></h1>
    </div>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-error" role="alert">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>
    <div><?php foreach ($errors as $e): ?><div><?= Helper::e($e) ?></div><?php endforeach; ?></div>
</div>
<?php endif; ?>

<form method="POST" action="<?= Helper::e($action) ?>" class="card" style="max-width:820px">
    <?= Helper::csrf() ?>
    <div class="card-body" style="display:flex;flex-direction:column;gap:1rem">

        <div class="form-group">
            <label class="form-label" for="mp-title"><?= t('mp_field_title') ?> <span style="color:#dc2626">*</span></label>
            <input type="text" id="mp-title" name="title" class="form-input" maxlength="200" required
                   value="<?= Helper::e($form['title']) ?>" placeholder="<?= t('mp_field_title_ph') ?>">
        </div>

        <div class="form-group">
            <label class="form-label" for="mp-desc"><?= t('mp_field_desc') ?></label>
            <textarea id="mp-desc" name="description" class="form-textarea" rows="3" maxlength="5000" placeholder="<?= t('mp_field_desc_ph') ?>"><?= Helper::e($form['description']) ?></textarea>
        </div>

        <div class="form-row" style="display:flex;gap:1rem;flex-wrap:wrap">
            <div class="form-group" style="flex:1;min-width:240px">
                <label class="form-label" for="mp-loc"><?= t('mp_field_location') ?></label>
                <input type="text" id="mp-loc" name="location" class="form-input" maxlength="300"
                       value="<?= Helper::e($form['location']) ?>" placeholder="<?= t('mp_field_location_ph') ?>">
            </div>
            <div class="form-group" style="flex:1;min-width:240px">
                <label class="form-label" for="mp-deadline"><?= t('mp_field_deadline') ?></label>
                <input type="datetime-local" id="mp-deadline" name="deadline" class="form-input" value="<?= Helper::e($form['deadline']) ?>">
                <small class="form-hint"><?= t('mp_field_deadline_hint') ?></small>
            </div>
        </div>

        <fieldset style="border:1px solid var(--border-color);border-radius:8px;padding:1rem">
            <legend style="padding:0 .4rem;font-size:.85rem;color:var(--text-muted)"><?= t('mp_field_options') ?></legend>

            <div class="mp-default-time">
                <span class="form-label" style="margin:0"><?= t('mp_default_time') ?></span>
                <div class="mp-time-presets" id="mp-presets">
                    <button type="button" class="mp-preset" data-t=""><?= t('mp_all_day') ?></button>
                    <?php foreach ($presets as $p): ?>
                    <button type="button" class="mp-preset<?= $p === '09:00' ? ' active' : '' ?>" data-t="<?= Helper::e($p) ?>"><?= Helper::e($p) ?></button>
                    <?php endforeach; ?>
                    <input type="time" id="mp-custom-time" class="form-input mp-time" aria-label="<?= t('mp_default_time') ?>">
                </div>
                <label class="mp-dur-wrap"><?= t('mp_duration') ?> <select id="mp-default-dur" class="form-select mp-dur-sel"></select></label>
                <button type="button" class="btn btn-ghost btn-xs" id="mp-apply-all"><?= t('mp_apply_to_all') ?></button>
            </div>

            <p class="form-hint" style="margin:.6rem 0 .7rem"><?= t('mp_cal_hint') ?></p>

            <div class="mp-cal-wrap">
                <div id="mp-calendar" class="mp-cal"></div>
                <div class="mp-cal-side">
                    <div id="mp-options" class="mp-rows"></div>
                    <p id="mp-empty-note" class="form-hint" style="margin:.4rem 0 0"><?= t('mp_no_dates') ?></p>
                </div>
            </div>

            <?php // Server-rendered seed rows for the JS widget (edit mode / re-render after a validation error). ?>
            <div id="mp-seed" hidden>
                <?php foreach ($prefilled as $o): ?>
                <span data-date="<?= Helper::e($o['date']) ?>" data-start="<?= Helper::e($o['start'] ?? '') ?>" data-end="<?= Helper::e($o['end'] ?? '') ?>"></span>
                <?php endforeach; ?>
            </div>

            <small class="form-hint" style="display:block;margin-top:.7rem"><?= t('mp_opt_hint') ?></small>
            <noscript><p class="form-hint" style="color:#b45309"><?= t('mp_cal_nojs') ?></p></noscript>
        </fieldset>

        <div style="display:flex;flex-direction:column;gap:.5rem">
            <label style="display:flex;align-items:center;gap:.5rem;cursor:pointer">
                <input type="hidden" name="allow_maybe" value="0">
                <input type="checkbox" name="allow_maybe" value="1" <?= $form['allow_maybe'] ? 'checked' : '' ?>>
                <span><?= t('mp_field_allow_maybe') ?></span>
            </label>
            <label style="display:flex;align-items:center;gap:.5rem;cursor:pointer">
                <input type="hidden" name="hide_results" value="0">
                <input type="checkbox" name="hide_results" value="1" <?= $form['hide_results'] ? 'checked' : '' ?>>
                <span><?= t('mp_field_hide_results') ?></span>
            </label>
            <label style="display:flex;align-items:center;gap:.5rem;cursor:pointer">
                <input type="hidden" name="notify_owner" value="0">
                <input type="checkbox" name="notify_owner" value="1" <?= $form['notify_owner'] ? 'checked' : '' ?>>
                <span><?= t('mp_field_notify_owner') ?></span>
            </label>
        </div>

        <div class="form-actions" style="display:flex;gap:.5rem">
            <button type="submit" class="btn btn-primary"><?= $mode === 'edit' ? t('save') : t('mp_create_submit') ?></button>
            <a href="<?= Helper::e($backUrl) ?>" class="btn btn-ghost"><?= t('cancel') ?></a>
        </div>
    </div>
</form>

<template id="mp-row-template">
    <div class="mp-option-row" data-date="">
        <input type="hidden" name="opt_date[]" value="">
        <span class="mp-date-label"></span>
        <span class="mp-time-display"></span>
        <span class="mp-time-edit" hidden>
            <input type="time" name="opt_start[]" class="form-input mp-time mp-start" aria-label="<?= t('mp_opt_start') ?>">
            <span class="mp-time-sep">–</span>
            <input type="time" name="opt_end[]" class="form-input mp-time mp-end" aria-label="<?= t('mp_opt_end') ?>">
        </span>
        <button type="button" class="mp-edit-time" title="<?= t('mp_edit_time') ?>" aria-label="<?= t('mp_edit_time') ?>">✎</button>
        <button type="button" class="mp-remove-opt" title="<?= t('remove') ?>" aria-label="<?= t('remove') ?>">×</button>
    </div>
</template>

<style>
.mp-default-time{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap;background:var(--bg-table-head);border:1px solid var(--border-color);border-radius:6px;padding:.5rem .6rem}
.mp-time-presets{display:flex;align-items:center;gap:.35rem;flex-wrap:wrap}
.mp-preset{border:1px solid var(--border-color);background:var(--bg-card);border-radius:999px;padding:.25rem .6rem;font:inherit;font-size:.8rem;cursor:pointer;color:inherit}
.mp-preset:hover{border-color:var(--color-primary,#4f46e5)}
.mp-preset.active{background:var(--color-primary,#4f46e5);border-color:var(--color-primary,#4f46e5);color:#fff;font-weight:600}
.mp-time{width:auto;padding:.2rem .35rem;font-size:.8rem}
.mp-dur-wrap{font-size:.83rem;display:inline-flex;align-items:center;gap:.3rem;color:var(--text-muted)}
.mp-dur-sel{width:auto;padding:.18rem .3rem;font-size:.8rem}
.mp-dur-sel:disabled{opacity:.5}
.mp-cal-wrap{display:flex;gap:1.25rem;flex-wrap:wrap;align-items:flex-start;margin-top:.2rem}
.mp-cal{flex:0 0 auto;min-width:260px;user-select:none}
.mp-cal-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:.4rem;gap:.5rem}
.mp-cal-title{font-weight:600;text-transform:capitalize}
.mp-cal-nav{border:1px solid var(--border-color);background:var(--bg-table-head);border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:1rem;line-height:1}
.mp-cal-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:3px}
.mp-cal-wd{text-align:center;font-size:.7rem;color:var(--text-muted);padding:2px 0;text-transform:capitalize}
.mp-cal-empty{height:34px}
.mp-cal-day{height:34px;border:1px solid transparent;border-radius:6px;background:transparent;cursor:pointer;font:inherit;font-size:.85rem;color:inherit}
.mp-cal-day:hover{background:var(--bg-hover);border-color:var(--border-color)}
.mp-cal-day.today{font-weight:700;outline:1px dashed #94a3b8}
.mp-cal-day.selected{background:var(--color-primary,#4f46e5);color:#fff;border-color:var(--color-primary,#4f46e5);font-weight:700}
.mp-cal-day.selected:hover{background:var(--color-primary-dark,#4338ca)}
.mp-cal-side{flex:1;min-width:240px}
.mp-rows{display:flex;flex-direction:column;gap:.4rem}
.mp-option-row{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;background:var(--bg-table-head);border:1px solid var(--border-color);border-radius:6px;padding:.35rem .55rem}
.mp-option-row .mp-date-label{flex:1;min-width:120px;font-size:.88rem;font-weight:600;text-transform:capitalize}
.mp-option-row .mp-time-display{font-size:.83rem;color:var(--text-muted)}
.mp-time-edit{display:inline-flex;align-items:center;gap:.25rem}
.mp-time-sep{color:var(--text-muted);font-size:.8rem}
.mp-edit-time,.mp-remove-opt{border:0;background:transparent;cursor:pointer;line-height:1;padding:0 .2rem}
.mp-edit-time{color:var(--text-muted);font-size:.9rem}
.mp-remove-opt{color:#dc2626;font-size:1.1rem}
</style>
<script nonce="<?= csp_nonce() ?>">
(function () {
    var lang     = document.documentElement.getAttribute('lang') || 'de';
    var ALLDAY   = <?= json_encode(Lang::get('mp_all_day')) ?>;
    var DUR_NONE = <?= json_encode(Lang::get('mp_dur_none')) ?>;
    var calEl    = document.getElementById('mp-calendar');
    var list     = document.getElementById('mp-options');
    var note     = document.getElementById('mp-empty-note');
    var tpl      = document.getElementById('mp-row-template');
    var seedEl   = document.getElementById('mp-seed');
    var presetsBox = document.getElementById('mp-presets');
    var customInp  = document.getElementById('mp-custom-time');
    var durSel     = document.getElementById('mp-default-dur');
    var applyAll   = document.getElementById('mp-apply-all');
    if (!calEl || !list || !tpl) return;

    function pad(n) { return (n < 10 ? '0' : '') + n; }
    function isoOf(y, m, d) { return y + '-' + pad(m + 1) + '-' + pad(d); }

    // ── Duration select ────────────────────────────────────────────────────
    var DURATIONS = [0, 15, 30, 45, 60, 90, 120, 180, 240, 480];
    function durLabel(min) {
        if (min === 0) return DUR_NONE;
        if (min < 60) return min + ' min';
        var h = min / 60;
        try { h = h.toLocaleString(lang); } catch (e) { h = String(h); }
        return h + ' h';
    }
    if (durSel) {
        durSel.innerHTML = DURATIONS.map(function (m) {
            return '<option value="' + m + '"' + (m === 60 ? ' selected' : '') + '>' + durLabel(m) + '</option>';
        }).join('');
    }
    function defaultDuration() { return durSel ? (parseInt(durSel.value, 10) || 0) : 60; }
    function addMinutes(t, mins) {
        if (!/^\d{2}:\d{2}$/.test(t || '') || !mins) return '';
        var tot = parseInt(t.slice(0, 2), 10) * 60 + parseInt(t.slice(3, 5), 10) + mins;
        if (tot > 24 * 60 - 1) tot = 24 * 60 - 1;
        return pad(Math.floor(tot / 60)) + ':' + pad(tot % 60);
    }

    function timeLabel(start, end) {
        if (!start) return ALLDAY;
        return (end && end > start) ? (start + ' – ' + end) : start;
    }
    function defaultStart() {
        var c = (customInp && customInp.value) ? customInp.value : '';
        if (c) return c;
        var a = presetsBox ? presetsBox.querySelector('.mp-preset.active') : null;
        return a ? (a.getAttribute('data-t') || '') : '';
    }
    function syncDurState() { if (durSel) durSel.disabled = !defaultStart(); }
    function fmtDate(iso) {
        var d = new Date(iso + 'T00:00:00');
        try { return d.toLocaleDateString(lang, { weekday: 'short', day: '2-digit', month: '2-digit', year: 'numeric' }); }
        catch (e) { return iso; }
    }
    function selectedDates() {
        return Array.prototype.map.call(list.querySelectorAll('.mp-option-row'), function (r) { return r.dataset.date; });
    }
    function refreshNote() { if (note) note.style.display = list.querySelector('.mp-option-row') ? 'none' : ''; }

    function syncRow(row) {
        var s = row.querySelector('.mp-start').value || '';
        var e = row.querySelector('.mp-end').value || '';
        row.querySelector('.mp-time-display').textContent = timeLabel(s, e);
    }
    function setRowTime(row, start, end) {
        row.querySelector('.mp-start').value = start || '';
        row.querySelector('.mp-end').value   = end || '';
        syncRow(row);
    }
    function addDate(iso, start, end, fromSeed) {
        if (selectedDates().indexOf(iso) !== -1) return;
        var frag = tpl.content.cloneNode(true);
        var row  = frag.querySelector('.mp-option-row');
        row.dataset.date = iso;
        row.querySelector('input[name="opt_date[]"]').value = iso;
        row.querySelector('.mp-date-label').textContent = fmtDate(iso);
        if (fromSeed) { setRowTime(row, start || '', end || ''); }
        else { var d = defaultStart(); setRowTime(row, d, d ? addMinutes(d, defaultDuration()) : ''); }
        var rows   = Array.prototype.slice.call(list.querySelectorAll('.mp-option-row'));
        var before = null;
        for (var i = 0; i < rows.length; i++) { if (rows[i].dataset.date > iso) { before = rows[i]; break; } }
        list.insertBefore(frag, before);
        refreshNote();
    }
    function removeDate(iso) {
        var r = list.querySelector('.mp-option-row[data-date="' + iso + '"]');
        if (r) r.remove();
        refreshNote();
    }

    // ── Default-time picker ────────────────────────────────────────────────
    if (presetsBox) {
        presetsBox.addEventListener('click', function (ev) {
            var b = ev.target.closest('.mp-preset');
            if (!b) return;
            Array.prototype.forEach.call(presetsBox.querySelectorAll('.mp-preset'), function (x) { x.classList.remove('active'); });
            b.classList.add('active');
            if (customInp) customInp.value = '';
            syncDurState();
        });
        if (customInp) {
            customInp.addEventListener('input', function () {
                if (customInp.value) Array.prototype.forEach.call(presetsBox.querySelectorAll('.mp-preset'), function (x) { x.classList.remove('active'); });
                syncDurState();
            });
        }
    }
    if (applyAll) {
        applyAll.addEventListener('click', function () {
            var d = defaultStart(), dur = defaultDuration();
            Array.prototype.forEach.call(list.querySelectorAll('.mp-option-row'), function (r) {
                setRowTime(r, d, d ? addMinutes(d, dur) : '');
            });
        });
    }

    // ── Row interactions ───────────────────────────────────────────────────
    list.addEventListener('click', function (ev) {
        if (ev.target.closest('.mp-remove-opt')) { ev.target.closest('.mp-option-row').remove(); refreshNote(); render(); return; }
        var ed = ev.target.closest('.mp-edit-time');
        if (ed) { var box = ed.closest('.mp-option-row').querySelector('.mp-time-edit'); box.hidden = !box.hidden; if (!box.hidden) { var i = box.querySelector('input'); if (i) i.focus(); } }
    });
    list.addEventListener('input', function (ev) {
        var row = ev.target.closest('.mp-option-row'); if (!row) return;
        if (ev.target.classList.contains('mp-start')) {
            var s = ev.target.value, e = row.querySelector('.mp-end');
            if (s && (!e.value || e.value <= s)) e.value = addMinutes(s, defaultDuration());
        }
        syncRow(row);
    });

    // ── Calendar ───────────────────────────────────────────────────────────
    var view = new Date(); view.setDate(1); view.setHours(0, 0, 0, 0);
    function render() {
        var y = view.getFullYear(), m = view.getMonth();
        var sel = selectedDates();
        var first = new Date(y, m, 1);
        var startWd = (first.getDay() + 6) % 7; // Monday-first
        var daysInMonth = new Date(y, m + 1, 0).getDate();
        var wd = [];
        for (var i = 0; i < 7; i++) {
            try { wd.push(new Date(Date.UTC(2024, 0, 1 + i)).toLocaleDateString(lang, { weekday: 'short', timeZone: 'UTC' })); }
            catch (e) { wd.push(['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'][i]); }
        }
        var now = new Date(), todayIso = isoOf(now.getFullYear(), now.getMonth(), now.getDate());
        var title;
        try { title = first.toLocaleDateString(lang, { month: 'long', year: 'numeric' }); } catch (e) { title = (m + 1) + '/' + y; }
        var h = '<div class="mp-cal-head"><button type="button" class="mp-cal-nav" data-d="-1">‹</button>'
              + '<span class="mp-cal-title"></span>'
              + '<button type="button" class="mp-cal-nav" data-d="1">›</button></div><div class="mp-cal-grid">';
        for (var w = 0; w < 7; w++) h += '<div class="mp-cal-wd">' + wd[w] + '</div>';
        for (var b = 0; b < startWd; b++) h += '<div class="mp-cal-empty"></div>';
        for (var d = 1; d <= daysInMonth; d++) {
            var iso = isoOf(y, m, d);
            var cls = 'mp-cal-day' + (sel.indexOf(iso) !== -1 ? ' selected' : '') + (iso === todayIso ? ' today' : '');
            h += '<button type="button" class="' + cls + '" data-iso="' + iso + '">' + d + '</button>';
        }
        h += '</div>';
        calEl.innerHTML = h;
        calEl.querySelector('.mp-cal-title').textContent = title;
    }
    calEl.addEventListener('click', function (ev) {
        var nav = ev.target.closest('.mp-cal-nav');
        if (nav) { view.setMonth(view.getMonth() + parseInt(nav.getAttribute('data-d'), 10)); render(); return; }
        var day = ev.target.closest('.mp-cal-day');
        if (day) {
            var iso = day.getAttribute('data-iso');
            if (selectedDates().indexOf(iso) !== -1) removeDate(iso); else addDate(iso);
            render();
        }
    });

    // ── Seed from server-rendered rows (edit / validation re-render) ────────
    if (seedEl) {
        Array.prototype.forEach.call(seedEl.querySelectorAll('span[data-date]'), function (s) {
            addDate(s.getAttribute('data-date'), s.getAttribute('data-start'), s.getAttribute('data-end'), true);
        });
    }
    var sd = selectedDates().slice().sort();
    if (sd.length) { var fd = new Date(sd[0] + 'T00:00:00'); view = new Date(fd.getFullYear(), fd.getMonth(), 1); }
    syncDurState();
    refreshNote();
    render();
})();
</script>
