<template>
  <div>
    <section class="hero-carousel">
      <div class="carousel-track" :style="{ transform: `translateX(-${current * 100}%)` }">
        <div v-for="(slide, i) in slides" :key="i" class="carousel-slide" :style="{ background: `linear-gradient(rgba(0,0,0,.55), rgba(0,0,0,.55)), url(${slide.bgImage}) center/cover no-repeat` }">
          <div class="slide-bg-icon"><i class="fa-solid fa-church"></i></div>
          <div class="slide-content">
            <h1>{{ slide.title.replace('{name}', info.name || 'Our Church') }}</h1>
            <p>{{ slide.subtitle }}</p>
            <div>
              <router-link :to="slide.btnLink" class="btn btn-light btn-lg me-2">
                <i :class="slide.btnIcon + ' me-2'"></i>{{ slide.btnText }}
              </router-link>
            </div>
          </div>
        </div>
      </div>
      <div class="carousel-indicators">
        <button v-for="(_, i) in slides" :key="i" :class="{ active: current === i }" @click="current = i"></button>
      </div>
      <button class="carousel-control carousel-prev" @click="prev"><i class="fa-solid fa-chevron-left"></i></button>
      <button class="carousel-control carousel-next" @click="next"><i class="fa-solid fa-chevron-right"></i></button>
    </section>

    <div class="countdown-bar" v-if="countdown.days > 0 || countdown.hours > 0">
      <div class="countdown-label">Next Sunday Service in</div>
      <div class="countdown-items">
        <div class="countdown-item"><span class="countdown-num">{{ countdown.days }}</span><span class="countdown-unit">Days</span></div>
        <div class="countdown-item"><span class="countdown-num">{{ countdown.hours }}</span><span class="countdown-unit">Hours</span></div>
        <div class="countdown-item"><span class="countdown-num">{{ countdown.minutes }}</span><span class="countdown-unit">Min</span></div>
        <div class="countdown-item"><span class="countdown-num">{{ countdown.seconds }}</span><span class="countdown-unit">Sec</span></div>
      </div>
    </div>

    <section class="live-stream-section text-center">
      <div class="container">
        <span class="live-badge mb-3"><i class="fa-solid fa-circle me-1"></i>Live Stream</span>
        <h2 class="fw-bold mb-3">Watch Our Services Online</h2>
        <p class="mb-4" style="opacity:.8;">Can&rsquo;t join us in person? Worship with us from anywhere.</p>
        <div class="row justify-content-center">
          <div class="col-lg-8">
            <div class="ratio ratio-16x9 rounded-4 overflow-hidden shadow-lg">
              <iframe src="https://www.youtube.com/embed/jXMwY2-ejyc?rel=0" title="Live Stream" allowfullscreen style="border:none;" loading="lazy"></iframe>
            </div>
          </div>
        </div>
        <div class="mt-4">
          <a href="https://youtube.com" target="_blank" class="btn btn-danger btn-lg"><i class="fa-brands fa-youtube me-2"></i>Subscribe on YouTube</a>
        </div>
      </div>
    </section>

    <section v-if="ministries.length" class="website-section" style="background:var(--bg-section);">
      <div class="container">
        <h2 class="fw-bold mb-2 text-center">Our Ministries</h2>
        <p class="text-center text-muted mb-5">There&rsquo;s a place for everyone to grow, serve, and belong</p>
        <div class="row g-4">
          <div v-for="(m, i) in ministries" :key="m.min_id" class="col-lg-4 col-md-6 animate-on-scroll anim-zoom" :style="{ transitionDelay: i * .08 + 's' }">
            <div class="card ministry-card shadow-sm h-100">
              <div class="card-body text-center p-4">
                <div v-if="m.min_image_url" class="ministry-img mb-3">
                  <img :src="m.min_image_url" :alt="m.min_title" class="img-fluid rounded-3" style="height:100px;width:100px;object-fit:cover;">
                </div>
                <div v-else class="ministry-icon" :style="{ '--min-bg': m.min_bg_color || '#e3f2fd' }"><i :class="m.min_icon || 'fa-solid fa-hand-holding-heart'"></i></div>
                <h5 class="fw-bold mt-3">{{ m.min_title }}</h5>
                <p class="text-muted small mb-0">{{ m.min_description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section v-if="featured" class="website-section">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-lg-6 mb-4 mb-lg-0 animate-on-scroll" ref="el1">
            <span class="badge bg-primary mb-2"><i class="fa-solid fa-star me-1"></i>Featured Sermon</span>
            <h2 class="fw-bold">{{ featured.serm_title }}</h2>
            <div class="d-flex flex-wrap gap-3 text-secondary mb-3">
              <span v-if="featured.serm_speaker"><i class="fa-solid fa-user me-1"></i>{{ featured.serm_speaker }}</span>
              <span v-if="featured.serm_date"><i class="fa-solid fa-calendar me-1"></i>{{ formatDate(featured.serm_date) }}</span>
              <span v-if="featured.serm_scripture"><i class="fa-solid fa-book-bible me-1"></i>{{ featured.serm_scripture }}</span>
            </div>
            <p>{{ truncate(featured.serm_description, 300) }}</p>
            <router-link :to="'/sermons/' + featured.serm_id" class="btn btn-primary"><i class="fa-solid fa-play me-2"></i>Listen Now</router-link>
          </div>
          <div class="col-lg-6 animate-on-scroll" ref="el2">
            <div v-if="featured.serm_image_url" class="bg-light rounded-4 d-flex align-items-center justify-content-center shadow-sm" style="height:380px;">
              <img :src="featured.serm_image_url" :alt="featured.serm_title" class="img-fluid rounded-4 w-100 h-100" style="object-fit:cover;">
            </div>
            <div v-else class="bg-light rounded-4 d-flex align-items-center justify-content-center shadow-sm" style="height:380px;">
              <div class="text-center text-secondary">
                <i class="fa-solid fa-headphones fa-4x mb-2" style="opacity:.4;"></i>
                <p class="mb-0 small">Featured Sermon</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section class="website-section">
      <div class="container">
        <div class="d-flex align-items-center justify-content-between mb-4">
          <h2 class="fw-bold mb-0">Latest Sermons</h2>
          <router-link to="/sermons" class="btn btn-outline-primary btn-sm">View All <i class="fa-solid fa-arrow-right ms-1"></i></router-link>
        </div>
        <div class="row">
          <div v-for="(s, i) in latestSermons" :key="s.serm_id" class="col-md-4 mb-4 animate-on-scroll anim-zoom" :style="{ transitionDelay: i * .1 + 's' }" :ref="'sermon' + i">
            <div class="card sermon-card shadow-sm">
              <div v-if="s.serm_image_url" class="overflow-hidden rounded-top"><img :src="s.serm_image_url" class="card-img-top" :alt="s.serm_title"></div>
              <div v-else class="card-img-top d-flex align-items-center justify-content-center bg-light" style="height:200px;">
                <i class="fa-solid fa-headphones fa-3x text-secondary" style="opacity:.4;"></i>
              </div>
              <div class="card-body">
                <h5 class="card-title">{{ s.serm_title }}</h5>
                <div class="text-secondary small mb-2">{{ s.serm_speaker ? s.serm_speaker + ' · ' : '' }}{{ formatDate(s.serm_date) }}</div>
                <p class="card-text">{{ truncate(s.serm_description, 120) }}</p>
                <router-link :to="'/sermons/' + s.serm_id" class="btn btn-sm btn-primary">View Sermon</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section v-if="latestVideos.length" class="website-section">
      <div class="container">
        <div class="d-flex align-items-center justify-content-between mb-4">
          <h2 class="fw-bold mb-0">Recent Videos</h2>
          <router-link to="/videos" class="btn btn-outline-primary btn-sm">View All <i class="fa-solid fa-arrow-right ms-1"></i></router-link>
        </div>
        <div class="row">
          <div v-for="(v, i) in latestVideos" :key="v.vid_id" class="col-md-4 mb-4 animate-on-scroll anim-flip" :style="{ transitionDelay: i * .1 + 's' }">
            <div class="card video-card shadow-sm">
              <div v-if="v.vid_thumbnail_url" class="overflow-hidden rounded-top"><img :src="v.vid_thumbnail_url" class="card-img-top" :alt="v.vid_title"></div>
              <div v-else class="d-flex align-items-center justify-content-center bg-light" style="height:200px;">
                <i class="fa-solid fa-video fa-3x text-secondary" style="opacity:.4;"></i>
              </div>
              <div class="card-body">
                <h5 class="card-title">{{ v.vid_title }}</h5>
                <p class="text-secondary small">{{ formatDate(v.vid_date) }}</p>
                <p class="card-text">{{ truncate(v.vid_description, 120) }}</p>
                <a v-if="v.vid_url" :href="v.vid_url" target="_blank" class="btn btn-sm btn-primary"><i class="fa-solid fa-play me-1"></i>Watch</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section v-if="events.length" class="website-section">
      <div class="container">
        <h2 class="fw-bold mb-2 text-center">Upcoming Events</h2>
        <p class="text-center text-muted mb-5">Join us for these special gatherings and activities</p>
        <div class="row g-4">
          <div v-for="(ev, i) in events" :key="ev.evt_id" class="col-md-4 animate-on-scroll" :class="i % 2 === 0 ? 'anim-left' : 'anim-right'" :style="{ transitionDelay: i * .1 + 's' }">
            <div class="card event-card shadow-sm h-100">
              <div class="event-date" :style="{ background: ev.evt_color || '#0d6efd' }">
                <span class="event-month">{{ formatMonth(ev.evt_date) }}</span>
                <span class="event-day">{{ formatDay(ev.evt_date) }}</span>
              </div>
              <div class="card-body">
                <span class="badge mb-2" :style="{ background: (ev.evt_color || '#0d6efd') + '22', color: ev.evt_color || '#0d6efd' }">{{ ev.evt_category || 'General' }}</span>
                <h5 class="fw-bold">{{ ev.evt_title }}</h5>
                <p class="text-muted small mb-2"><i class="fa-regular fa-clock me-1"></i>{{ ev.evt_time || 'TBA' }}</p>
                <p class="text-muted small">{{ truncate(ev.evt_description, 150) }}</p>
                <a v-if="ev.evt_link" :href="ev.evt_link" target="_blank" class="btn btn-sm btn-outline-primary">Learn More</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section v-if="answeredPrayers.length" class="website-section">
      <div class="container">
        <h2 class="fw-bold mb-4 text-center">Testimonies</h2>
        <p class="text-center text-secondary mb-5">Hear what God is doing in our community.</p>
        <div class="row">
          <div v-for="p in answeredPrayers" :key="p.pray_id" class="col-md-6 mb-3">
            <div class="card prayer-card shadow-sm">
              <div class="card-body">
                <p class="card-text"><em>"{{ truncate(p.pray_request, 200) }}"</em></p>
                <div v-if="p.pray_answer_notes" class="mt-2 p-3 bg-success bg-opacity-10 rounded">
                  <strong class="text-success"><i class="fa-solid fa-check-circle me-1"></i>Testimony:</strong> {{ p.pray_answer_notes }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section class="website-section give-section text-center">
      <div class="container">
        <div class="row justify-content-center">
          <div class="col-lg-8 animate-up">
            <i class="fa-solid fa-hand-holding-heart give-icon"></i>
            <h2 class="fw-bold mb-3">Support Our Ministry</h2>
            <p class="lead text-muted mb-4">Your generous giving helps us share God&rsquo;s love with our community and beyond. Every gift makes a difference.</p>
            <div class="d-flex justify-content-center gap-3 flex-wrap">
              <a href="#" class="btn btn-primary btn-lg"><i class="fa-solid fa-heart me-2"></i>Give Online</a>
              <router-link to="/contact" class="btn btn-outline-primary btn-lg"><i class="fa-solid fa-envelope me-2"></i>Get in Touch</router-link>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section class="website-section connect-section">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-lg-6 mb-4 mb-lg-0 animate-on-scroll">
            <h2 class="fw-bold mb-2">Stay Connected</h2>
            <p class="text-muted mb-4">Sign up for our weekly newsletter and never miss an update on sermons, events, and community news.</p>
            <form class="row g-2" @submit.prevent>
              <div class="col-sm-8"><input type="email" class="form-control form-control-lg" placeholder="Your email address" required></div>
              <div class="col-sm-4"><button type="submit" class="btn btn-primary w-100 btn-lg"><i class="fa-solid fa-paper-plane me-2"></i>Subscribe</button></div>
            </form>
            <div class="mt-4">
              <p class="text-muted small mb-2">Follow us on social media</p>
              <div class="d-flex gap-2">
                <a href="#" class="social-link-lg" title="Facebook"><i class="fa-brands fa-facebook-f"></i></a>
                <a href="#" class="social-link-lg" title="Instagram"><i class="fa-brands fa-instagram"></i></a>
                <a href="#" class="social-link-lg" title="YouTube"><i class="fa-brands fa-youtube"></i></a>
                <a href="#" class="social-link-lg" title="X"><i class="fa-brands fa-x-twitter"></i></a>
              </div>
            </div>
          </div>
          <div class="col-lg-5 offset-lg-1 animate-on-scroll">
            <div class="bg-light rounded-4 d-flex align-items-center justify-content-center shadow-sm" style="height:300px;">
              <div class="text-center text-secondary p-4">
                <i class="fa-solid fa-church fa-4x mb-3" style="opacity:.3;"></i>
                <p class="fw-bold mb-1">{{ info.name || 'Our Church' }}</p>
                <p class="small mb-0">{{ info.address || '123 Church Street' }}<br>{{ info.city }}, {{ info.state }} {{ info.zip }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { getFeaturedSermon, getSermons, getVideos, getAnsweredPrayers, getChurchInfo, getEvents, getMinistries } from '../api/index.js'

const info = ref({})
const featured = ref(null)
const latestSermons = ref([])
const latestVideos = ref([])
const answeredPrayers = ref([])
const events = ref([])
const current = ref(0)
const countdown = ref({ days: 0, hours: 0, minutes: 0, seconds: 0 })
let timer
let countdownTimer

function updateCountdown() {
  const now = new Date()
  const nextSun = new Date(now)
  nextSun.setDate(now.getDate() + (7 - now.getDay()) % 7)
  nextSun.setHours(9, 0, 0, 0)
  if (now.getDay() === 0 && now.getHours() >= 9) nextSun.setDate(nextSun.getDate() + 7)
  const diff = Math.max(0, Math.floor((nextSun - now) / 1000))
  countdown.value = {
    days: Math.floor(diff / 86400),
    hours: Math.floor((diff % 86400) / 3600),
    minutes: Math.floor((diff % 3600) / 60),
    seconds: diff % 60,
  }
}

const ministries = ref([])

const slides = [
  { title: 'Welcome to {name}', subtitle: 'We are a community of faith, hope, and love. Join us as we grow together in Christ.', btnText: 'Watch Sermons', btnLink: '/sermons', btnIcon: 'fa-solid fa-headphones', bgImage: 'https://images.unsplash.com/photo-1438232992991-995b7058bbb3?w=1600&q=80' },
  { title: 'Join Us in Worship', subtitle: 'Experience the joy of worshiping together every Sunday morning.', btnText: 'Service Times', btnLink: '/about', btnIcon: 'fa-solid fa-clock', bgImage: 'https://images.unsplash.com/photo-1477067292052-5516f32e3c88?w=1600&q=80' },
  { title: 'Growing Together in Faith', subtitle: 'Discover the power of community and deepen your relationship with God.', btnText: 'Prayer Requests', btnLink: '/prayer', btnIcon: 'fa-solid fa-hands-praying', bgImage: 'https://images.unsplash.com/photo-1529156069898-49953e39b3ac?w=1600&q=80' },
  { title: 'A Community of Love', subtitle: 'Everyone is welcome. Come as you are and experience God\'s love.', btnText: 'Contact Us', btnLink: '/contact', btnIcon: 'fa-solid fa-envelope', bgImage: 'https://images.unsplash.com/photo-1504384308090-c894fdcc538d?w=1600&q=80' },
]

function next() { current.value = (current.value + 1) % slides.length; resetTimer() }
function prev() { current.value = (current.value - 1 + slides.length) % slides.length; resetTimer() }
function resetTimer() { clearInterval(timer); timer = setInterval(() => { current.value = (current.value + 1) % slides.length }, 6000) }

function formatDate(d) {
  return d ? new Date(d + 'T00:00:00').toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : ''
}
function formatMonth(d) {
  return d ? new Date(d + 'T00:00:00').toLocaleDateString('en-US', { month: 'short' }).toUpperCase() : ''
}
function formatDay(d) {
  return d ? new Date(d + 'T00:00:00').getDate() : ''
}
function truncate(s, n) { return s ? (s.length > n ? s.slice(0, n) + '...' : s) : '' }

onMounted(async () => {
  try {
    info.value = await getChurchInfo()
    const [f, serm, vid, pray, evts, mins] = await Promise.all([
      getFeaturedSermon(), getSermons(3), getVideos(3), getAnsweredPrayers(),
      getEvents(3).catch(() => ({ events: [] })),
      getMinistries().catch(() => ({ ministries: [] }))
    ])
    featured.value = f.sermon
    latestSermons.value = serm.sermons
    latestVideos.value = vid.videos
    answeredPrayers.value = pray.prayers
    events.value = evts.events || []
    ministries.value = mins.ministries || []
  } catch (e) {}
  updateCountdown()
  countdownTimer = setInterval(updateCountdown, 1000)
  resetTimer()
  nextTick(observe)
})
onUnmounted(() => { clearInterval(timer); clearInterval(countdownTimer) })

function observe() {
  const els = document.querySelectorAll('.animate-on-scroll')
  if ('IntersectionObserver' in window) {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) { e.target.classList.add('visible'); obs.unobserve(e.target) }
      })
    }, { threshold: .15 })
    els.forEach(el => obs.observe(el))
  } else { els.forEach(el => el.classList.add('visible')) }
}
</script>
