<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Heart, Send, CheckCircle2, MessageSquare, Shield, Fish, Trash2, HelpCircle } from 'lucide-vue-next'

const stats = ref({
  totalDonors: 12543,
  totalAmount: 627150000,
  releasedFish: 4200000,
  collectedWaste: 185000,
  purifiedArea: 95000
})

const recentDonations = ref<any[]>([])

const form = ref({
  name: '',
  amount: 30000,
  message: ''
})

const showSuccess = ref(false)
const isSubmitting = ref(false)

const predefinedAmounts = [10000, 30000, 50000, 100000, 300000]

// Real-time impact simulation computed values
const simulatedImpact = computed(() => {
  const amount = form.value.amount || 0
  const multiplier = amount / 10000
  return {
    fish: Math.floor(multiplier * 2),
    waste: (multiplier * 0.5).toFixed(1),
    area: (multiplier * 0.2).toFixed(2)
  }
})

const loadData = async () => {
  try {
    // @ts-ignore
    const CampaignService = await import('../../bindings/changeme/campaignservice')
    const currentStats = await CampaignService.GetStats()
    if (currentStats) stats.value = currentStats
    const list = await CampaignService.GetRecentDonations()
    if (list) {
      // Reverse list to show newest first
      recentDonations.value = [...list].reverse()
    }
  } catch (e) {
    console.warn('Wails bindings not available, using mock local data.', e)
    // Local mock data fallback
    recentDonations.value = [
      { name: '김어부', amount: 50000, message: '바다가 다시 풍요로워지길 바랍니다.', timestamp: new Date(Date.now() - 10 * 60000).toISOString() },
      { name: '이바다', amount: 30000, message: '깨끗한 바다를 우리 아이들에게!', timestamp: new Date(Date.now() - 60 * 60000).toISOString() },
      { name: '박수협', amount: 100000, message: '어업인 여러분 힘내세요!', timestamp: new Date(Date.now() - 180 * 60000).toISOString() }
    ]
  }
}

onMounted(() => {
  loadData()
})

const handleDonate = async () => {
  if (form.value.amount <= 0) return
  isSubmitting.value = true
  
  try {
    // @ts-ignore
    const CampaignService = await import('../../bindings/changeme/campaignservice')
    const newStats = await CampaignService.Donate(form.value.name, form.value.amount, form.value.message)
    if (newStats) stats.value = newStats
    
    // Refresh donation list
    const list = await CampaignService.GetRecentDonations()
    if (list) recentDonations.value = [...list].reverse()
    
    showSuccessModal()
  } catch (e) {
    console.warn('Wails backend Donate call skipped. Simulating successfully on frontend.', e)
    // Simulating locally if not running in Wails
    stats.value.totalDonors += 1
    stats.value.totalAmount += form.value.amount
    
    const multiplier = form.value.amount / 10000
    stats.value.releasedFish += Math.floor(multiplier * 2)
    stats.value.collectedWaste += Math.floor(multiplier * 0.5)
    stats.value.purifiedArea += Math.floor(multiplier * 0.2)
    
    recentDonations.value.unshift({
      name: form.value.name || '익명의 기부자',
      amount: form.value.amount,
      message: form.value.message || '푸른 바다를 함께 응원합니다!',
      timestamp: new Date().toISOString()
    })
    
    showSuccessModal()
  } finally {
    isSubmitting.value = false
  }
}

const showSuccessModal = () => {
  showSuccess.value = true
  // Reset form
  form.value.name = ''
  form.value.message = ''
}

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('ko-KR').format(num)
}

const formatDate = (dateStr: string) => {
  const d = new Date(dateStr)
  return `${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}
</script>

<template>
  <div class="donation-container">
    <!-- Hero Header -->
    <div class="donation-hero">
      <h1 class="page-title">희망의 바다 기금 기부</h1>
      <p class="page-subtitle">수협중앙회와 함께 더 맑은 바다 생태계를 가꾸는 가장 가치 있는 첫걸음입니다.</p>
    </div>

    <!-- Main Grid layout -->
    <div class="donation-grid">
      <!-- Left Column: Form and Impact simulation -->
      <div class="column-left">
        <!-- Interactive Impact Simulator Card -->
        <div class="card simulator-card">
          <h3 class="card-title"><Fish class="card-icon" /> 실시간 기부 효과 시뮬레이션</h3>
          <p class="card-desc">기부하시는 금액에 따라 우리 바다에 생겨날 놀라운 변화를 확인해보세요.</p>
          
          <div class="simulator-graphic">
            <!-- Ocean environment visual feedback -->
            <div class="mini-ocean">
              <div class="sim-bubbles">
                <div v-for="n in 6" :key="n" class="sim-bubble" :style="`--i:${n}`"></div>
              </div>
              
              <!-- Floating simulated fish -->
              <div class="fish-pond">
                <div 
                  v-for="n in Math.min(simulatedImpact.fish, 10)" 
                  :key="n" 
                  class="sim-fish"
                  :style="`--speed:${1.5 + Math.random() * 2}s; --delay:${Math.random() * 2}s; --y:${15 + (n * 8)}%`"
                >
                  🐟
                </div>
                <div v-if="simulatedImpact.fish === 0" class="no-fish-text">치어가 방류 대기 중입니다.</div>
              </div>
            </div>
          </div>

          <!-- Impact Metrics Grid -->
          <div class="impact-metrics">
            <div class="metric-box">
              <span class="m-icon"><Fish /></span>
              <span class="m-val">{{ simulatedImpact.fish }} 마리</span>
              <span class="m-lbl">수산 치어 방류</span>
            </div>
            <div class="metric-box">
              <span class="m-icon"><Trash2 /></span>
              <span class="m-val">{{ simulatedImpact.waste }} kg</span>
              <span class="m-lbl">해양 쓰레기 수거</span>
            </div>
            <div class="metric-box">
              <span class="m-icon"><Shield /></span>
              <span class="m-val">{{ simulatedImpact.area }} m²</span>
              <span class="m-lbl">바닷속 갯녹음 정화</span>
            </div>
          </div>
        </div>

        <!-- Donation Form Card -->
        <div class="card form-card">
          <h3 class="card-title"><Heart class="card-icon form-icon" /> 가상 후원 참여 폼</h3>
          <p class="card-desc">후원 금액과 응원 메시지는 실시간 캠페인 대시보드에 반영됩니다.</p>
          
          <form @submit.prevent="handleDonate" class="donation-form">
            <!-- Name Input -->
            <div class="form-group">
              <label for="donor-name" class="form-label">후원자명 (또는 단체명)</label>
              <input 
                id="donor-name"
                type="text" 
                v-model="form.name" 
                placeholder="익명의 기부자" 
                class="form-input"
              />
            </div>

            <!-- Amount Input & Preset Buttons -->
            <div class="form-group">
              <label class="form-label">후원 금액 선택</label>
              <div class="preset-buttons">
                <button
                  type="button"
                  v-for="amt in predefinedAmounts"
                  :key="amt"
                  :class="['preset-btn', { active: form.amount === amt }]"
                  @click="form.amount = amt"
                >
                  {{ formatNumber(amt / 10000) }}만 원
                </button>
              </div>
              <div class="custom-amount-input">
                <input 
                  type="number" 
                  v-model.number="form.amount" 
                  placeholder="직접 입력 (원)" 
                  min="1000"
                  step="1000"
                  class="form-input custom-input"
                />
                <span class="currency-label">원</span>
              </div>
            </div>

            <!-- Message Input -->
            <div class="form-group">
              <label for="donor-msg" class="form-label">바다를 위한 응원 메시지</label>
              <textarea 
                id="donor-msg"
                v-model="form.message" 
                placeholder="깨끗한 바다를 향한 어업인과 수협에 전할 격려의 한마디를 작성해주세요."
                class="form-textarea"
                rows="3"
              ></textarea>
            </div>

            <button type="submit" class="btn btn-submit" :disabled="isSubmitting || form.amount < 1000">
              <Heart class="submit-icon" />
              <span>{{ isSubmitting ? '전송 중...' : '기금 후원하기' }}</span>
            </button>
          </form>
        </div>
      </div>

      <!-- Right Column: Live dashboard stats and recent list -->
      <div class="column-right">
        <!-- Campaign Stats Box -->
        <div class="card stats-box-card">
          <h3 class="card-title">실시간 희망 바다 현황</h3>
          <div class="simple-stat-row">
            <span class="simple-lbl">누적 기금 조성액</span>
            <span class="simple-val accent-text">{{ formatNumber(stats.totalAmount) }} 원</span>
          </div>
          <div class="simple-stat-row">
            <span class="simple-lbl">누적 동참자</span>
            <span class="simple-val">{{ formatNumber(stats.totalDonors) }} 명</span>
          </div>
        </div>

        <!-- Recent Donations Feed -->
        <div class="card feed-card">
          <h3 class="card-title"><MessageSquare class="card-icon" /> 실시간 참여 피드</h3>
          <div class="donation-feed">
            <transition-group name="list">
              <div v-for="(item, idx) in recentDonations" :key="idx" class="feed-item">
                <div class="feed-header">
                  <span class="feed-name">{{ item.name }} 님</span>
                  <span class="feed-amt">{{ formatNumber(item.amount) }}원 후원</span>
                </div>
                <p class="feed-msg">"{{ item.message || '풍요로운 바다의 미래를 힘차게 응원합니다!' }}"</p>
                <span class="feed-time">{{ formatDate(item.timestamp) }}</span>
              </div>
            </transition-group>
            
            <div v-if="recentDonations.length === 0" class="empty-feed">
              첫 번째 기부 참여를 기다리고 있습니다.
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Success Modal popup -->
    <div v-if="showSuccess" class="modal-overlay" @click.self="showSuccess = false">
      <div class="modal-content">
        <CheckCircle2 class="success-big-icon" />
        <h2 class="modal-title">후원이 완료되었습니다!</h2>
        <p class="modal-desc">
          보내주신 따뜻한 희망의 씨앗이 건강한 바다 생태계 복원과 우리 어업인 지원 기금에 소중하게 사용됩니다. 감사합니다!
        </p>
        <button class="btn btn-primary btn-modal-close" @click="showSuccess = false">확인</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.donation-container {
  display: flex;
  flex-direction: column;
  gap: 40px;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.donation-hero {
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  font-weight: 800;
  margin: 0 0 10px 0;
  background: linear-gradient(to right, #ffffff, var(--primary-color));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.page-subtitle {
  color: #64748b;
  margin: 0;
}

.donation-grid {
  display: grid;
  grid-template-columns: 1.3fr 1fr;
  gap: 30px;
}

.column-left, .column-right {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

/* Card Common Base */
.card {
  background: rgba(6, 17, 38, 0.4);
  border: 1px solid rgba(0, 210, 255, 0.08);
  border-radius: 20px;
  padding: 30px;
  backdrop-filter: blur(10px);
}

.card-title {
  font-size: 1.25rem;
  font-weight: 800;
  color: white;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-icon {
  width: 20px;
  height: 20px;
  color: var(--primary-color);
}

.card-desc {
  font-size: 0.9rem;
  color: #64748b;
  margin: 0 0 20px 0;
}

/* Live Simulator Visual Graphic */
.simulator-card {
  border-color: rgba(0, 210, 255, 0.15);
}

.simulator-graphic {
  width: 100%;
  margin-bottom: 24px;
}

.mini-ocean {
  width: 100%;
  height: 180px;
  background: linear-gradient(to bottom, #072a56 0%, #03152d 100%);
  border-radius: 12px;
  border: 1px solid rgba(0, 210, 255, 0.2);
  position: relative;
  overflow: hidden;
}

.sim-bubbles {
  position: absolute;
  inset: 0;
}

.sim-bubble {
  position: absolute;
  bottom: -10px;
  background: rgba(0, 210, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  width: 8px;
  height: 8px;
  left: calc(var(--i) * 15%);
  animation: sim-bubble-up 3s linear infinite;
  animation-delay: calc(var(--i) * 0.4s);
}

@keyframes sim-bubble-up {
  0% { transform: translateY(0) scale(1); opacity: 0; }
  20% { opacity: 0.6; }
  90% { opacity: 0.6; }
  100% { transform: translateY(-200px) scale(1.3); opacity: 0; }
}

.fish-pond {
  position: absolute;
  inset: 0;
}

.sim-fish {
  position: absolute;
  font-size: 1.3rem;
  animation: swim var(--speed) linear infinite alternate;
  animation-delay: var(--delay);
  left: -20px;
  top: var(--y);
}

@keyframes swim {
  0% { left: -20px; transform: scaleX(1); }
  45% { transform: scaleX(1); }
  50% { transform: scaleX(-1); }
  95% { transform: scaleX(-1); }
  100% { left: calc(100% - 10px); transform: scaleX(1); }
}

.no-fish-text {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #475569;
  font-weight: 600;
  font-size: 0.9rem;
}

/* Impact Metrics */
.impact-metrics {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.metric-box {
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(0, 210, 255, 0.08);
  border-radius: 12px;
  padding: 15px 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.m-icon {
  color: var(--primary-color);
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
}

.m-val {
  font-size: 1.1rem;
  font-weight: 800;
  color: white;
}

.m-lbl {
  font-size: 0.75rem;
  color: #64748b;
  font-weight: 600;
}

/* Donation Form */
.donation-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 0.9rem;
  font-weight: 700;
  color: #cbd5e1;
}

.form-input, .form-textarea {
  background: rgba(0, 0, 0, 0.25);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  padding: 12px 16px;
  color: white;
  font-family: inherit;
  font-size: 0.95rem;
  transition: all 0.3s ease;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 10px rgba(0, 210, 255, 0.2);
}

.preset-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 8px;
}

.preset-btn {
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 8px;
  padding: 10px;
  color: #94a3b8;
  font-weight: 700;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.preset-btn:hover {
  background: rgba(0, 210, 255, 0.08);
  color: var(--primary-color);
}

.preset-btn.active {
  background: rgba(0, 210, 255, 0.15);
  border-color: var(--primary-color);
  color: white;
}

.custom-amount-input {
  display: flex;
  align-items: center;
  position: relative;
  margin-top: 5px;
}

.custom-input {
  width: 100%;
  padding-right: 40px;
}

.currency-label {
  position: absolute;
  right: 15px;
  color: #64748b;
  font-weight: 700;
}

.btn-submit {
  background: linear-gradient(135deg, #ff6b6b, #ff4747);
  color: white;
  justify-content: center;
  padding: 15px;
  border-radius: 12px;
  font-size: 1.05rem;
  font-weight: 700;
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.3);
  margin-top: 10px;
}

.btn-submit:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 107, 107, 0.5);
}

.btn-submit:disabled {
  background: #1e293b;
  color: #475569;
  box-shadow: none;
  cursor: not-allowed;
}

.submit-icon {
  width: 18px;
  height: 18px;
}

/* Campaign Stats Box */
.stats-box-card {
  background: linear-gradient(135deg, rgba(6, 17, 38, 0.7), rgba(3, 8, 20, 0.7));
  border-color: rgba(0, 210, 255, 0.15);
}

.simple-stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
}

.simple-stat-row:not(:last-child) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.simple-lbl {
  font-size: 0.9rem;
  color: #94a3b8;
  font-weight: 600;
}

.simple-val {
  font-size: 1.15rem;
  font-weight: 800;
  color: white;
}

.accent-text {
  color: var(--primary-color);
  text-shadow: 0 0 10px rgba(0, 210, 255, 0.3);
}

/* Feed Card */
.feed-card {
  flex: 1;
}

.donation-feed {
  display: flex;
  flex-direction: column;
  gap: 15px;
  max-height: 380px;
  overflow-y: auto;
  padding-right: 5px;
}

/* Scrollbar styling */
.donation-feed::-webkit-scrollbar {
  width: 4px;
}
.donation-feed::-webkit-scrollbar-thumb {
  background: rgba(0, 210, 255, 0.2);
  border-radius: 2px;
}

.feed-item {
  background: rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.03);
  border-radius: 12px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 6px;
  transition: all 0.3s ease;
}

.feed-item:hover {
  border-color: rgba(0, 210, 255, 0.1);
  background: rgba(0, 0, 0, 0.25);
}

.feed-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.feed-name {
  font-size: 0.9rem;
  font-weight: 800;
  color: white;
}

.feed-amt {
  font-size: 0.85rem;
  font-weight: 700;
  color: #ff6b6b;
}

.feed-msg {
  font-size: 0.85rem;
  color: #94a3b8;
  margin: 0;
  line-height: 1.4;
  font-style: italic;
}

.feed-time {
  font-size: 0.75rem;
  color: #475569;
  align-self: flex-end;
}

.empty-feed {
  padding: 40px;
  text-align: center;
  color: #475569;
  font-size: 0.9rem;
  font-weight: 600;
}

/* Success Modal */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(2, 6, 17, 0.8);
  backdrop-filter: blur(8px);
  z-index: 110;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.modal-content {
  background: radial-gradient(circle at center, #061530 0%, #030814 100%);
  border: 1px solid rgba(0, 210, 255, 0.25);
  max-width: 500px;
  width: 100%;
  border-radius: 24px;
  padding: 40px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 20px 50px rgba(0, 210, 255, 0.3);
}

.success-big-icon {
  width: 70px;
  height: 70px;
  color: var(--primary-color);
  margin-bottom: 20px;
  animation: scale-up-bounce 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

@keyframes scale-up-bounce {
  0% { transform: scale(0.3); opacity: 0; }
  70% { transform: scale(1.1); }
  100% { transform: scale(1); opacity: 1; }
}

.modal-title {
  font-size: 1.6rem;
  font-weight: 800;
  color: white;
  margin: 0 0 10px 0;
}

.modal-desc {
  font-size: 0.95rem;
  color: #94a3b8;
  line-height: 1.6;
  margin: 0 0 30px 0;
}

.btn-modal-close {
  width: 120px;
}

/* Transitions */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateY(-30px);
}

/* Responsive */
@media (max-width: 992px) {
  .donation-grid {
    grid-template-columns: 1fr;
  }
}
</style>
