<%= form_for @vote, url: {controller: "platform_communicates", action: "#{type}"} do |form| %>
  <% if vote.errors.any? %>
    <div class="alert alert-danger">
      <h5><%= pluralize(vote.errors.count, "error") %> 阻止了此投票的保存：</h5>
      <ul>
        <% vote.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <!-- 基本信息 -->
  <div class="card mb-4">
    <div class="card-header">
      <h6 class="m-0 font-weight-bold text-primary">基本信息</h6>
    </div>
    <div class="card-body">

      <div class="form-group">
        <%= form.label :description, "投票描述", class: "font-weight-bold" %>
        <%= form.text_area :description, class: "form-control", rows: 3, placeholder: "输入投票描述（可选）" %>
        <small class="form-text text-muted">详细描述投票的目的和背景</small>
      </div>
    </div>
  </div>

  <!-- 投票设置 -->
  <div class="card mb-4">
    <div class="card-header">
      <h6 class="m-0 font-weight-bold text-primary">投票设置</h6>
    </div>
    <div class="card-body">
      <div class="form-group">
        <div class="form-check">
          <%= form.check_box :is_multiple_choice, class: "form-check-input", id: "is_multiple_choice" %>
          <%= form.label :is_multiple_choice, "允许多选", class: "form-check-label font-weight-bold" %>
        </div>
        <small class="form-text text-muted">启用后用户可以选择多个选项</small>
      </div>

      <div class="form-group" id="max_choices_field" style="<%= 'display: none;' unless @vote.is_multiple_choice %>">
        <%= form.label :max_choice_vote_options_count, "最多选择数", class: "font-weight-bold" %>
        <%= form.number_field :max_choice_vote_options_count, class: "form-control", min: 2, max: 20, placeholder: "输入最多可选择的数量" %>
        <small class="form-text text-muted">设置用户最多可以选择的选项数量（2-20）</small>
      </div>

      <div class="form-group">
        <%= form.label :due_at, "结束时间", class: "font-weight-bold" %>
        <div class="input-group">
          <%= form.datetime_local_field :due_at, class: "form-control" %>
          <div class="input-group-append">
            <button type="button" class="btn btn-outline-secondary" id="clear_ends_at">
              清除
            </button>
          </div>
        </div>
        <small class="form-text text-muted">不设置则投票永久有效</small>
      </div>
    </div>
  </div>

  <!-- 投票选项 -->
  <div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h6 class="m-0 font-weight-bold text-primary">投票选项</h6>
      <button type="button" class="btn btn-sm btn-primary" id="add_vote_option">
        添加选项
      </button>
    </div>
    <div class="card-body">
      <div id="vote_options">
        <%= form.fields_for :vote_options do |vote_option_fields| %>
          <div class="vote-option-item card mb-3">
            <div class="card-body">
              <div class="row">
                <div class="col-md-8">
                  <div class="form-group">
                    <%= vote_option_fields.label :title, "选项名称", class: "font-weight-bold" %>
                    <%= vote_option_fields.text_field :title, class: "form-control", placeholder: "输入选项名称", required: true %>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <%= vote_option_fields.label :order_index, "排序", class: "font-weight-bold" %>
                    <%= vote_option_fields.number_field :order_index, class: "form-control", min: 1, value: vote_option_fields.object.order_index || 1 %>
                  </div>
                </div>
                <div class="col-md-1 d-flex align-items-end">
                  <% unless vote_option_fields.object.persisted? %>
                    <button type="button" class="btn btn-danger btn-sm remove-option" style="margin-bottom: 1rem;">
                      删除
                    </button>
                  <% end %>
                </div>
              </div>
              <% if vote_option_fields.object.persisted? %>
                <div class="form-group">
                  <div class="form-check">
                    <%= vote_option_fields.check_box :_destroy, class: "form-check-input" %>
                    <%= vote_option_fields.label :_destroy, "删除此选项", class: "form-check-label text-danger" %>
                  </div>
                </div>
              <% end %>
            </div>
          </div>
        <% end %>
      </div>
      
      <div class="alert alert-info"> 
        <strong>提示：</strong> 至少需要添加2个投票选项，最多支持50个选项。
      </div>
    </div>
  </div>

  <!-- 表单操作 -->
  <div class="form-group text-center">
    <%= form.submit vote.persisted? ? "更新投票" : "创建投票", class: "btn btn-primary btn-lg mr-2" %>
    <%= link_to "取消", applet_admins_platform_communicates_path, class: "btn btn-secondary btn-lg" %>
  </div>
<% end %>

<!-- 投票选项模板（用于动态添加） -->
<template id="vote_option_template">
  <div class="vote-option-item card mb-3">
    <div class="card-body">
      <div class="row">
        <div class="col-md-8">
          <div class="form-group">
            <label class="font-weight-bold">选项名称</label>
            <input type="text" name="vote[vote_options_attributes][INDEX][title]" class="form-control" placeholder="输入选项名称" required>
          </div>
        </div>
        <div class="col-md-3">
          <div class="form-group">
            <label class="font-weight-bold">排序</label>
            <input type="number" name="vote[vote_options_attributes][INDEX][order_index]" class="form-control" min="1" value="1">
          </div>
        </div>
        <div class="col-md-1 d-flex align-items-end">
          <button type="button" class="btn btn-danger btn-sm remove-option" style="margin-bottom: 1rem;">
            删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<%= javascript_tag nonce: true do %>
  // 简化的投票表单交互功能
document.addEventListener('DOMContentLoaded', function() {
  initVoteForm();
});

// 如果使用 Turbolinks/Turbo
document.addEventListener('turbolinks:load', initVoteForm);
document.addEventListener('turbo:load', initVoteForm);

function initVoteForm() {
  console.log('初始化投票表单...');
  
  // 防止重复初始化
  if (window.voteFormInitialized) {
    console.log('投票表单已经初始化过，跳过');
    return;
  }
  window.voteFormInitialized = true;
  
  // 多选切换
  const multipleChoiceCheckbox = document.getElementById('is_multiple_choice');
  const maxChoicesField = document.getElementById('max_choices_field');
  
  if (multipleChoiceCheckbox && maxChoicesField) {
    function toggleMaxChoices() {
      maxChoicesField.style.display = multipleChoiceCheckbox.checked ? 'block' : 'none';
      if (!multipleChoiceCheckbox.checked) {
        const maxChoiceInput = document.getElementById('vote_max_choice_vote_options_count');
        if (maxChoiceInput) maxChoiceInput.value = '';
      }
    }
    
    multipleChoiceCheckbox.addEventListener('change', toggleMaxChoices);
    toggleMaxChoices(); // 初始状态
  }
  
  // 清除结束时间
  const clearEndsAtBtn = document.getElementById('clear_ends_at');
  if (clearEndsAtBtn) {
    clearEndsAtBtn.addEventListener('click', function() {
      const endsAtInput = document.getElementById('vote_ends_at');
      if (endsAtInput) endsAtInput.value = '';
    });
  }
  
  // 添加选项 - 关键修复：确保只绑定一次
  const addOptionButton = document.getElementById('add_vote_option');
  if (addOptionButton && !addOptionButton.hasListener) {
    addOptionButton.hasListener = true; // 标记已绑定
    
    addOptionButton.addEventListener('click', function(event) {
      event.preventDefault();
      event.stopPropagation();
      addNewOption();
    });
  }
  
  // 删除选项 - 使用事件委托
  const optionsContainer = document.getElementById('vote_options');
  if (optionsContainer) {
    optionsContainer.addEventListener('click', function(event) {
      if (event.target.closest('.remove-option')) {
        event.preventDefault();
        event.target.closest('.vote-option-item').remove();
      }
    });
  }
  
  // 表单验证
  const form = document.querySelector('.vote-form');
  if (form) {
    form.addEventListener('submit', validateForm);
  }
}

// 添加新选项
function addNewOption() {
  console.log('执行添加选项函数');
  
  const optionsContainer = document.getElementById('vote_options');
  const optionTemplate = document.getElementById('vote_option_template');
  
  if (!optionsContainer || !optionTemplate) {
    console.error('找不到选项容器或模板');
    return;
  }
  
  // 计算新的索引和位置
  const currentOptions = optionsContainer.querySelectorAll('.vote-option-item');
  const newIndex = currentOptions.length;
  const newPosition = getNextPosition();
  
  const newOption = optionTemplate.content.cloneNode(true);
  const html = newOption.querySelector('.vote-option-item').outerHTML;
  let newHtml = html.replace(/INDEX/g, newIndex);
  newHtml = newHtml.replace(/POSITION_VALUE/g, newPosition);
  
  optionsContainer.insertAdjacentHTML('beforeend', newHtml);
  
  console.log(`成功添加选项，索引: ${newIndex}, 位置: ${newPosition}`);
}

// 获取下一个位置值
function getNextPosition() {
  const positionInputs = document.querySelectorAll('input[name*="position"]');
  let maxPosition = 0;
  
  positionInputs.forEach(input => {
    const value = parseInt(input.value) || 0;
    if (value > maxPosition) maxPosition = value;
  });
  
  return maxPosition + 1;
}

// 表单验证
function validateForm(event) {
  const optionsContainer = document.getElementById('vote_options');
  const optionItems = optionsContainer ? optionsContainer.querySelectorAll('.vote-option-item') : [];
  let validOptionCount = 0;
  
  // 计算有效的选项数量
  optionItems.forEach(item => {
    const nameInput = item.querySelector('input[type="text"][name*="name"]');
    if (nameInput && nameInput.value.trim()) {
      validOptionCount++;
    }
  });
  
  if (validOptionCount < 2) {
    event.preventDefault();
    alert('请至少填写2个有效的投票选项！');
    return false;
  }
  
  // 验证选项名称是否重复
  const optionNames = [];
  let hasDuplicate = false;
  
  optionItems.forEach(item => {
    const nameInput = item.querySelector('input[type="text"][name*="name"]');
    if (nameInput && nameInput.value.trim()) {
      const name = nameInput.value.trim().toLowerCase();
      if (optionNames.includes(name)) {
        hasDuplicate = true;
        nameInput.classList.add('is-invalid');
      } else {
        optionNames.push(name);
        nameInput.classList.remove('is-invalid');
      }
    }
  });
  
  if (hasDuplicate) {
    event.preventDefault();
    alert('存在重复的选项名称，请修改后重新提交！');
    return false;
  }
  
  return true;
}
<% end %>