<template>
  <div class="voting-page">
    <!-- Step 1: Admission Number -->
    <div v-if="step === 1" class="step-container admission-step">
      <div class="content-card">
        <h1>Welcome to KCPS Elections</h1>
        <p class="instruction">Enter your admission number to proceed to the ballot.</p>
        <div class="input-group">
          <input 
            v-model="admissionNumber" 
            type="text" 
            placeholder="e.g. 2024001" 
            @keyup.enter="checkAdmission"
            ref="admissionInput"
            autofocus
          />
          <button @click="checkAdmission" :disabled="loading" class="primary-btn large">
            {{ loading ? 'Verifying...' : 'Start Voting' }}
          </button>
        </div>
        <p v-if="error" class="error-text">{{ error }}</p>
      </div>
    </div>

    <!-- Step 2: Full Ballot Selection -->
    <div v-else-if="step === 2" class="step-container ballot-step">
      <header class="ballot-header">
        <div class="voter-info">
          Voter Admission: <span>{{ admissionNumber }}</span>
        </div>
        <h2>Cast Your Ballot</h2>
        <button class="ghost-btn" @click="resetFlow">Cancel</button>
      </header>

      <div class="ballot-content">
        <div v-for="pos in positions" :key="pos.id" class="position-section">
          <h3 class="pos-title">{{ pos.title }}</h3>
          <div class="candidates-grid">
            <div 
              v-for="candidate in getCandidatesForPosition(pos.id)" 
              :key="candidate.id" 
              class="candidate-card"
              :class="{ selected: selections[pos.id] === candidate.id }"
              @click="selectCandidate(pos.id, candidate.id)"
            >
              <div class="image-box">
                <img :src="candidate.image_url ? 'http://192.168.29.200:3000' + candidate.image_url : '/placeholder.png'" :alt="candidate.name" />
                <div v-if="selections[pos.id] === candidate.id" class="selected-check">✓</div>
              </div>
              <div class="candidate-info">
                <h3>{{ candidate.name }}</h3>
              </div>
            </div>
          </div>
        </div>
      </div>

      <footer class="ballot-footer">
        <p v-if="!isBallotComplete" class="warning-text">
          Please select one candidate for each position to proceed.
        </p>
        <button 
          @click="showConfirmModal = true" 
          :disabled="!isBallotComplete" 
          class="primary-btn submit-ballot-btn"
        >
          Submit Full Ballot
        </button>
      </footer>
    </div>

    <!-- Step 3: Success Confirmation -->
    <div v-else-if="step === 3" class="step-container success-step">
      <div class="success-card">
        <div class="check-icon">✓</div>
        <h2>Vote Recorded!</h2>
        <p>Thank you for participating in the KCPS Student Council Election.</p>
        <div class="progress-bar-container">
          <div class="progress-bar" :style="{ width: progress + '%' }"></div>
        </div>
        <p class="timer-text">Resetting for next voter in {{ Math.ceil((100 - progress)/33) }}s</p>
      </div>
    </div>

    <!-- Modal -->
    <Transition name="fade">
      <div v-if="showConfirmModal" class="modal-backdrop">
        <div class="modal">
          <div class="modal-icon">🗳️</div>
          <h3>Confirm Your Selection</h3>
          <p>You have made selections for all {{ positions.length }} positions.</p>
          <div class="modal-footer">
            <button class="confirm-btn" @click="submitVote" :disabled="loading">
              {{ loading ? 'Processing...' : 'Yes, Cast Ballot' }}
            </button>
            <button class="cancel-btn" @click="showConfirmModal = false">No, Go Back</button>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, reactive, computed } from 'vue';
import { candidateService, voteService, positionService } from '../services/api';

const step = ref(1);
const admissionNumber = ref('');
const positions = ref([]);
const allCandidates = ref([]);
const selections = reactive({}); // { positionId: candidateId }
const showConfirmModal = ref(false);
const loading = ref(false);
const error = ref('');
const admissionInput = ref(null);
const progress = ref(0);

const isBallotComplete = computed(() => {
  return positions.value.every(pos => !!selections[pos.id]);
});

onMounted(async () => {
  fetchData();
  focusInput();
});

const focusInput = () => {
  nextTick(() => {
    admissionInput.value?.focus();
  });
};

const fetchData = async () => {
  try {
    const [posRes, candRes] = await Promise.all([
      positionService.getAll(),
      candidateService.getAll()
    ]);
    positions.value = posRes.data;
    allCandidates.value = candRes.data;
  } catch (err) {
    console.error('Failed to fetch data');
  }
};

const getCandidatesForPosition = (posId) => {
  return allCandidates.value.filter(c => c.position_id === posId);
};

const selectCandidate = (posId, candId) => {
  selections[posId] = candId;
};

const checkAdmission = async () => {
  if (!admissionNumber.value) {
    error.value = 'Please enter your admission number';
    return;
  }

  const num = parseInt(admissionNumber.value);
  if (isNaN(num) || num < 5000 || num > 15000) {
    error.value = 'Invalid Admission Number. Must be between 5000 and 15000.';
    return;
  }

  loading.value = true;
  error.value = '';
  try {
    const response = await voteService.checkAdmission(admissionNumber.value);
    if (response.data.hasVoted) {
      error.value = 'Already voted under this admission number.';
    } else {
      step.value = 2;
    }
  } catch (err) {
    error.value = err.response?.data?.error || 'Verification failed. Try again.';
  } finally {
    loading.value = false;
  }
};

const submitVote = async () => {
  loading.value = true;
  try {
    const candidateIds = Object.values(selections);
    await voteService.castVote({
      admissionNumber: admissionNumber.value,
      candidateIds: candidateIds
    });
    showConfirmModal.value = false;
    step.value = 3;
    startResetTimer();
  } catch (err) {
    alert('Critical Error: Failed to save ballot.');
    showConfirmModal.value = false;
  } finally {
    loading.value = false;
  }
};

const startResetTimer = () => {
  progress.value = 0;
  const interval = setInterval(() => {
    progress.value += 2;
    if (progress.value >= 100) {
      clearInterval(interval);
      resetFlow();
    }
  }, 60);
};

const resetFlow = () => {
  step.value = 1;
  admissionNumber.value = '';
  Object.keys(selections).forEach(key => delete selections[key]);
  error.value = '';
  focusInput();
};
</script>

<style scoped>
.voting-page {
  min-height: 100vh;
  background-color: var(--bg-color);
  color: var(--text-primary);
}

.step-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
}

/* Step 1 */
.admission-step {
  justify-content: center;
  height: 80vh;
}

.content-card {
  background: var(--card-bg);
  padding: 4rem;
  border-radius: 16px;
  border: 1px solid var(--border-color);
  text-align: center;
  max-width: 600px;
  width: 100%;
}

h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.instruction {
  color: var(--text-secondary);
  font-size: 1.1rem;
  margin-bottom: 3rem;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

input {
  background: #252932;
  border: 2px solid var(--border-color);
  padding: 1.5rem;
  border-radius: 12px;
  color: var(--text-primary);
  font-size: 1.5rem;
  text-align: center;
}

input:focus {
  outline: none;
  border-color: var(--accent-color);
}

.primary-btn.large {
  padding: 1.5rem;
  font-size: 1.25rem;
  font-weight: 700;
  background-color: var(--accent-color);
  border: none;
  border-radius: 12px;
  color: #fff;
  cursor: pointer;
}

.error-text {
  color: var(--danger-color);
  margin-top: 1.5rem;
  font-weight: 600;
}

/* Step 2 */
.ballot-step {
  max-width: 1200px;
  margin: 0 auto;
}

.ballot-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.voter-info {
  color: var(--text-secondary);
}

.voter-info span {
  color: var(--accent-color);
  font-weight: 700;
}

.ballot-content {
  width: 100%;
}

.position-section {
  margin-bottom: 4rem;
}

.pos-title {
  color: var(--accent-color);
  font-size: 1.5rem;
  margin-bottom: 2rem;
  text-transform: uppercase;
  letter-spacing: 2px;
  border-left: 4px solid var(--accent-color);
  padding-left: 1rem;
}

.candidates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 2rem;
  width: 100%;
}

.candidate-card {
  background: var(--card-bg);
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid var(--border-color);
  cursor: pointer;
  position: relative;
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.candidate-card:hover {
  transform: translateY(-8px);
}

.candidate-card.selected {
  border-color: var(--accent-color);
  background: rgba(124, 58, 237, 0.1);
  box-shadow: 0 0 20px rgba(124, 58, 237, 0.2);
}

.image-box {
  width: 100%;
  aspect-ratio: 1/1;
  background: #252932;
  position: relative;
}

.image-box img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.selected-check {
  position: absolute;
  top: 10px;
  right: 10px;
  background: var(--accent-color);
  color: #fff;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
}

.candidate-info {
  padding: 1rem;
  text-align: center;
}

.candidate-info h3 {
  margin: 0;
  font-size: 1.1rem;
  color: var(--text-primary);
}

.ballot-footer {
  width: 100%;
  margin-top: 4rem;
  padding: 2rem;
  text-align: center;
  border-top: 1px solid var(--border-color);
}

.warning-text {
  color: var(--danger-color);
  margin-bottom: 1.5rem;
  font-weight: 600;
}

.submit-ballot-btn {
  padding: 1.5rem 4rem;
  font-size: 1.5rem;
  font-weight: 800;
  border-radius: 50px;
}

.submit-ballot-btn:disabled {
  background: #252932;
  color: var(--text-secondary);
  cursor: not-allowed;
}

/* Success */
.success-step {
  justify-content: center;
  height: 80vh;
}

.success-card {
  text-align: center;
  background: var(--card-bg);
  padding: 4rem;
  border-radius: 16px;
  border: 2px solid var(--accent-color);
  max-width: 500px;
}

.check-icon {
  width: 80px;
  height: 80px;
  background: var(--accent-color);
  color: #fff;
  font-size: 3rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  margin: 0 auto 2rem;
}

.progress-bar-container {
  width: 100%;
  height: 6px;
  background: #252932;
  border-radius: 3px;
  margin: 2rem 0 1rem;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: var(--accent-color);
  transition: width 0.06s linear;
}

.timer-text {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

/* Modal */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.85);
  backdrop-filter: blur(8px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: var(--card-bg);
  padding: 3rem;
  border-radius: 20px;
  border: 1px solid var(--border-color);
  max-width: 440px;
  width: 90%;
  text-align: center;
}

.modal-icon {
  font-size: 4rem;
  margin-bottom: 1.5rem;
}

.modal-footer {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 2rem;
}

.confirm-btn {
  background: var(--accent-color);
  color: #fff;
  border: none;
  padding: 1rem;
  border-radius: 8px;
  font-weight: 700;
  font-size: 1.1rem;
  cursor: pointer;
}

.cancel-btn {
  background: transparent;
  color: var(--text-secondary);
  border: none;
  cursor: pointer;
  padding: 0.5rem;
}

.ghost-btn {
  background: transparent;
  border: 1px solid var(--border-color);
  color: var(--text-secondary);
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
