
function isHiddenPollWalk(walk) {
  const status = String(walk?.status || '').toLowerCase().trim();
  const title = String(walk?.title || '').toLowerCase().trim();
  const token = String(walk?.checkin_token || '').toLowerCase().trim();
  const id = Number(walk?.id || 0);
  const date = String(walk?.walk_date || '').slice(0, 10);

  const now = new Date();
  const todayIso = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;

  const legacySeed = id === 1 || id === 2
    || title.includes('sunrise waterfront')
    || title.includes('community park')
    || token.startsWith('pyrk-walk-sunrise-')
    || token.startsWith('pyrk-walk-park-');

  return ['deleted','archived','removed','remove','trash','trashed','cancelled','canceled','inactive','hidden'].includes(status)
    || (date && date < todayIso)
    || legacySeed
    || !!walk?.deleted_at
    || !!walk?.removed_at
    || !!walk?.archived_at
    || !!walk?.cancelled_at
    || !!walk?.canceled_at
    || !!walk?.deleted_by
    || !!walk?.removed_by
    || !!walk?.archived_by
    || Number(walk?.is_deleted || walk?.deleted || walk?.is_archived || walk?.archived || walk?.is_removed || 0) === 1;
}

function visiblePollWalks(walks) {
  return (walks || []).filter(w => !isHiddenPollWalk(w));
}


let pollState = {polls: [], walks: [], members: [], groups: []};
let selectedGroupIds = new Set();
let selectedMemberIds = new Set();

function isDeletedWalk(walk){
  const status=String(walk?.status||'').toLowerCase().trim();
  return ['deleted','archived','removed','remove','trash','trashed','cancelled','canceled','inactive'].includes(status)
    || !!walk?.deleted_at
    || !!walk?.removed_at
    || !!walk?.archived_at
    || !!walk?.cancelled_at
    || !!walk?.canceled_at
    || !!walk?.deleted_by
    || !!walk?.removed_by
    || !!walk?.archived_by
    || Number(walk?.is_deleted||walk?.deleted||walk?.is_archived||walk?.archived||walk?.is_removed||0)===1;
}
function visibleWalks(walks){return (walks||[]).filter(w=>!isDeletedWalk(w));}

function pollTypeLabel(type){return ({general:'General',timing:'Timing',date:'Date',location:'Location',route:'Route / routing',other:'Other'})[type||'general']||'General';}
function statusPill(status){const s=String(status||'draft'); const cls=s==='active'?'pill-green':(s==='closed'?'pill-red':'pill-muted'); return `<span class="pill ${cls}">${Pyrk.esc(s)}</span>`;}
function ddMmYyyy(value){if(!value)return ''; const s=String(value); const m=s.match(/^(\d{4})-(\d{2})-(\d{2})/); if(!m)return s.replace('T',' ').slice(0,10); return `${m[3]}/${m[2]}/${m[1]}`;}
function normalizeDateInput(el){let value=String(el.value||'').replace(/[^\d]/g,'').slice(0,8); if(value.length>=5)value=`${value.slice(0,2)}/${value.slice(2,4)}/${value.slice(4)}`; else if(value.length>=3)value=`${value.slice(0,2)}/${value.slice(2)}`; el.value=value;}
function validateDateInput(value,label){const raw=String(value||'').trim(); if(!raw)return true; const m=raw.match(/^(\d{2})\/(\d{2})\/(\d{4})$/); if(!m){alert(`${label} must be dd/mm/yyyy.`); return false;} const d=Number(m[1]),mo=Number(m[2]),y=Number(m[3]); const date=new Date(y,mo-1,d); if(date.getFullYear()!==y||date.getMonth()!==mo-1||date.getDate()!==d){alert(`${label} is not a valid date.`); return false;} return true;}
function memberPollLink(id){const base=window.location.origin+window.location.pathname.replace(/\/admin\/polls\.php.*$/,'/polls.php'); return `${base}?id=${id}`;}
function fillWalkOptions(){
  const select=document.getElementById('pollWalkId');
  if(!select)return;
  const current=select.value;
  pollState.walks=visibleWalks(pollState.walks||[]);
  select.innerHTML='<option value="">No walk</option>'+pollState.walks.map(w=>`<option value="${w.id}">${Pyrk.esc(w.title)} · ${Pyrk.esc(w.walk_date||'')}</option>`).join('');
  if(current&&pollState.walks.some(w=>Number(w.id)===Number(current))){
    select.value=current;
  }else if(current){
    select.value='';
  }
}
function filteredPolls(){const q=(document.getElementById('pollSearch')?.value||'').toLowerCase().trim(); const status=document.getElementById('pollStatusFilter')?.value||''; return (pollState.polls||[]).filter(p=>{const hay=`${p.title||''} ${p.description||''} ${p.poll_type||''}`.toLowerCase(); return (!q||hay.includes(q))&&(!status||p.status===status);});}
function renderStats(){const polls=pollState.polls||[]; const totalResponses=polls.reduce((sum,p)=>sum+Number(p.response_count||0),0); document.getElementById('pollTotal').textContent=polls.length; document.getElementById('pollActive').textContent=polls.filter(p=>p.status==='active').length; document.getElementById('pollResponses').textContent=totalResponses; document.getElementById('pollClosed').textContent=polls.filter(p=>p.status==='closed').length;}
function resultBars(poll){const results=poll.results||[]; const totalVotes=results.reduce((sum,r)=>sum+Number(r.votes||0),0); const total=Math.max(1,totalVotes); return `<div class="poll-results-bars">${results.map(r=>{const votes=Number(r.votes||0); const pct=Math.round((votes/total)*100); return `<div class="poll-result-row"><div><strong>${Pyrk.esc(r.option_text)}</strong><span>${votes} votes</span></div><div class="poll-bar"><i style="width:${pct}%"></i></div></div>`;}).join('')}${totalVotes===0?'<p class="muted small">No votes yet.</p>':''}</div>`;}
function commentList(poll){const comments=poll.comments||[]; if(!comments.length)return '<p class="muted small">No comments yet.</p>'; return `<div class="poll-comments">${comments.slice(0,5).map(c=>`<p><strong>${Pyrk.esc(c.member_name||'Member')}</strong><span>${Pyrk.esc(c.comment)}</span></p>`).join('')}</div>`;}
function audienceLabel(p){if(p.target_scope==='selected_members')return `${Number((p.target_member_ids||[]).length)} selected members`; if(p.target_scope==='selected_groups')return `${Number((p.target_group_ids||[]).length)} selected teams/groups`; if(p.target_scope==='walk_registrants')return `Walk registrants · ${Pyrk.esc(p.walk_title||'Selected walk')}`; return 'All members';}
function emailStatusLine(p){const b=p.last_email_batch; if(!b)return '<span>Email not sent</span>'; return `<span>Email: ${Number(b.sent_count||0)} sent · ${Number(b.failed_count||0)} failed</span>`;}
function renderPolls(){
  renderStats();
  const box=document.getElementById('pollCards');
  if(!box)return;
  const rows=filteredPolls();
  box.innerHTML=rows.map(p=>`<article class="poll-admin-card">
    <div class="poll-card-head"><div><span class="poll-type-chip">${Pyrk.esc(pollTypeLabel(p.poll_type))}</span><h3>${Pyrk.esc(p.title)}</h3></div>${statusPill(p.status)}</div>
    <p>${Pyrk.esc(p.description||'No description')}</p>
    <div class="poll-meta-strip"><span>${audienceLabel(p)}</span><span>${Number(p.response_count||0)} responses</span><span>${p.allow_multiple==1?'Multiple choice':'Single choice'}</span><span>${p.is_anonymous==1?'Anonymous':'Named'}</span>${emailStatusLine(p)}</div>
    ${resultBars(p)}${commentList(p)}
    <div class="poll-actions">
      <button class="btn btn-light btn-small" type="button" onclick="editPoll(${p.id})">Edit</button>
      <button class="btn btn-light btn-small" type="button" onclick="copyPollLink(${p.id})">Copy link</button>
      <button class="btn btn-small" type="button" onclick="openPollEmailModal(${p.id})">${p.last_email_batch?'Resend email':'Send email'}</button>
      ${p.status!=='active'?`<button class="btn btn-small" type="button" onclick="setPollStatus(${p.id}, 'active')">Activate</button>`:''}
      ${p.status!=='closed'?`<button class="btn btn-danger btn-small" type="button" onclick="setPollStatus(${p.id}, 'closed')">Close</button>`:''}
    </div>
  </article>`).join('')||'<div class="empty-state"><strong>No polls found</strong><span>Create your first member poll.</span></div>';
}
function openPollModal(){const modal=document.getElementById('pollModal'); if(!modal)return; modal.hidden=false; modal.setAttribute('aria-hidden','false'); setTimeout(()=>document.getElementById('pollTitle')?.focus(),80);}
function closePollModal(){const modal=document.getElementById('pollModal'); if(!modal)return; modal.hidden=true; modal.setAttribute('aria-hidden','true');}
function resetForm(){document.getElementById('pollForm')?.reset(); document.getElementById('pollId').value=''; document.getElementById('pollFormTitle').textContent='Create poll'; document.getElementById('pollStatus').value='draft'; document.getElementById('pollType').value='general'; document.getElementById('pollTargetScope').value='all_members'; document.getElementById('pollAnonymous').checked=true; selectedMemberIds=new Set((pollState.members||[]).map(m=>Number(m.id))); selectedGroupIds=new Set((pollState.groups||[]).filter(g=>String(g.status||'active')==='active').map(g=>Number(g.id))); document.getElementById('pollLinkBox').hidden=true; syncTargetScope(); renderMemberPicker(); renderGroupPicker(); openPollModal();}
function syncTargetScope(){const scope=document.getElementById('pollTargetScope')?.value||'all_members'; const walk=document.getElementById('pollWalkId'); const memberPanel=document.getElementById('pollMemberPickerPanel'); const groupPanel=document.getElementById('pollGroupPickerPanel'); if(walk)walk.disabled=scope!=='walk_registrants'; if(memberPanel)memberPanel.hidden=scope==='walk_registrants'||scope==='selected_groups'; if(groupPanel)groupPanel.hidden=scope!=='selected_groups';}
function memberMatchesSearch(member,q){const hay=`${member.full_name||''} ${member.email||''} ${member.mobile||''}`.toLowerCase(); return !q||hay.includes(q);}
function renderMemberPicker(){const list=document.getElementById('pollMemberList'); const count=document.getElementById('pollSelectedMemberCount'); if(!list)return; const q=(document.getElementById('pollMemberSearch')?.value||'').toLowerCase().trim(); const members=(pollState.members||[]).filter(m=>memberMatchesSearch(m,q)); if(count)count.textContent=`${selectedMemberIds.size} selected`; list.innerHTML=members.map(m=>{const checked=selectedMemberIds.has(Number(m.id)); return `<label class="poll-member-row ${checked?'is-selected':''}"><input type="checkbox" value="${Number(m.id)}" ${checked?'checked':''}><span class="member-avatar">${Pyrk.esc(String(m.full_name||'?').slice(0,1).toUpperCase())}</span><span><strong>${Pyrk.esc(m.full_name||'Member')}</strong><small>${Pyrk.esc(m.email||'')}${m.mobile?' · '+Pyrk.esc(m.mobile):''}</small></span></label>`;}).join('')||'<p class="muted">No members match your search.</p>';}

function groupMatchesSearch(group,q){
  const hay=`${group.group_name||''} ${group.description||''}`.toLowerCase();
  return !q || hay.includes(q);
}
function renderGroupPicker(){
  const list=document.getElementById('pollGroupList');
  const count=document.getElementById('pollSelectedGroupCount');
  if(!list)return;
  const q=(document.getElementById('pollGroupSearch')?.value||'').toLowerCase().trim();
  const groups=(pollState.groups||[]).filter(g=>groupMatchesSearch(g,q));
  if(count)count.textContent=`${selectedGroupIds.size} selected`;
  list.innerHTML=groups.map(g=>{
    const id=Number(g.id);
    const checked=selectedGroupIds.has(id);
    const disabled=String(g.status||'active')!=='active';
    return `<label class="poll-member-row poll-group-row ${checked?'is-selected':''} ${disabled?'is-disabled':''}">
      <input type="checkbox" value="${id}" ${checked?'checked':''} ${disabled?'disabled':''}>
      <span class="member-avatar">👥</span>
      <span><strong>${Pyrk.esc(g.group_name||'Team')}</strong><small>${Number(g.member_count||0)} members · ${Pyrk.esc(g.status||'active')}</small></span>
    </label>`;
  }).join('')||'<p class="muted">No teams/groups match your search.</p>';
}

window.editPoll=function editPoll(id){const p=(pollState.polls||[]).find(x=>Number(x.id)===Number(id)); if(!p)return; document.getElementById('pollFormTitle').textContent='Edit poll'; document.getElementById('pollId').value=p.id; document.getElementById('pollTitle').value=p.title||''; document.getElementById('pollDescription').value=p.description||''; document.getElementById('pollType').value=p.poll_type||'general'; document.getElementById('pollStatus').value=p.status||'draft'; document.getElementById('pollTargetScope').value=p.target_scope||'all_members'; document.getElementById('pollWalkId').value=p.walk_id||''; document.getElementById('pollStartsAt').value=ddMmYyyy(p.starts_at); document.getElementById('pollEndsAt').value=ddMmYyyy(p.ends_at); document.getElementById('pollOptionsText').value=(p.options||[]).map(o=>o.option_text).join('\n'); document.getElementById('pollAllowMultiple').checked=Number(p.allow_multiple||0)===1; document.getElementById('pollAnonymous').checked=Number(p.is_anonymous||0)===1; selectedMemberIds=p.target_scope==='selected_members'?new Set((p.target_member_ids||[]).map(Number)):new Set((pollState.members||[]).map(m=>Number(m.id))); selectedGroupIds=p.target_scope==='selected_groups'?new Set((p.target_group_ids||[]).map(Number)):new Set((pollState.groups||[]).filter(g=>String(g.status||'active')==='active').map(g=>Number(g.id))); const linkBox=document.getElementById('pollLinkBox'); const linkInput=document.getElementById('pollShareLink'); linkBox.hidden=false; linkInput.value=memberPollLink(p.id); syncTargetScope(); renderMemberPicker(); renderGroupPicker(); openPollModal();};
window.copyPollLink=async function copyPollLink(id){const link=memberPollLink(id); try{await navigator.clipboard.writeText(link); alert('Poll link copied.');}catch{prompt('Copy poll link:',link);}};
window.setPollStatus=async function setPollStatus(id,status){const res=await Pyrk.post('polls.php',{action:'set_status',id,status}); alert(res.message||(res.ok?'Updated.':'Failed.')); if(res.ok)await loadPolls();};
async function loadPolls(){const res=await Pyrk.get('polls.php',{action:'admin'}); if(!res.ok){document.getElementById('pollCards').innerHTML=`<p class="notice bad">${Pyrk.esc(res.message)}</p>`; return;} pollState=res.data||{polls:[],walks:[],members:[]}; pollState.walks=visibleWalks(pollState.walks||[]); selectedMemberIds=new Set((pollState.members||[]).map(m=>Number(m.id))); selectedGroupIds=new Set((pollState.groups||[]).filter(g=>String(g.status||'active')==='active').map(g=>Number(g.id))); fillWalkOptions(); renderMemberPicker(); renderGroupPicker(); renderPolls();}

/* Professional custom dd/mm/yyyy calendar. No native/browser date picker. */
let activePollDateInputId = null;
const pollCalState = {
  year: new Date().getFullYear(),
  month: new Date().getMonth()
};

function parseDdMmYyyyToDate(value) {
  const raw = String(value || '').trim();
  const m = raw.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if (!m) return null;
  const day = Number(m[1]);
  const month = Number(m[2]);
  const year = Number(m[3]);
  const d = new Date(year, month - 1, day);
  if (d.getFullYear() !== year || d.getMonth() !== month - 1 || d.getDate() !== day) return null;
  return d;
}

function formatPollCalendarDate(date) {
  return `${String(date.getDate()).padStart(2, '0')}/${String(date.getMonth() + 1).padStart(2, '0')}/${date.getFullYear()}`;
}

function selectedPollCalendarDate() {
  const el = activePollDateInputId ? document.getElementById(activePollDateInputId) : null;
  return parseDdMmYyyyToDate(el?.value || '');
}

function renderPollCalendar() {
  const grid = document.getElementById('pollCalGrid');
  const label = document.getElementById('pollCalCurrent');
  if (!grid || !label) return;

  const monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  label.textContent = `${monthNames[pollCalState.month]} ${pollCalState.year}`;

  const selected = selectedPollCalendarDate();
  const selectedIso = selected ? `${selected.getFullYear()}-${selected.getMonth()}-${selected.getDate()}` : '';
  const today = new Date();
  const todayIso = `${today.getFullYear()}-${today.getMonth()}-${today.getDate()}`;

  const first = new Date(pollCalState.year, pollCalState.month, 1);
  const daysInMonth = new Date(pollCalState.year, pollCalState.month + 1, 0).getDate();

  let html = '';
  for (let i = 0; i < first.getDay(); i++) {
    html += '<span class="poll-date-empty"></span>';
  }

  for (let day = 1; day <= daysInMonth; day++) {
    const date = new Date(pollCalState.year, pollCalState.month, day);
    const iso = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
    const classes = [
      'poll-date-day',
      iso === selectedIso ? 'is-selected' : '',
      iso === todayIso ? 'is-today' : ''
    ].filter(Boolean).join(' ');
    html += `<button type="button" class="${classes}" data-poll-date="${formatPollCalendarDate(date)}">${day}</button>`;
  }

  grid.innerHTML = html;
}

function openPollCalendar(inputId) {
  activePollDateInputId = inputId;
  const input = document.getElementById(inputId);
  const existing = parseDdMmYyyyToDate(input?.value || '');
  const base = existing || new Date();

  pollCalState.year = base.getFullYear();
  pollCalState.month = base.getMonth();

  const title = document.getElementById('pollDateTitle');
  if (title) title.textContent = inputId === 'pollEndsAt' ? 'Select end date' : 'Select start date';

  renderPollCalendar();

  const modal = document.getElementById('pollDateModal');
  if (modal) {
    modal.hidden = false;
    modal.setAttribute('aria-hidden', 'false');
  }
}

function closePollCalendar() {
  const modal = document.getElementById('pollDateModal');
  if (modal) {
    modal.hidden = true;
    modal.setAttribute('aria-hidden', 'true');
  }
}

function movePollCalendarMonth(delta) {
  pollCalState.month += delta;
  while (pollCalState.month < 0) {
    pollCalState.month += 12;
    pollCalState.year -= 1;
  }
  while (pollCalState.month > 11) {
    pollCalState.month -= 12;
    pollCalState.year += 1;
  }
  renderPollCalendar();
}

function movePollCalendarYear(delta) {
  pollCalState.year += delta;
  renderPollCalendar();
}

function setActivePollDate(value) {
  const input = activePollDateInputId ? document.getElementById(activePollDateInputId) : null;
  if (input) {
    input.value = value;
    input.dispatchEvent(new Event('input', {bubbles: true}));
  }
}

function clearActivePollDate() {
  const input = activePollDateInputId ? document.getElementById(activePollDateInputId) : null;
  if (input) input.value = '';
  closePollCalendar();
}

function setTodayActivePollDate() {
  setActivePollDate(formatPollCalendarDate(new Date()));
  closePollCalendar();
}


document.getElementById('pollForm')?.addEventListener('submit',async e=>{e.preventDefault(); if(!validateDateInput(document.getElementById('pollStartsAt')?.value,'Starts at'))return; if(!validateDateInput(document.getElementById('pollEndsAt')?.value,'Ends at'))return; const fd=new FormData(e.currentTarget); fd.append('action','save'); const scope=document.getElementById('pollTargetScope')?.value||'all_members'; if(scope==='selected_members'){fd.set('member_ids',JSON.stringify([...selectedMemberIds]));} else if(scope==='selected_groups'){fd.set('group_ids',JSON.stringify([...selectedGroupIds]));} else if(scope==='all_members'){fd.set('member_ids',JSON.stringify((pollState.members||[]).map(m=>Number(m.id))));} const res=await Pyrk.postForm('polls.php',fd); Pyrk.toast('pollMsg',res); if(res.ok){await loadPolls(); const newId=res.data?.poll_id; if(newId)editPoll(newId);}});
document.getElementById('newPollBtn')?.addEventListener('click',()=>resetForm()); document.getElementById('closePollModalBtn')?.addEventListener('click',closePollModal); document.getElementById('pollModal')?.addEventListener('click',e=>{if(e.target?.id==='pollModal')closePollModal();}); document.addEventListener('keydown',e=>{if(e.key==='Escape')closePollModal();}); document.getElementById('resetPollForm')?.addEventListener('click',resetForm); document.getElementById('pollSearch')?.addEventListener('input',renderPolls); document.getElementById('pollStatusFilter')?.addEventListener('change',renderPolls); document.getElementById('pollTargetScope')?.addEventListener('change',syncTargetScope); document.getElementById('pollMemberSearch')?.addEventListener('input',renderMemberPicker);

document.getElementById('pollGroupSearch')?.addEventListener('input',renderGroupPicker);
document.getElementById('pollSelectAllGroups')?.addEventListener('click',()=>{selectedGroupIds=new Set((pollState.groups||[]).filter(g=>String(g.status||'active')==='active').map(g=>Number(g.id))); renderGroupPicker();});
document.getElementById('pollClearGroups')?.addEventListener('click',()=>{selectedGroupIds=new Set(); renderGroupPicker();});
document.getElementById('pollGroupList')?.addEventListener('change',e=>{const input=e.target.closest('input[type="checkbox"]'); if(!input)return; const id=Number(input.value); if(input.checked)selectedGroupIds.add(id); else selectedGroupIds.delete(id); renderGroupPicker();});
 document.getElementById('pollSelectAllMembers')?.addEventListener('click',()=>{selectedMemberIds=new Set((pollState.members||[]).map(m=>Number(m.id))); renderMemberPicker();}); document.getElementById('pollClearMembers')?.addEventListener('click',()=>{selectedMemberIds=new Set(); renderMemberPicker();}); document.getElementById('pollMemberList')?.addEventListener('change',e=>{const input=e.target.closest('input[type="checkbox"]'); if(!input)return; const id=Number(input.value); if(input.checked)selectedMemberIds.add(id); else selectedMemberIds.delete(id); renderMemberPicker();}); ['pollStartsAt','pollEndsAt'].forEach(id=>document.getElementById(id)?.addEventListener('input',e=>normalizeDateInput(e.target))); document.getElementById('copyPollLinkBtn')?.addEventListener('click',()=>{const link=document.getElementById('pollShareLink')?.value||''; if(link)navigator.clipboard?.writeText(link).then(()=>alert('Poll link copied.'));});

document.querySelectorAll('.poll-date-trigger').forEach(btn => {
  btn.addEventListener('click', () => openPollCalendar(btn.dataset.dateTarget));
});
document.getElementById('pollDateCloseBtn')?.addEventListener('click', closePollCalendar);
document.getElementById('pollCalDoneBtn')?.addEventListener('click', closePollCalendar);
document.getElementById('pollCalClearBtn')?.addEventListener('click', clearActivePollDate);
document.getElementById('pollCalTodayBtn')?.addEventListener('click', setTodayActivePollDate);
document.getElementById('pollCalPrevMonth')?.addEventListener('click', () => movePollCalendarMonth(-1));
document.getElementById('pollCalNextMonth')?.addEventListener('click', () => movePollCalendarMonth(1));
document.getElementById('pollCalPrevYear')?.addEventListener('click', () => movePollCalendarYear(-1));
document.getElementById('pollCalNextYear')?.addEventListener('click', () => movePollCalendarYear(1));
document.getElementById('pollCalGrid')?.addEventListener('click', e => {
  const day = e.target.closest('[data-poll-date]');
  if (!day) return;
  setActivePollDate(day.dataset.pollDate);
  closePollCalendar();
});
document.getElementById('pollDateModal')?.addEventListener('click', e => {
  if (e.target && e.target.id === 'pollDateModal') closePollCalendar();
});

loadPolls();


// Hard guard: keep New poll opening even if an optional picker fails.
(function(){
  const btn=document.getElementById('newPollBtn');
  if(!btn || btn.dataset.pollOpenGuard==='1') return;
  btn.dataset.pollOpenGuard='1';
  btn.addEventListener('click',()=>{
    setTimeout(()=>{
      const modal=document.getElementById('pollModal');
      if(modal && modal.hidden){
        try{
          const form=document.getElementById('pollForm');
          if(form) form.reset();
          const id=document.getElementById('pollId'); if(id) id.value='';
          const title=document.getElementById('pollFormTitle'); if(title) title.textContent='Create poll';
          const status=document.getElementById('pollStatus'); if(status) status.value='draft';
          const type=document.getElementById('pollType'); if(type) type.value='general';
          const scope=document.getElementById('pollTargetScope'); if(scope) scope.value='all_members';
          const anon=document.getElementById('pollAnonymous'); if(anon) anon.checked=true;
          if(typeof syncTargetScope==='function') syncTargetScope();
          if(typeof renderMemberPicker==='function') renderMemberPicker();
          if(typeof renderGroupPicker==='function') renderGroupPicker();
        }catch(e){ console.error('Poll open guard:', e); }
        modal.hidden=false;
        modal.setAttribute('aria-hidden','false');
      }
    },0);
  }, true);
})();
