'use client'

import { useState, useEffect } from 'react'
import ScrollReveal from './ScrollReveal'
import styles from './Contact.module.css'

export default function Contact() {
  const [count, setCount] = useState<number | null>(null)
  const [status, setStatus] = useState<'idle' | 'voting' | 'voted' | 'already'>('idle')

  // Check localStorage and fetch count on mount
  useEffect(() => {
    const hasVoted = localStorage.getItem('prime-declared')
    if (hasVoted) {
      setStatus('already')
    }

    fetch('/api/vote')
      .then(res => res.json())
      .then(data => setCount(data.count ?? 0))
      .catch(() => setCount(null))
  }, [])

  const handleVote = async () => {
    if (status === 'voted' || status === 'already' || status === 'voting') return

    setStatus('voting')

    try {
      const response = await fetch('/api/vote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })

      const data = await response.json()

      if (data.alreadyVoted) {
        setStatus('already')
      } else {
        setStatus('voted')
        localStorage.setItem('prime-declared', 'true')
      }

      setCount(data.count)
    } catch (error) {
      console.error('Vote error:', error)
      setStatus('idle')
    }
  }

  const isVoted = status === 'voted' || status === 'already'

  return (
    <section id="contact" className={styles.contact}>
      <div className={styles.container}>
        <div className={styles.content}>
          <ScrollReveal direction="left">
            <div className={styles.info}>
              <span className={styles.label}>JOIN THE MOVEMENT</span>
              <h2 className={styles.title}>
                Declare <span className="text-gradient">PRIME</span>
              </h2>
              <p className={styles.description}>
                No auditions. No permission. If you&apos;ve paid the cost, you&apos;re already in.
              </p>
              <div className={styles.links}>
                <a href="https://twitter.com/inmyprime_sol" target="_blank" rel="noopener noreferrer" className={styles.socialLink}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
                  </svg>
                  <span>@inmyprime_sol</span>
                </a>
                <a href="https://pump.fun/coin/D8WDarzRHYpW5VkbwiRTuWCLzerAdwFw5PNkivkYpump" target="_blank" rel="noopener noreferrer" className={styles.socialLink}>
                  <img src="/images/pumpfun.png" alt="Pump.fun" width="20" height="20" style={{ objectFit: 'contain' }} />
                  <span>Pump.fun</span>
                </a>
              </div>
            </div>
          </ScrollReveal>

          <ScrollReveal direction="right" delay={0.1}>
            <div className={styles.voter}>
              <button
                className={`${styles.voteButton} ${isVoted ? styles.voted : ''}`}
                onClick={handleVote}
                disabled={status === 'voting'}
              >
                {status === 'voting' ? (
                  <span className={styles.votingText}>DECLARING...</span>
                ) : isVoted ? (
                  <>
                    <span className={styles.checkmark}>✓</span>
                    <span>DECLARED</span>
                  </>
                ) : (
                  <span>DECLARE PRIME</span>
                )}
              </button>
              <p className={styles.voteCount}>
                {count !== null && count !== undefined ? (
                  <>
                    <span className={styles.countNumber}>{count.toLocaleString()}</span>
                    <span className={styles.countLabel}> declared</span>
                  </>
                ) : (
                  <span className={styles.countLabel}>Join the movement</span>
                )}
              </p>
            </div>
          </ScrollReveal>
        </div>
      </div>

      {/* Footer */}
      <footer className={styles.footer}>
        <ScrollReveal direction="fade">
          <div className={styles.footerContent}>
            <div className={styles.footerLogo}>
              <span className="text-gradient">PRIME</span>
            </div>
            <p className={styles.footerText}>
              Not stronger. Different.
            </p>
            <p className={styles.copyright}>
              &copy; {new Date().getFullYear()} PRIME. All rights reserved.
            </p>
          </div>
        </ScrollReveal>
      </footer>
    </section>
  )
}
