function pollTypeLabel(type) {
  return ({general:'General', timing:'Timing', date:'Date', location:'Location', route:'Route / routing', other:'Other'})[type || 'general'] || 'General';
}

function targetText(poll) {
  return poll.target_scope === 'walk_registrants' ? `For registered members · ${poll.walk_title || 'walk'}` : 'For all members';
}

function optionInput(poll, option) {
  const type = Number(poll.allow_multiple || 0) === 1 ? 'checkbox' : 'radio';
  const name = `poll_option_${poll.id}`;
  return `<label class="client-poll-option">
    <input type="${type}" name="${name}" value="${Number(option.id)}">
    <span>${Pyrk.esc(option.option_text)}</span>
  </label>`;
}

function responseSummary(poll) {
  const response = poll.my_response;
  if (!response) return '';
  const selected = new Set((response.option_ids || []).map(Number));
  const labels = (poll.options || []).filter(o => selected.has(Number(o.id))).map(o => o.option_text);
  return `<div class="poll-submitted-box">
    <strong>Submitted</strong>
    <span>${Pyrk.esc(labels.join(', ') || 'Response saved')}</span>
    ${response.comment ? `<em>${Pyrk.esc(response.comment)}</em>` : ''}
  </div>`;
}

function renderPolls(polls) {
  const box = document.getElementById('clientPolls');
  if (!box) return;

  const selectedId = Number(window.PYRK_SELECTED_POLL_ID || 0);
  const sorted = [...(polls || [])].sort((a,b) => selectedId && Number(a.id) === selectedId ? -1 : 0);

  box.innerHTML = sorted.map(p => {
    const responded = !!p.has_responded;
    return `<article class="client-poll-card ${responded ? 'is-responded' : ''}" id="poll${p.id}">
      <div class="poll-card-head">
        <div>
          <span class="poll-type-chip">${Pyrk.esc(pollTypeLabel(p.poll_type))}</span>
          <h3>${Pyrk.esc(p.title)}</h3>
          <p>${Pyrk.esc(p.description || '')}</p>
        </div>
        <span class="pill">${Pyrk.esc(targetText(p))}</span>
      </div>

      ${responded ? responseSummary(p) : `
        <form class="client-poll-form" data-poll-id="${Number(p.id)}" data-multiple="${Number(p.allow_multiple || 0)}">
          <div class="client-poll-options">
            ${(p.options || []).map(o => optionInput(p, o)).join('')}
          </div>
          <label class="field-label">Comment / suggestion
            <textarea name="comment" placeholder="Optional: tell us why you chose this."></textarea>
          </label>
          <button class="btn" type="submit">Submit opinion</button>
        </form>`}
    </article>`;
  }).join('') || '<div class="empty-state"><strong>No open polls</strong><span>There are no polls assigned to you right now.</span></div>';
}

async function loadPolls() {
  const res = await Pyrk.get('polls.php', {action:'active'});
  if (!res.ok) {
    Pyrk.toast('clientPollMsg', res);
    return;
  }
  renderPolls(res.data?.polls || []);

  const selectedId = Number(window.PYRK_SELECTED_POLL_ID || 0);
  if (selectedId) setTimeout(() => document.getElementById(`poll${selectedId}`)?.scrollIntoView({behavior:'smooth', block:'start'}), 200);
}

document.addEventListener('submit', async e => {
  const form = e.target.closest('.client-poll-form');
  if (!form) return;
  e.preventDefault();

  const pollId = Number(form.dataset.pollId || 0);
  const checked = [...form.querySelectorAll('input[type="radio"]:checked, input[type="checkbox"]:checked')].map(i => Number(i.value));
  if (!checked.length) {
    Pyrk.toast('clientPollMsg', {ok:false, message:'Select an option first.'});
    return;
  }

  const comment = form.querySelector('textarea[name="comment"]')?.value || '';
  const res = await Pyrk.post('polls.php', {action:'submit', poll_id: pollId, option_ids: checked, comment});
  Pyrk.toast('clientPollMsg', res);
  if (res.ok) await loadPolls();
});

loadPolls();
