import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { FileDown } from 'lucide-react'
import { useLang } from '@/context/LangContext'

const NAVY = '#032340'
const GOLD = '#CD9E53'
const EASE = [0.22, 1, 0.36, 1] as const

type ScrollDir = 'left' | 'right' | 'up'
type Cover = { img: string; num: string; dir: ScrollDir; fileUrl?: string; title?: string }

/* static fallback — Figma covers; replaced at runtime by panel factory-reports */
const COVERS: Cover[] = [
  { img: '/factory/cover-1.png', num: '۵۵', dir: 'right' },
  { img: '/factory/cover-2.png', num: '۵۴', dir: 'up' },
  { img: '/factory/cover-3.png', num: '۵۳', dir: 'left' },
  { img: '/factory/cover-4.png', num: '۵۲', dir: 'up' },
  { img: '/factory/cover-5.png', num: '۵۱', dir: 'left' },
]

const FALLBACK_DIRS: ScrollDir[] = ['right', 'up', 'left', 'up', 'left']
// only allow http(s) or root-relative paths to reach a download href
const safeFile = (u: unknown): string | undefined =>
  typeof u === 'string' && (/^https?:\/\//i.test(u) || u.startsWith('/')) ? u : undefined

function ScrollAnimation({ children, direction = 'up' }: { children: React.ReactNode; direction?: ScrollDir }) {
  const offset =
    direction === 'left' ? { x: -50, y: 0 } :
    direction === 'right' ? { x: 50, y: 0 } :
    { x: 0, y: 50 }
  return (
    <motion.div
      initial={{ opacity: 0, ...offset }}
      whileInView={{ opacity: 1, x: 0, y: 0 }}
      viewport={{ once: true, amount: 0.35 }}
      transition={{ duration: 0.6, ease: EASE }}
      style={{ height: '100%' }}
    >
      {children}
    </motion.div>
  )
}

/* magazine card — gray panel with floating cover on top, title + download button below */
function ReportCard({ img, title, fileUrl, lang }: { img: string; title: string; fileUrl?: string; lang: 'fa' | 'en' }) {
  const label = lang === 'fa' ? 'دانلود ماهنامه' : 'Download'
  const Tag = fileUrl ? 'a' : 'div'
  const linkProps = fileUrl ? { href: fileUrl, download: true, target: '_blank', rel: 'noopener noreferrer' } : {}

  return (
    <Tag
      {...linkProps}
      style={{
      display: 'flex',
      flexDirection: 'column',
      background: '#F9F9F9',
      borderRadius: '24px',
      textDecoration: 'none',
      cursor: fileUrl ? 'pointer' : 'default',
      boxShadow: '0 12px 28px -20px rgba(7,29,73,0.3)',
      transition: 'transform 180ms, box-shadow 180ms',
      height: '100%',
      position: 'relative', // برای قرارگیری خط طلایی
      paddingBottom: '4px'  // ایجاد فضا برای خط طلایی
      }}
      onMouseEnter={(e) => { const d = e.currentTarget; d.style.transform = 'translateY(-4px)'; d.style.boxShadow = '0 20px 38px -22px rgba(7,29,73,0.4)' }}
      onMouseLeave={(e) => { const d = e.currentTarget; d.style.transform = 'translateY(0)'; d.style.boxShadow = '0 12px 28px -20px rgba(7,29,73,0.3)' }}
    >
      {/* تصویر */}
      <div style={{
      width: '100%',
      aspectRatio: '1 / 0.8',
      overflow: 'hidden',
      clipPath: 'polygon(0 0, 100% 20%, 100% 100%, 0 100%)',
      borderTopLeftRadius: '24px',
      borderTopRightRadius: '24px'
      }}>
      <img src={img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </div>

      {/* محتوا */}
      <div style={{ 
      padding: '16px 20px', 
      textAlign: 'right', 
      display: 'flex', 
      flexDirection: 'column', 
      flexGrow: 1 
      }}>
      <div style={{ fontSize: '18px', fontWeight: '800', color: '#000', marginBottom: 'auto' }}>
        {title}
      </div>
      
      <div style={{ 
        display: 'flex', 
        justifyContent: 'flex-end', 
        alignItems: 'center', 
        gap: '8px', 
        color: GOLD, 
        fontSize: '14px', 
        fontWeight: '700',
        marginTop: '16px'
      }}>
        <span>{label}</span>
        <FileDown size={18} />
      </div>
      </div>

      {/* خط طلایی کاملاً مستقل در پایین */}
      <div style={{ 
      position: 'absolute',
      bottom: 0,
      left: 0,
      width: '100%',
      height: '4px',
      backgroundColor: GOLD,
      borderRadius: '0 0 24px 24px'
      }} />
    </Tag>
  )
}

export default function FactoryReportsScroll() {
  const { lang } = useLang()
  const [covers, setCovers] = useState<Cover[]>(COVERS)

  // pull the monthly magazines from the panel; fall back to the static covers
  useEffect(() => {
    const PANEL_API = (import.meta as ImportMeta & { env?: Record<string, string> }).env?.VITE_PANEL_API || ''
    let alive = true
    fetch(`${PANEL_API}/api/factory-reports?limit=5`)
      .then(r => (r.ok ? r.json() : null))
      .then((rows) => {
        if (!alive || !Array.isArray(rows) || rows.length === 0) return
        setCovers(rows.map((r: Record<string, unknown>, i): Cover => ({
          img: String(r.img || ''),
          num: '',
          dir: FALLBACK_DIRS[i % FALLBACK_DIRS.length],
          fileUrl: safeFile(r.fileUrl),
          title: typeof r.titleFa === 'string' ? r.titleFa : undefined,
        })))
      })
      .catch(() => {})
    return () => { alive = false }
  }, [])

  return (
    <section style={{ background: '#faf7f4', padding: '40px 0' }} dir={lang === 'fa' ? 'rtl' : 'ltr'}>
      <div className="max-w-7xl mx-auto px-12 max-md:px-5">

        {/* compact heading — gold accent on the leading (right) edge */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 22 }}>
          <span style={{ width: 3, height: 28, background: GOLD, borderRadius: 2, flexShrink: 0 }} />
          <h2 style={{ fontSize: 'clamp(19px, 2vw, 26px)', fontWeight: 900, color: NAVY, margin: 0 }}>ماهنامه تحلیلی کارخانه</h2>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14 }} className="max-lg:!grid-cols-3 max-sm:!grid-cols-2">
          {covers.map((c, i) => (
            // 5th+ cover is hidden on phones so the 2-col grid stays a clean 2×2 (no orphan)
            <div key={c.img + i} className={i >= 4 ? 'max-sm:!hidden' : undefined}>
              <ScrollAnimation direction={c.dir}>
                <ReportCard img={c.img} title={c.title || (c.num ? `ماهنامه شماره ${c.num}` : 'ماهنامه کارخانه')} fileUrl={c.fileUrl} lang={lang} />
              </ScrollAnimation>
            </div>
          ))}
        </div>

      </div>
    </section>
  )
}
