import { useState, type FC } from 'react'
import { Link } from 'react-router-dom'
import { MapPin, Phone, Mail, ChevronsUp } from 'lucide-react'
import { BASE } from '@/context/AuthContext'

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

/* curved top edge with a centered scroll-to-top button (matches the Figma) */
function FooterCurve() {
  return (
    <div style={{ position: 'relative', height: 64, lineHeight: 0, background: 'var(--paper, #fff)' }}>
      <svg viewBox="0 0 1440 64" preserveAspectRatio="none" width="100%" height="64" style={{ display: 'block' }}>
        <path
          d="M0,0 L132,0 C192,0 206,52 240,52 C274,52 288,0 348,0 L1440,0 L1440,64 L0,64 Z"
          fill="#032340"
        />
      </svg>
      {/* scroll-to-top button sitting in the dip (left side) */}
      <button
        onClick={scrollToTop}
        aria-label="بازگشت به بالا"
        style={{
          position: 'absolute', top: 8, left: '16.7%', transform: 'translateX(-50%)',
          width: 40, height: 40, borderRadius: '50%', cursor: 'pointer',
          background: '#032340', border: '2px solid rgba(255,255,255,0.25)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'transform 180ms, background 180ms',
        }}
        onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.transform = 'translateX(-50%) translateY(-3px)'; (e.currentTarget as HTMLElement).style.background = '#CD9E53' }}
        onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.transform = 'translateX(-50%)'; (e.currentTarget as HTMLElement).style.background = '#032340' }}
      >
        <ChevronsUp size={20} color="#fff" strokeWidth={2.5} />
      </button>
    </div>
  )
}

const NAVY = '#032340'
const GOLD = '#CD9E53'

/* brand glyphs — lucide has no brand icons, so inline SVGs; fill follows currentColor (= NAVY) */
type IconProps = { size?: number }

const TelegramIcon: FC<IconProps> = ({ size = 18 }) => (
  <svg viewBox="0 0 24 24" width={size} height={size} fill="currentColor" aria-hidden="true">
    <path d="M9.78 18.65l.28-4.23 7.68-6.92c.34-.31-.07-.46-.52-.19L7.74 13.3 3.64 12c-.88-.25-.89-.86.2-1.3l15.97-6.16c.73-.33 1.43.18 1.15 1.3l-2.72 12.81c-.19.91-.74 1.13-1.5.71L12.6 16.3l-1.99 1.93c-.23.23-.42.42-.83.42z" />
  </svg>
)

const XIcon: FC<IconProps> = ({ size = 16 }) => (
  <svg viewBox="0 0 24 24" width={size} height={size} fill="currentColor" aria-hidden="true">
    <path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z" />
  </svg>
)

const LinkedinIcon: FC<IconProps> = ({ size = 18 }) => (
  <svg viewBox="0 0 24 24" width={size} height={size} fill="currentColor" aria-hidden="true">
    <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
  </svg>
)

const AparatIcon: FC<IconProps> = ({ size = 19 }) => (
  <svg viewBox="0 0 100 100" width={size} height={size} fill="currentColor" aria-hidden="true">
    <defs>
      <mask id="aparat-mask">
        {/* show everything white by default */}
        <rect width="100" height="100" fill="white" />
        {/* cut gap between outer petals and inner disc */}
        <circle cx="50" cy="50" r="44" fill="black" />
        {/* restore the disc */}
        <circle cx="50" cy="50" r="41" fill="white" />
        {/* punch 4 holes + center in disc */}
        <circle cx="34" cy="34" r="10" fill="black" />
        <circle cx="66" cy="34" r="10" fill="black" />
        <circle cx="34" cy="66" r="10" fill="black" />
        <circle cx="66" cy="66" r="10" fill="black" />
        <circle cx="50" cy="50" r="5"  fill="black" />
      </mask>
    </defs>
    {/* full square → mask reveals: 4 corner petals + reel with holes */}
    <rect width="100" height="100" rx="22" mask="url(#aparat-mask)" />
  </svg>
)

/* round social buttons (gold filled, like the screenshot) */
const SOCIALS: { Icon: FC<IconProps>; name: string; href: string }[] = [
  { Icon: AparatIcon,   name: 'آپارات',   href: '#' },
  { Icon: XIcon,        name: 'X',        href: '#' },
  { Icon: LinkedinIcon, name: 'لینکداین', href: '#' },
  { Icon: TelegramIcon, name: 'تلگرام',   href: '#' },
]

function SocialIcon({ Icon, name, href }: { Icon: FC<IconProps>; name: string; href: string }) {
  const [hovered, setHovered] = useState(false)
  return (
    <a
      href={href} target="_blank" rel="noopener noreferrer" aria-label={name} title={name}
      onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}
      style={{
        width: 42, height: 42, borderRadius: '50%', flexShrink: 0,
        background: GOLD, color: NAVY, display: 'flex', alignItems: 'center', justifyContent: 'center',
        textDecoration: 'none', cursor: 'pointer', transition: 'transform 150ms, opacity 150ms',
        transform: hovered ? 'translateY(-3px)' : 'none', opacity: hovered ? 0.9 : 1,
      }}
    >
      <Icon />
    </a>
  )
}

/* center nav — the navbar items */
const NAV_LINKS = [
  { label: 'رادار آینده',    href: '/radar' },
  { label: 'آمار و داده',    href: '/pulse' },
  { label: 'در یک نگاه',     href: '/at-a-glance' },
  { label: 'رسانه و رویداد', href: '/podcast' },
  { label: 'شبکه خبرگان',    href: '/experts' },
  { label: 'درباره ما',      href: '/about' },
]

function NavItem({ href, label }: { href: string; label: string }) {
  const [hovered, setHovered] = useState(false)
  return (
    <Link to={href}
      onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0',
        fontSize: 13.5, color: hovered ? '#fff' : 'rgba(255,255,255,0.6)',
        textDecoration: 'none', transition: 'color 150ms', flexDirection: 'row-reverse', justifyContent: 'flex-end',
      }}
    >
      {label}
      <span style={{ width: 4, height: 4, borderRadius: '50%', background: GOLD, flexShrink: 0 }} />
    </Link>
  )
}

/* contact rows */
const CONTACT = [
  { Icon: MapPin, label: 'نشانی:', value: 'تهران، خیابان کارگر شمالی، پارک علم و فناوری دانشگاه تهران، مرکز نوآوری تحول دیجیتال صنعت فولاد کشور' },
  { Icon: Phone,  label: 'شماره تماس:', value: '۰۲۱-۱۲۳۴۵۶۷', ltr: true },
  { Icon: Mail,   label: 'پست الکترونیک:', value: 'info@steelforesight.com', ltr: true, accent: true },
]

function NewsletterBox() {
  const [email, setEmail] = useState('')
  const [done, setDone] = useState(false)
  const [busy, setBusy] = useState(false)
  const [err, setErr] = useState('')

  const submit = async () => {
    const e = email.trim()
    if (!e || busy) return
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) { setErr('ایمیل نامعتبر است'); return }
    setBusy(true); setErr('')
    try {
      const res = await fetch(`${BASE}/api/newsletter`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: e }),
      })
      if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'خطا در ثبت')
      setDone(true)
    } catch (x) {
      setErr(x instanceof Error ? x.message : 'خطا در ثبت')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 700, color: '#fff', marginBottom: 12 }}>عضویت در خبرنامه اندیشکده</div>
      <div style={{ display: 'flex', border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8, overflow: 'hidden', background: 'rgba(255,255,255,0.05)' }}>
        <input
          type="email" value={email}
          onChange={e => { setEmail(e.target.value); if (err) setErr('') }}
          onKeyDown={e => e.key === 'Enter' && submit()}
          placeholder="ایمیل خود را وارد کنید..." disabled={done}
          style={{
            flex: 1, border: 'none', padding: '11px 14px', fontSize: 13, fontFamily: 'inherit',
            background: 'transparent', color: '#fff', outline: 'none', direction: 'rtl', minWidth: 0,
          }}
        />
        <button
          onClick={submit} disabled={done || busy}
          style={{
            background: GOLD, color: NAVY, border: 'none', padding: '11px 22px',
            fontSize: 12, fontWeight: 800, fontFamily: 'inherit', cursor: (done || busy) ? 'default' : 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
          }}
        >
          {done ? '✓ ثبت شد' : busy ? '...' : 'ثبت'}
        </button>
      </div>
      {err && <div style={{ fontSize: 11, color: '#fca5a5', marginTop: 6 }}>{err}</div>}
    </div>
  )
}

export function Footer() {
  return (
    <footer dir="rtl" style={{ color: 'rgba(255,255,255,0.6)' }}>
      <FooterCurve />
      <div style={{ backgroundColor: NAVY, maxWidth: '100%' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '40px 48px 48px' }} className="max-md:!px-6 max-md:!py-10">

        <div className="grid grid-cols-[1.3fr_0.8fr_1.2fr] max-lg:grid-cols-2 max-md:grid-cols-1 gap-12 max-md:gap-10">

          {/* ── BRAND (right side in RTL) ── */}
          <div style={{ textAlign: 'center', position: 'relative', left: 100 }} className="max-md:!left-0">
            <img src="/logo%20white.png" alt="اندیشکده فولاد آینده" style={{ height: 96, width: 'auto', display: 'block', margin: '0 auto 14px' }} />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12, marginBottom: 4 }}>
              <span style={{ height: 2, width: 28, background: 'linear-gradient(to left, #3b82f6, transparent)', borderRadius: 2 }} />
              <span style={{ fontSize: 22, fontWeight: 900, color: '#fff', lineHeight: 1.3, whiteSpace: 'nowrap' }}>اندیشکده فولاد آینده</span>
              <span style={{ height: 2, width: 28, background: 'linear-gradient(to right, #3b82f6, transparent)', borderRadius: 2 }} />
            </div>
            <div style={{ fontSize: 10, letterSpacing: 2, color: 'rgba(255,255,255,0.35)', textTransform: 'uppercase', marginBottom: 18 }}>The Steel Futures Institute</div>

            <p style={{
              fontSize: 13, lineHeight: 2, color: 'rgba(255,255,255,0.62)',
              border: '1px solid rgba(255,255,255,0.15)', borderRadius: 14, padding: '16px 18px', margin: '0 0 26px',
            }}>
              فضایی همدلانه برای اندیشیدن به فردای صنعت؛ جایی که دانش، پژوهش و نوآوری به بینش‌هایی برای توسعه صنعتی تبدیل می‌شوند.
            </p>

            <div style={{ fontSize: 13, fontWeight: 700, color: '#fff', marginBottom: 14 }}>ما را در شبکه‌های اجتماعی دنبال کنید.</div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
              {SOCIALS.map((s) => (
                <SocialIcon key={s.name} Icon={s.Icon} name={s.name} href={s.href} />
              ))}
            </div>
          </div>

          {/* ── NAV (center) ── */}
          <nav aria-label="پیوندهای پایین" style={{ display: 'flex', flexDirection: 'column' }}>
            {NAV_LINKS.map((l) => (
              <NavItem key={l.label} href={l.href} label={l.label} />
            ))}
          </nav>

          {/* ── CONTACT + badges + newsletter (left side in RTL) ── */}
          <div>
            <div style={{ fontSize: 14, fontWeight: 800, color: '#fff', marginBottom: 18 }}>اطلاعات تماس</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 26 }}>
              {CONTACT.map((c) => (
                <div key={c.label} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 13 }}>
                  <c.Icon size={15} color={GOLD} style={{ flexShrink: 0, marginTop: 4 }} />
                  <span style={{ color: 'rgba(255,255,255,0.45)', flexShrink: 0 }}>{c.label}</span>
                  <span style={{ color: c.accent ? GOLD : 'rgba(255,255,255,0.75)', direction: c.ltr ? 'ltr' : 'rtl', lineHeight: 1.9 }}>{c.value}</span>
                </div>
              ))}
            </div>

            {/* certification badges — etehadie from Figma; samandehi/enamad await their assets */}
            <div style={{ display: 'flex', gap: 12, marginBottom: 26 }}>
              {[
                { img: '/trust-etehadie.png', alt: 'اتحادیه کشوری کسب و کارهای مجازی', href: 'https://ecunion.ir', scale: 1.35 },
                { img: '/trust-samandehi.png', alt: 'نشان ملی ثبت (رسانه‌های دیجیتال) - ساماندهی', href: 'https://samandehi.ir', scale: 1 },
                { img: '/trust-enamad.png', alt: 'نماد اعتماد الکترونیکی', href: 'https://enamad.ir', scale: 1 },
              ].map((b, i) => (
                <a key={i} href={b.href} target="_blank" rel="noopener noreferrer" aria-label={b.alt}
                  style={{ width: 66, height: 66, borderRadius: 10, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, overflow: 'hidden' }}>
                  {b.img
                    ? <img src={b.img} alt={b.alt} style={{ width: '100%', height: '100%', objectFit: 'contain', transform: `scale(${b.scale})` }} />
                    : <span style={{ fontSize: 9, color: 'rgba(7,29,73,0.4)', fontWeight: 700 }}>نشان</span>}
                </a>
              ))}
            </div>

            <NewsletterBox />
          </div>
        </div>
      </div>
      </div>

      {/* copyright bar */}
      <div style={{ background: GOLD, color: NAVY }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '14px 48px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', fontSize: 12, fontWeight: 700 }}
             className="max-md:!px-6 max-md:!justify-center max-md:!text-center">
          <span>تمامی حقوق مادی و معنوی این وب‌سایت متعلق به <a href="https://www.msc.ir" target="_blank" rel="noopener noreferrer" style={{ color: NAVY, fontWeight: 900, textDecoration: 'underline' }}>شرکت فولاد مبارکه</a> می‌باشد.</span>
          <span style={{ opacity: 0.8 }}>طراح و پشتیبان؛ <a href="https://irfartak.com" target="_blank" rel="noopener noreferrer" style={{ color: NAVY, fontWeight: 900, textDecoration: 'underline' }}>شرکت دانش‌بنیان نواندیشان آتی نگار فرتاک</a></span>
        </div>
      </div>
    </footer>
  )
}
