"use client"

import { useState } from "react"
import Link from "next/link"
import { siteConfig, toolPages } from "@/lib/data"
import { ChevronRight } from "lucide-react"

export function Footer() {
  const [email, setEmail] = useState("")
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<{title: string, desc: string, isError: boolean} | null>(null)

    const handleSubscribe = async (e: React.FormEvent) => {
    e.preventDefault()

    const trimmedEmail = email.trim()

    if (!trimmedEmail) {
      setResult({
        title: "Subscription failed",
        desc: "Please enter your email address.",
        isError: true
      })
      return
    }

    setLoading(true)
    setResult(null)

    try {
      const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:8080"

      const response = await fetch(`${backendUrl}/api/newsletter/subscribe`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: trimmedEmail,
          source: "footer",
        }),
      })

      const data = await response.json()

      if (!response.ok) {
        setResult({
          title: "Subscription failed",
          desc: data.message || data.error || "Please try again later.",
          isError: true
        })
        return
      }

      setResult({
        title: "Subscribed successfully!",
        desc: "Thank you for subscribing.",
        isError: false
      })

      setEmail("")
    } catch (error) {
      console.error("Newsletter subscription error:", error)

      setResult({
        title: "Subscription failed",
        desc: "Something went wrong. Please try again later.",
        isError: true
      })
    } finally {
      setLoading(false)

      setTimeout(() => {
        setResult(null)
      }, 1500)
    }
  }

  return (
    <footer className="bg-[#020617] text-slate-400 border-t border-primary/20 relative overflow-hidden">
      {/* CSS for changing color text */}
      <style>{`
        @keyframes colorChange {
          0% { color: #0D9488; } /* Primary Teal */
          33% { color: #06B6D4; } /* Cyan */
          66% { color: #10B981; } /* Emerald */
          100% { color: #0D9488; }
        }
        .changing-color-text {
          animation: colorChange 6s infinite ease-in-out;
        }
      `}</style>

      {/* Subtle top glow */}
      <div className="absolute top-0 left-1/2 -translate-x-1/2 w-full max-w-2xl h-px bg-gradient-to-r from-transparent via-primary/50 to-transparent shadow-[0_0_20px_rgba(var(--primary),0.3)]" />

      <div className="mx-auto max-w-7xl px-4 py-12 lg:px-8 relative z-10">
        {/* Changed from grid to flex with justify-start to pull columns close to the left */}
        <div className="flex flex-col md:flex-row flex-wrap gap-x-8 gap-y-10 justify-start text-sm">
          
          {/* Column 1: Brand & Contact */}
          <div className="space-y-4 max-w-[260px]">
            <h2 className="text-xl font-bold uppercase tracking-wider changing-color-text">{siteConfig.name}</h2>
            
            <div className="space-y-2 text-slate-400">
              <p>204, Alpha Analytics Services Pvt. Ltd.</p>
              <p>18 High street baner pashan link road, Baner, Pune, India-411045</p>
              <p className="pt-2">
                <span className="font-bold text-white">Email:</span>{" "}
                <a href={`mailto:${siteConfig.contact.email}`} className="hover:text-primary transition-colors">
                  {siteConfig.contact.email}
                </a>
              </p>
            </div>

            {/* Social Icons */}
            <div className="flex gap-3 pt-2">
              <a href="https://x.com/codeframeai" target="_blank" rel="noopener noreferrer" className="h-9 w-9 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-slate-400 hover:bg-primary hover:text-white hover:border-primary transition-colors" aria-label="X (Twitter)">
                <svg viewBox="0 0 24 24" className="w-4 h-4" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 22.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.008 5.965H5.078z" /></svg>
              </a>
              <a href="https://www.facebook.com/CodeframeAI/" target="_blank" rel="noopener noreferrer" className="h-9 w-9 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-slate-400 hover:bg-primary hover:text-white hover:border-primary transition-colors" aria-label="Facebook">
                <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/></svg>
              </a>
              <a href="https://www.instagram.com/codeframe.ai/" target="_blank" rel="noopener noreferrer" className="h-9 w-9 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-slate-400 hover:bg-primary hover:text-white hover:border-primary transition-colors" aria-label="Instagram">
                <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="20" x="2" y="2" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" x2="17.51" y1="6.5" y2="6.5"/></svg>
              </a>
              <a href="https://www.linkedin.com/company/codeframe-ai/" target="_blank" rel="noopener noreferrer" className="h-9 w-9 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-slate-400 hover:bg-primary hover:text-white hover:border-primary transition-colors" aria-label="LinkedIn">
                <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/><rect width="4" height="12" x="2" y="9"/><circle cx="4" cy="4" r="2"/></svg>
              </a>
              <a href="#" target="_blank" rel="noopener noreferrer" className="h-9 w-9 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-zinc-400 hover:bg-primary hover:text-white hover:border-primary transition-colors" aria-label="Reddit">
                <svg viewBox="0 0 24 24" className="w-4 h-4" fill="currentColor"><path d="M22 11.5c0-1.38-1.12-2.5-2.5-2.5-.66 0-1.25.26-1.69.68C16.03 8.65 14.15 8 12.06 8l1.32-6.22 4.31.91c.05 1.15 1.01 2.06 2.18 2.06 1.21 0 2.19-.98 2.19-2.19 0-1.21-.98-2.19-2.19-2.19-.94 0-1.74.59-2.06 1.41l-4.73-1-.38 1.83-.87 4.09c-2.12.04-4.04.72-5.78 1.76-.44-.43-1.04-.69-1.7-.69-1.38 0-2.5 1.12-2.5 2.5 0 .97.55 1.81 1.35 2.21-.06.27-.09.55-.09.83 0 3.86 4.39 7 9.8 7s9.8-3.14 9.8-7c0-.28-.03-.56-.09-.83.8-.4 1.35-1.24 1.35-2.21zm-15.5 2.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5-.67 1.5-1.5 1.5-1.5-.67-1.5-1.5zm8.9 4.19c-1.1.75-2.73.94-3.5.94-.78 0-2.4-.19-3.5-.94-.25-.17-.31-.51-.14-.76.17-.25.51-.31.76-.14.88.6 2.16.84 2.88.84.71 0 1.99-.24 2.88-.84.25-.17.59-.11.76.14.17.25.11.59-.14.76zm-.4-2.69c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/></svg>
              </a>
            </div>
          </div>

          {/* Column 2: Useful Links */}
          <div className="min-w-[150px]">
            <h3 className="text-base font-bold text-white mb-4">Useful Links</h3>
            <ul className="space-y-2">
              {[
                { name: "Home", href: "/" },
                { name: "About us", href: "/#about" },
                { name: "Services", href: "/#products" },
                { name: "Feedback", href: "/feedback" },
                { name: "Terms of service", href: "https://app.codeframeai.com/#/terms-and-conditions" },
                { name: "Privacy policy", href: "https://app.codeframeai.com/#/privacy-policy" }
              ].map((link) => (
                <li key={link.name}>
                  {link.href.startsWith('http') ? (
                    <a 
                      href={link.href} 
                      target="_blank" 
                      rel="noopener noreferrer" 
                      className="flex items-center gap-2 hover:text-white transition-colors group"
                    >
                      <ChevronRight className="h-4 w-4 text-primary group-hover:translate-x-1 transition-transform" />
                      {link.name}
                    </a>
                  ) : (
                    <Link href={link.href} className="flex items-center gap-2 hover:text-white transition-colors group">
                      <ChevronRight className="h-4 w-4 text-primary group-hover:translate-x-1 transition-transform" />
                      {link.name}
                    </Link>
                  )}
                </li>
              ))}
            </ul>
          </div>

          {/* Column 3: Our Services */}
          <div className="min-w-[180px]">
            <h3 className="text-base font-bold text-white mb-4">Our Services</h3>
            <ul className="space-y-2">
              {toolPages.slice(0, 5).map((tool) => (
                <li key={tool.slug}>
                  <Link href={`/${tool.slug}`} className="flex items-center gap-2 hover:text-white transition-colors group">
                    <ChevronRight className="h-4 w-4 text-primary group-hover:translate-x-1 transition-transform" />
                    {tool.title}
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          {/* Column 4: Our Newsletter */}
          <div className="max-w-[300px]">
            <h3 className="text-base font-bold text-white mb-4">Our Newsletter</h3>
            <p className="text-slate-400 leading-relaxed mb-4">
              Subscribe to our newsletter and receive the latest news about our products and services!
            </p>
            
            <form onSubmit={handleSubscribe} className="flex flex-col gap-3">
              <div className="flex flex-col sm:flex-row gap-2">
                <input
                  type="email"
                  placeholder="Enter your email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="flex-1 px-4 py-2.5 bg-white/5 border border-white/10 rounded-lg text-white placeholder:text-slate-600 focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all text-sm"
                  required
                />
                {!result && (
                  <button 
                    type="submit"
                    disabled={loading}
                    className="px-6 py-2.5 bg-primary hover:bg-primary/90 text-white font-bold rounded-lg transition-colors text-sm shadow-lg shadow-primary/20 disabled:opacity-50"
                  >
                    {loading ? "..." : "Subscribe"}
                  </button>
                )}
              </div>
              
              {result && (
                <div className={`p-3 rounded-lg text-xs border animate-in fade-in duration-200 ${result.isError ? "bg-destructive/10 text-destructive border-destructive/20" : "bg-primary/10 text-primary border-primary/20"}`}>
                  <strong>{result.title}</strong>
                  <p className="mt-1 opacity-90">{result.desc}</p>
                </div>
              )}
            </form>
          </div>

        </div>

        {/* Copyright */}
        <div className="mt-12 pt-6 border-t border-white/5 text-center text-xs text-slate-600">
          <p>© {new Date().getFullYear()} {siteConfig.name}. All rights reserved.</p>
        </div>
      </div>
    </footer>
  )
}
