<?php
defined('BASE_PATH') || exit;
/** @var array $poll */
/** @var array $options */
/** @var array $responses */
/** @var array $stats */
/** @var array $invites */
/** @var string $shareUrl */
$finalized   = !empty($poll['final_option_id']);
$finalOption = null;
foreach ($options as $o) { if ((int)$o['id'] === (int)$poll['final_option_id']) { $finalOption = $o; break; } }
$expired     = !$finalized && !empty($poll['deadline']) && (int)$poll['deadline'] < time();
$bestIds     = $stats['best_ids'];
$counts      = $stats['counts'];
?>
<div class="page-header">
    <div class="page-header-left">
        <a href="/polls" 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('mp_nav') ?>
        </a>
        <h1 class="page-title"><?= Helper::e($poll['title']) ?></h1>
    </div>
    <div class="page-header-actions" style="display:flex;gap:.4rem">
        <a href="/polls/<?= (int)$poll['id'] ?>/edit" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 013 3L12 15l-4 1 1-4z"/></svg>
            <?= t('edit') ?>
        </a>
        <form method="POST" action="/polls/<?= (int)$poll['id'] ?>/delete" style="display:inline" data-confirm="<?= Helper::e(t('mp_confirm_delete_poll')) ?>">
            <?= Helper::csrf() ?>
            <button type="submit" class="btn btn-danger btn-sm">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
                <?= t('delete') ?>
            </button>
        </form>
    </div>
</div>

<?php if (!empty($poll['description'])): ?>
<p style="margin-top:-.4rem;white-space:pre-wrap"><?= Helper::e($poll['description']) ?></p>
<?php endif; ?>

<!-- Share link -->
<div class="card" style="margin-bottom:1rem">
    <div class="card-body">
        <label class="form-label"><?= t('mp_share_link') ?></label>
        <div style="display:flex;gap:.5rem;flex-wrap:wrap">
            <input type="text" id="mp-share" class="form-input" readonly value="<?= Helper::e($shareUrl) ?>" style="flex:1;min-width:240px" data-select-on-focus>
            <button type="button" class="btn btn-secondary btn-sm" id="mp-copy"><?= t('mp_copy_link') ?></button>
            <a href="<?= Helper::e($shareUrl) ?>" target="_blank" rel="noopener" class="btn btn-ghost btn-sm"><?= t('mp_open_link') ?></a>
        </div>
        <small class="form-hint" style="display:block;margin-top:.4rem"><?= t('mp_share_hint') ?></small>
    </div>
</div>

<!-- Invite participants -->
<div class="card" style="margin-bottom:1rem">
    <div class="card-header"><h2 class="card-title"><?= t('mp_invite_title') ?></h2></div>
    <div class="card-body">
        <p class="text-muted" style="font-size:.9rem;margin-top:0"><?= t('mp_invite_hint') ?></p>
        <form method="POST" action="/polls/<?= (int)$poll['id'] ?>/invite" id="mp-invite-form">
            <?= Helper::csrf() ?>
            <div class="form-group">
                <label class="form-label" for="mp-inv-q"><?= t('mp_invite_users_label') ?></label>
                <div class="mp-inv-search">
                    <input type="text" id="mp-inv-q" class="form-input" autocomplete="off" placeholder="<?= t('mp_invite_search_ph') ?>">
                    <div id="mp-inv-results" class="mp-inv-results" style="display:none"></div>
                </div>
                <div id="mp-inv-chips" class="mp-inv-chips"></div>
            </div>
            <div class="form-group">
                <label class="form-label" for="mp-inv-emails"><?= t('mp_invite_emails_label') ?></label>
                <textarea id="mp-inv-emails" name="invite_emails" class="form-textarea" rows="2" placeholder="<?= t('mp_invite_emails_ph') ?>"></textarea>
            </div>
            <button type="submit" class="btn btn-primary btn-sm"><?= t('mp_invite_send') ?></button>
        </form>

        <?php if (!empty($invites)): ?>
        <div style="margin-top:1.1rem">
            <h3 style="font-size:.92rem;margin:0 0 .5rem;color:var(--text-muted,#6b7280)"><?= t('mp_invited_people') ?> (<?= count($invites) ?>)</h3>
            <div class="mp-invite-list">
                <?php foreach ($invites as $inv): ?>
                <div class="mp-invite-row">
                    <span class="mp-invite-who">
                        <?php if (!empty($inv['name'])): ?><strong><?= Helper::e($inv['name']) ?></strong> <?php endif; ?>
                        <span class="text-muted"><?= Helper::e($inv['email']) ?></span>
                    </span>
                    <?php if (!empty($inv['responded'])): ?>
                        <span class="badge badge-success"><?= t('mp_invite_responded') ?></span>
                    <?php else: ?>
                        <span class="badge badge-neutral"><?= t('mp_invite_pending') ?></span>
                    <?php endif; ?>
                    <form method="POST" action="/polls/<?= (int)$poll['id'] ?>/invites/<?= (int)$inv['id'] ?>/resend" style="display:inline">
                        <?= Helper::csrf() ?>
                        <button type="submit" class="btn btn-ghost btn-xs"><?= t('mp_invite_resend') ?></button>
                    </form>
                    <form method="POST" action="/polls/<?= (int)$poll['id'] ?>/invites/<?= (int)$inv['id'] ?>/delete" style="display:inline" data-confirm="<?= Helper::e(t('mp_invite_remove_confirm')) ?>">
                        <?= Helper::csrf() ?>
                        <button type="submit" class="btn btn-ghost btn-xs" title="<?= t('mp_invite_remove') ?>">×</button>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Status -->
<?php if ($finalized && $finalOption): ?>
<div class="alert alert-success" role="alert">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><path d="M22 4L12 14.01l-3-3"/></svg>
    <div>
        <strong><?= t('mp_finalized_to') ?>:</strong> <?= Helper::e(MeetingPollController::optionLabel($finalOption)) ?>
        <?php if (!empty($poll['location'])): ?> · <?= Helper::e($poll['location']) ?><?php endif; ?>
        <form method="POST" action="/polls/<?= (int)$poll['id'] ?>/reopen" style="display:inline;margin-left:.6rem">
            <?= Helper::csrf() ?>
            <button type="submit" class="btn btn-ghost btn-xs"><?= t('mp_reopen') ?></button>
        </form>
    </div>
</div>
<?php elseif ($expired): ?>
<div class="alert alert-error" role="alert" style="background:#f3f4f6;color:#374151;border-color:#e5e7eb">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
    <?= t('mp_deadline_passed', ['date' => MeetingPollController::fmtTs($poll['deadline'])]) ?>
</div>
<?php endif; ?>

<p class="text-muted" style="font-size:.85rem;margin-bottom:1rem">
    <?= t('mp_meta_responses', ['count' => (string)(int)$stats['total']]) ?>
    <?php if (!empty($poll['deadline']) && !$expired): ?> · <?= t('mp_meta_deadline', ['date' => MeetingPollController::fmtTs($poll['deadline'])]) ?><?php endif; ?>
    <?php if ((int)$poll['hide_results'] === 1): ?> · <?= t('mp_meta_hidden') ?><?php endif; ?>
</p>

<!-- Results grid -->
<div class="card">
    <div class="card-body">
        <?php if (empty($options)): ?>
            <p class="text-muted"><?= t('mp_no_options_yet') ?></p>
        <?php else: ?>
        <div class="mp-grid-wrap">
        <table class="mp-grid">
            <thead>
                <tr>
                    <th class="mp-name-col"><?= t('mp_participant') ?></th>
                    <?php foreach ($options as $o): $oid = (int)$o['id']; $isBest = in_array($oid, $bestIds, true); ?>
                    <th class="<?= $isBest ? 'mp-best' : '' ?>">
                        <div class="mp-opt-date"><?= Helper::e(MeetingPollController::optionDate($o)) ?></div>
                        <div class="mp-opt-time"><?= ($t = MeetingPollController::optionTime($o)) !== null ? Helper::e($t) : t('mp_all_day') ?></div>
                        <?php if ($finalized && $oid === (int)$poll['final_option_id']): ?><div class="mp-opt-final">✓ <?= t('mp_status_finalized') ?></div><?php endif; ?>
                    </th>
                    <?php endforeach; ?>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($responses)): ?>
                <tr><td colspan="<?= count($options) + 2 ?>" class="text-muted" style="padding:1.25rem;text-align:center"><?= t('mp_no_responses') ?></td></tr>
                <?php endif; ?>
                <?php foreach ($responses as $r): ?>
                <tr>
                    <td class="mp-name-col">
                        <strong><?= Helper::e($r['name']) ?></strong>
                        <?php if (!empty($r['comment'])): ?><div class="mp-comment">„<?= Helper::e($r['comment']) ?>"</div><?php endif; ?>
                    </td>
                    <?php foreach ($options as $o): $oid = (int)$o['id']; $v = $r['votes'][$oid] ?? 'no'; ?>
                    <td class="mp-cell mp-cell-<?= Helper::e($v) ?> <?= in_array($oid, $bestIds, true) ? 'mp-best' : '' ?>">
                        <?= $v === 'yes' ? '●' : ($v === 'maybe' ? '?' : '○') ?>
                    </td>
                    <?php endforeach; ?>
                    <td>
                        <form method="POST" action="/polls/<?= (int)$poll['id'] ?>/responses/<?= (int)$r['id'] ?>/delete" data-confirm="<?= Helper::e(t('mp_confirm_delete_response')) ?>">
                            <?= Helper::csrf() ?>
                            <button type="submit" class="btn btn-ghost btn-xs" title="<?= t('mp_delete_response') ?>">×</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr class="mp-totals">
                    <td class="mp-name-col"><?= t('mp_total') ?></td>
                    <?php foreach ($options as $o): $oid = (int)$o['id']; $c = $counts[$oid]; ?>
                    <td class="<?= in_array($oid, $bestIds, true) ? 'mp-best' : '' ?>">
                        <span class="mp-count-yes">● <?= (int)$c['yes'] ?></span>
                        <?php if ((int)$poll['allow_maybe'] === 1): ?><span class="mp-count-maybe">? <?= (int)$c['maybe'] ?></span><?php endif; ?>
                    </td>
                    <?php endforeach; ?>
                    <td></td>
                </tr>
            </tfoot>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Finalize -->
<?php if (!$finalized && !empty($options)): ?>
<div class="card" style="margin-top:1rem">
    <div class="card-header"><h2 class="card-title"><?= t('mp_finalize_title') ?></h2></div>
    <div class="card-body">
        <p class="text-muted" style="font-size:.9rem;margin-top:0"><?= t('mp_finalize_hint') ?></p>
        <form method="POST" action="/polls/<?= (int)$poll['id'] ?>/finalize" style="display:flex;gap:.6rem;align-items:center;flex-wrap:wrap">
            <?= Helper::csrf() ?>
            <select name="option_id" class="form-select" required>
                <option value=""><?= t('mp_finalize_choose') ?></option>
                <?php foreach ($options as $o): $oid = (int)$o['id']; ?>
                <option value="<?= $oid ?>"><?= Helper::e(MeetingPollController::optionLabel($o)) ?> — ✓ <?= (int)$counts[$oid]['yes'] ?></option>
                <?php endforeach; ?>
            </select>
            <label style="display:flex;align-items:center;gap:.4rem;cursor:pointer;font-size:.9rem">
                <input type="hidden" name="notify" value="0">
                <input type="checkbox" name="notify" value="1" checked>
                <span><?= t('mp_finalize_notify') ?></span>
            </label>
            <button type="submit" class="btn btn-primary btn-sm"><?= t('mp_finalize_submit') ?></button>
        </form>
    </div>
</div>
<?php endif; ?>

<style>
.mp-grid-wrap{overflow-x:auto;border:1px solid var(--border-color);border-radius:var(--border-radius)}
.mp-grid{border-collapse:collapse;width:100%;font-size:.9rem}
.mp-grid th,.mp-grid td{padding:.6rem .75rem;text-align:center;vertical-align:middle;border-bottom:1px solid var(--border-color);border-right:1px solid var(--border-color)}
.mp-grid th:last-child,.mp-grid td:last-child{border-right:0}
.mp-grid tfoot td{border-bottom:0}
.mp-grid thead th{background:var(--bg-table-head);font-weight:600;color:var(--text-secondary);font-size:.78rem;text-transform:uppercase;letter-spacing:.03em;position:relative}
.mp-grid tbody tr:hover td{background:var(--bg-hover)}
.mp-grid .mp-name-col{text-align:left;min-width:150px;background:var(--bg-table-head)}
.mp-grid tbody tr:hover .mp-name-col{background:var(--bg-hover)}
.mp-grid .mp-opt-date{font-size:.83rem;font-weight:700;color:var(--text-primary);text-transform:none;letter-spacing:0}
.mp-grid .mp-opt-time{font-size:.72rem;color:var(--text-muted);font-weight:400;margin-top:1px;text-transform:none;letter-spacing:0}
.mp-grid .mp-opt-final{display:inline-block;margin-top:5px;font-size:.6rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#fff;background:linear-gradient(135deg,#14b8a6,#0ea5e9);padding:2px 7px;border-radius:999px}
.mp-grid .mp-comment{font-size:.72rem;color:var(--text-muted);font-weight:400;margin-top:3px;font-style:italic}
.mp-grid .mp-cell{font-size:1.1rem;font-weight:700;line-height:1}
.mp-grid .mp-cell-yes{color:#16a34a}
.mp-grid .mp-cell-maybe{color:#d97706}
.mp-grid .mp-cell-no{color:#cbd5e1;font-weight:500}
.mp-grid thead th.mp-best{
    background:linear-gradient(180deg,rgba(20,184,166,.10) 0%,rgba(20,184,166,.20) 100%) !important;
    color:#0f766e;
}
.mp-grid thead th.mp-best .mp-opt-date{color:#0f766e}
.mp-grid thead th.mp-best::after{
    content:'★';position:absolute;top:5px;right:8px;
    font-size:.7rem;color:#14b8a6;
}
.mp-grid tbody td.mp-best{background:linear-gradient(180deg,rgba(20,184,166,.04) 0%,rgba(20,184,166,.10) 100%)}
.mp-grid tbody tr:hover td.mp-best{background:linear-gradient(180deg,rgba(20,184,166,.10) 0%,rgba(20,184,166,.16) 100%)}
.mp-grid tfoot td.mp-best{background:linear-gradient(180deg,rgba(20,184,166,.10) 0%,rgba(20,184,166,.18) 100%);color:#0f766e}
.mp-grid tfoot td{background:var(--bg-table-head);font-weight:600;color:var(--text-secondary)}
.mp-grid .mp-count-yes{color:#16a34a;font-weight:800}
.mp-grid .mp-count-maybe{color:#d97706;margin-left:.5rem;font-weight:700;font-size:.85rem}
[data-theme-mode="dark"] .mp-grid .mp-cell-yes{color:#34d399}
[data-theme-mode="dark"] .mp-grid .mp-cell-maybe{color:#fbbf24}
[data-theme-mode="dark"] .mp-grid .mp-cell-no{color:#475569}
[data-theme-mode="dark"] .mp-grid thead th.mp-best,
[data-theme-mode="dark"] .mp-grid tfoot td.mp-best{color:#5eead4}
[data-theme-mode="dark"] .mp-grid thead th.mp-best .mp-opt-date{color:#5eead4}
[data-theme-mode="dark"] .mp-grid .mp-count-yes{color:#34d399}
[data-theme-mode="dark"] .mp-grid .mp-count-maybe{color:#fbbf24}
.mp-inv-search{position:relative;max-width:420px}
.mp-inv-results{position:absolute;left:0;right:0;top:calc(100% + 3px);z-index:20;background:var(--bg-card);border:1px solid var(--border-color);border-radius:var(--border-radius-sm);box-shadow:var(--shadow-lg);max-height:220px;overflow:auto}
.mp-inv-item{padding:.45rem .65rem;cursor:pointer;font-size:.88rem}
.mp-inv-item:hover{background:var(--bg-hover)}
.mp-inv-chips{display:flex;flex-wrap:wrap;gap:.4rem;margin-top:.5rem}
.mp-chip{display:inline-flex;align-items:center;gap:.35rem;background:var(--color-primary);color:#fff;border-radius:999px;padding:.18rem .25rem .18rem .65rem;font-size:.82rem;font-weight:500}
.mp-chip-x{border:0;background:transparent;cursor:pointer;color:#fff;font-size:1rem;line-height:1;padding:0 .25rem;border-radius:999px;opacity:.85}
.mp-chip-x:hover{opacity:1;background:rgba(255,255,255,.2)}
.mp-invite-list{display:flex;flex-direction:column}
.mp-invite-row{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;padding:.4rem 0;border-bottom:1px solid var(--border-color)}
.mp-invite-row:last-child{border-bottom:0}
.mp-invite-who{flex:1;min-width:160px;font-size:.88rem}
</style>
<script nonce="<?= csp_nonce() ?>">
(function () {
    var btn = document.getElementById('mp-copy');
    var inp = document.getElementById('mp-share');
    if (!btn || !inp) return;
    btn.addEventListener('click', function () {
        inp.select();
        var done = function () { var o = btn.textContent; btn.textContent = '<?= t('mp_copied') ?>'; setTimeout(function(){ btn.textContent = o; }, 1500); };
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(inp.value).then(done, function(){ try { document.execCommand('copy'); done(); } catch(e){} });
        } else { try { document.execCommand('copy'); done(); } catch(e){} }
    });
})();
</script>
<script nonce="<?= csp_nonce() ?>">
(function () {
    var q     = document.getElementById('mp-inv-q');
    var res   = document.getElementById('mp-inv-results');
    var chips = document.getElementById('mp-inv-chips');
    if (!q || !res || !chips) return;
    var csrf  = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';
    var picked = {}; // user id -> true
    var timer  = null;

    chips.addEventListener('click', function (ev) {
        var x = ev.target.closest('.mp-chip-x'); if (!x) return;
        var s = x.closest('.mp-chip'); if (!s) return;
        delete picked[s.getAttribute('data-id')]; s.remove();
    });
    function addChip(u) {
        if (picked[u.id]) return;
        picked[u.id] = true;
        var s = document.createElement('span'); s.className = 'mp-chip'; s.setAttribute('data-id', u.id);
        var h = document.createElement('input'); h.type = 'hidden'; h.name = 'invite_user_id[]'; h.value = u.id; s.appendChild(h);
        var t = document.createElement('span'); t.textContent = u.username + (u.email ? ' <' + u.email + '>' : ''); s.appendChild(t);
        var x = document.createElement('button'); x.type = 'button'; x.className = 'mp-chip-x'; x.setAttribute('aria-label', '×'); x.textContent = '×'; s.appendChild(x);
        chips.appendChild(s);
    }
    function renderResults(list) {
        res.innerHTML = '';
        (list || []).forEach(function (u) {
            if (picked[u.id]) return;
            var d = document.createElement('div'); d.className = 'mp-inv-item';
            d.textContent = u.username + (u.email ? ' — ' + u.email : '');
            d.addEventListener('mousedown', function (ev) { ev.preventDefault(); addChip(u); res.style.display = 'none'; q.value = ''; });
            res.appendChild(d);
        });
        res.style.display = res.children.length ? 'block' : 'none';
    }
    function doSearch() {
        var term = q.value.trim();
        if (term.length < 2) { res.style.display = 'none'; return; }
        var body = new URLSearchParams(); body.set('q', term); body.set('csrf_token', csrf);
        fetch('/polls/user-search', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() })
            .then(function (r) { return r.ok ? r.json() : { users: [] }; })
            .then(function (j) { renderResults(j.users); })
            .catch(function () { res.style.display = 'none'; });
    }
    q.addEventListener('input', function () { clearTimeout(timer); timer = setTimeout(doSearch, 220); });
    q.addEventListener('focus', function () { if (res.children.length) res.style.display = 'block'; });
    q.addEventListener('blur', function () { setTimeout(function () { res.style.display = 'none'; }, 150); });
})();
</script>
