import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Download, FileText, ExternalLink, X, Eye, BookOpen } from 'lucide-react'
import { useLang } from '@/context/LangContext'
import { FALLBACK_TECHNOGEN_REPORTS, type TechnogenReport } from '@/data/technogen'

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

export default function TechnogenSection() {
  const { lang } = useLang()
  const isFa = lang === 'fa'
  const [reports, setReports] = useState<TechnogenReport[]>(FALLBACK_TECHNOGEN_REPORTS)
  const [selectedReport, setSelectedReport] = useState<TechnogenReport | null>(null)

  useEffect(() => {
    let unmounted = false
    fetch('/api/technogen')
      .then((res) => {
        if (!res.ok) throw new Error('API error')
        return res.json()
      })
      .then((data: TechnogenReport[]) => {
        if (!unmounted && Array.isArray(data) && data.length > 0) {
          setReports(data)
        }
      })
      .catch(() => {})
    return () => {
      unmounted = true
    }
  }, [])

  // Featured report (POSCO study) vs analytical notes
  const featured = reports.find((r) => r.isFeatured) || reports[0]
  const analyticalNotes = reports.filter((r) => r.id !== featured?.id)

  const openPreview = (report: TechnogenReport) => {
    setSelectedReport(report)
  }

  const closePreview = () => {
    setSelectedReport(null)
  }

  return (
    <section
      id="technogen"
      dir={isFa ? 'rtl' : 'ltr'}
      style={{
        background: 'var(--paper)',
        borderTop: '1px solid var(--rule-thin)',
        borderBottom: '1px solid var(--rule-thin)',
        padding: '44px 0 52px',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <div className="max-w-7xl mx-auto px-12 max-md:px-4">
        {/* ── Section Header with Gold Accent Line ── */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 4, height: 28, background: GOLD, borderRadius: 2, flexShrink: 0 }} />
            <h2
              style={{
                fontSize: 'clamp(20px, 2.2vw, 28px)',
                fontWeight: 900,
                color: NAVY,
                margin: 0,
                letterSpacing: isFa ? '-0.5px' : '-0.2px',
                lineHeight: 1.3,
              }}
            >
              {isFa ? 'تکنوژن؛ برنامه توسعه‌گر ملی فناوری' : 'Technogen: National Technology Developer Program'}
            </h2>
          </div>
          <p
            style={{
              fontSize: 13,
              color: 'rgba(3,35,64,0.65)',
              margin: '6px 0 0',
              paddingInlineStart: 16,
              lineHeight: 1.6,
            }}
          >
            {isFa
              ? 'گزارش‌های تحلیلی و مطالعات تطبیقی یادگیری صنعتی، انتقال دانش و ساخت قابلیت فناورانه در زنجیره فولاد'
              : 'Analytical notes and comparative studies on industrial learning, knowledge absorption, and technological capability building in steel.'}
          </p>
        </div>

        {/* ── Bento Grid Layout (Unified Single Block) ── */}
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(12, 1fr)',
            gap: 16,
            alignItems: 'stretch',
          }}
          className="max-lg:!grid-cols-1"
        >
          {/* ── Bento Card 1: Flagship POSCO Study (Spans 7 columns) ── */}
          {featured && (
            <motion.div
              initial={{ opacity: 0, y: 16 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, ease: EASE }}
              style={{
                gridColumn: 'span 7',
                position: 'relative',
                borderRadius: 18,
                overflow: 'hidden',
                background: `linear-gradient(135deg, ${NAVY} 0%, #062b4f 60%, #031e36 100%)`,
                boxShadow: '0 12px 30px -10px rgba(3,35,64,0.25)',
                border: '1px solid rgba(255,255,255,0.08)',
                padding: '24px 28px',
                display: 'flex',
                alignItems: 'center',
                gap: 24,
              }}
              className="max-lg:!col-span-1 max-md:!flex-col max-md:!p-5 max-md:!gap-4"
            >
              {/* Subtle background glow */}
              <div
                style={{
                  position: 'absolute',
                  top: '-30%',
                  right: '-20%',
                  width: '320px',
                  height: '320px',
                  borderRadius: '50%',
                  background: 'radial-gradient(circle, rgba(205,158,83,0.15) 0%, transparent 60%)',
                  pointerEvents: 'none',
                }}
              />

              {/* Cover Thumbnail */}
              <div
                style={{
                  flex: '0 0 160px',
                  display: 'flex',
                  justifyContent: 'center',
                }}
                className="max-md:!w-full"
              >
                <motion.div
                  whileHover={{ scale: 1.03, y: -3 }}
                  transition={{ duration: 0.25 }}
                  onClick={() => openPreview(featured)}
                  style={{
                    width: 150,
                    aspectRatio: '1 / 1.414',
                    borderRadius: 10,
                    overflow: 'hidden',
                    boxShadow: '0 14px 28px -6px rgba(0,0,0,0.5)',
                    border: '1px solid rgba(255,255,255,0.15)',
                    cursor: 'pointer',
                    background: NAVY,
                  }}
                >
                  <img
                    src={featured.coverImage}
                    alt={isFa ? featured.titleFa : (featured.titleEn || featured.titleFa)}
                    style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
                  />
                </motion.div>
              </div>

              {/* Info & Actions */}
              <div
                style={{
                  flex: '1 1 0',
                  color: '#fff',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  minWidth: 0,
                }}
                className="max-md:!text-center"
              >
                {/* Meta Pills */}
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                    marginBottom: 10,
                    flexWrap: 'wrap',
                  }}
                  className="max-md:!justify-center"
                >
                  <span
                    style={{
                      background: GOLD,
                      color: NAVY,
                      fontSize: 10,
                      fontWeight: 900,
                      padding: '3px 8px',
                      borderRadius: 4,
                    }}
                  >
                    {isFa ? 'مطالعه تطبیقی ویژه' : 'Flagship Study'}
                  </span>
                  {featured.code && (
                    <span
                      style={{
                        background: 'rgba(255,255,255,0.12)',
                        color: '#fff',
                        fontSize: 10,
                        fontWeight: 800,
                        padding: '3px 8px',
                        borderRadius: 4,
                        direction: 'ltr',
                      }}
                    >
                      {featured.code}
                    </span>
                  )}
                  <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.65)', fontWeight: 600 }}>
                    {isFa ? (featured.pagesFa || '۳۰ صفحه') : (featured.pagesEn || '30 Pages')}
                  </span>
                </div>

                {/* Title */}
                <h3
                  style={{
                    fontSize: 'clamp(16px, 1.6vw, 20px)',
                    fontWeight: 900,
                    lineHeight: 1.4,
                    margin: '0 0 8px',
                    color: '#fff',
                  }}
                >
                  {isFa ? featured.titleFa : (featured.titleEn || featured.titleFa)}
                </h3>

                {/* Subtitle / Excerpt */}
                {featured.subtitleFa && (
                  <p
                    style={{
                      fontSize: 12,
                      lineHeight: 1.7,
                      color: 'rgba(255,255,255,0.75)',
                      margin: '0 0 16px',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                      overflow: 'hidden',
                    }}
                  >
                    {isFa ? featured.subtitleFa : (featured.subtitleEn || featured.subtitleFa)}
                  </p>
                )}

                {/* Actions */}
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 10,
                    flexWrap: 'wrap',
                  }}
                  className="max-md:!justify-center"
                >
                  {featured.fileUrl && (
                    <a
                      href={featured.fileUrl}
                      download
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: 6,
                        background: `linear-gradient(135deg, ${GOLD} 0%, #e0b469 100%)`,
                        color: NAVY,
                        fontSize: 12,
                        fontWeight: 900,
                        padding: '9px 16px',
                        borderRadius: 8,
                        textDecoration: 'none',
                        boxShadow: '0 6px 16px -4px rgba(205,158,83,0.4)',
                        transition: 'transform 0.15s',
                      }}
                      className="hover:!brightness-105 active:!scale-95"
                    >
                      <Download size={14} strokeWidth={2.5} />
                      <span>{isFa ? 'دانلود PDF کامل' : 'Download PDF'}</span>
                    </a>
                  )}

                  <button
                    onClick={() => openPreview(featured)}
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: 6,
                      background: 'rgba(255,255,255,0.08)',
                      border: '1px solid rgba(255,255,255,0.18)',
                      color: '#fff',
                      fontSize: 12,
                      fontWeight: 700,
                      padding: '9px 14px',
                      borderRadius: 8,
                      cursor: 'pointer',
                      transition: 'background 0.15s',
                    }}
                    className="hover:!bg-white/15"
                  >
                    <BookOpen size={14} />
                    <span>{isFa ? 'مشاهده آنلاین' : 'Read'}</span>
                  </button>
                </div>
              </div>
            </motion.div>
          )}

          {/* ── Bento Cards 2, 3, 4: Analytical Notes (Spans 5 columns) ── */}
          <div
            style={{
              gridColumn: 'span 5',
              display: 'flex',
              flexDirection: 'column',
              gap: 10,
              justifyContent: 'space-between',
            }}
            className="max-lg:!col-span-1"
          >
            {analyticalNotes.map((note, idx) => (
              <motion.div
                key={note.id}
                initial={{ opacity: 0, x: isFa ? -12 : 12 }}
                whileInView={{ opacity: 1, x: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.4, ease: EASE, delay: idx * 0.08 }}
                whileHover={{ y: -2 }}
                style={{
                  background: '#FFFFFF',
                  borderRadius: 14,
                  border: '1px solid rgba(3,35,64,0.08)',
                  boxShadow: '0 4px 14px -4px rgba(3,35,64,0.05)',
                  padding: '12px 14px',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 14,
                  flex: '1 1 0',
                }}
              >
                {/* Mini Cover Thumbnail */}
                <div
                  onClick={() => openPreview(note)}
                  style={{
                    flex: '0 0 54px',
                    width: 54,
                    aspectRatio: '1 / 1.414',
                    borderRadius: 6,
                    overflow: 'hidden',
                    boxShadow: '0 4px 10px rgba(0,0,0,0.15)',
                    border: '1px solid rgba(3,35,64,0.1)',
                    background: NAVY,
                    cursor: 'pointer',
                  }}
                >
                  <img
                    src={note.coverImage}
                    alt={isFa ? note.titleFa : (note.titleEn || note.titleFa)}
                    style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
                  />
                </div>

                {/* Content */}
                <div style={{ flex: '1 1 0', minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                    {note.code && (
                      <span
                        style={{
                          background: 'rgba(3,35,64,0.06)',
                          color: NAVY,
                          fontSize: 9,
                          fontWeight: 800,
                          padding: '2px 6px',
                          borderRadius: 3,
                          direction: 'ltr',
                        }}
                      >
                        {note.code}
                      </span>
                    )}
                    <span
                      style={{
                        background: 'rgba(205,158,83,0.15)',
                        color: '#9c6f28',
                        fontSize: 9,
                        fontWeight: 800,
                        padding: '2px 6px',
                        borderRadius: 3,
                      }}
                    >
                      {isFa ? (note.tagFa || 'یادداشت تحلیلی') : (note.tagEn || 'Analytical Note')}
                    </span>
                    <span style={{ fontSize: 10, color: 'rgba(3,35,64,0.5)', fontWeight: 600, marginInlineStart: 'auto' }}>
                      {isFa ? (note.pagesFa || '۴ صفحه') : (note.pagesEn || '4 Pages')}
                    </span>
                  </div>

                  <h4
                    onClick={() => openPreview(note)}
                    style={{
                      fontSize: 13,
                      fontWeight: 800,
                      color: NAVY,
                      lineHeight: 1.4,
                      margin: '0 0 2px',
                      cursor: 'pointer',
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                    }}
                    title={isFa ? note.titleFa : (note.titleEn || note.titleFa)}
                  >
                    {isFa ? note.titleFa : (note.titleEn || note.titleFa)}
                  </h4>

                  {note.subtitleFa && (
                    <p
                      style={{
                        fontSize: 11,
                        lineHeight: 1.5,
                        color: 'rgba(3,35,64,0.65)',
                        margin: 0,
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                      }}
                    >
                      {isFa ? note.subtitleFa : (note.subtitleEn || note.subtitleFa)}
                    </p>
                  )}
                </div>

                {/* Quick Action Buttons */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                  {note.fileUrl && (
                    <a
                      href={note.fileUrl}
                      download
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: 32,
                        height: 32,
                        borderRadius: 8,
                        background: 'rgba(3,35,64,0.06)',
                        color: NAVY,
                        textDecoration: 'none',
                        transition: 'all 0.15s',
                      }}
                      className="hover:!bg-navy hover:!text-white"
                      title={isFa ? 'دانلود فایل PDF' : 'Download PDF'}
                    >
                      <Download size={14} />
                    </a>
                  )}

                  <button
                    onClick={() => openPreview(note)}
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      width: 32,
                      height: 32,
                      borderRadius: 8,
                      background: 'transparent',
                      border: '1px solid rgba(3,35,64,0.15)',
                      color: NAVY,
                      cursor: 'pointer',
                      transition: 'all 0.15s',
                    }}
                    className="hover:!border-navy"
                    title={isFa ? 'مشاهده آنلاین' : 'Preview'}
                  >
                    <Eye size={14} />
                  </button>
                </div>
              </motion.div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Document Reader / Preview Modal ── */}
      <AnimatePresence>
        {selectedReport && (
          <div
            style={{
              position: 'fixed',
              inset: 0,
              zIndex: 9999,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '24px 16px',
            }}
          >
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              style={{
                position: 'absolute',
                inset: 0,
                background: 'rgba(3, 20, 36, 0.85)',
                backdropFilter: 'blur(8px)',
              }}
              onClick={closePreview}
            />

            {/* Modal Window */}
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              transition={{ duration: 0.3, ease: EASE }}
              style={{
                position: 'relative',
                width: '100%',
                maxWidth: 1000,
                height: '90vh',
                background: '#FFFFFF',
                borderRadius: 24,
                boxShadow: '0 30px 90px rgba(0,0,0,0.5)',
                display: 'flex',
                flexDirection: 'column',
                overflow: 'hidden',
                zIndex: 1,
              }}
            >
              {/* Modal Top Header */}
              <div
                style={{
                  padding: '16px 24px',
                  background: NAVY,
                  color: '#fff',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: 16,
                  borderBottom: '1px solid rgba(255,255,255,0.1)',
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
                  <FileText size={20} color={GOLD} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 11, color: GOLD, fontWeight: 700 }}>
                      {selectedReport.code} · {isFa ? selectedReport.tagFa : (selectedReport.tagEn || selectedReport.tagFa)}
                    </div>
                    <div
                      style={{
                        fontSize: 15,
                        fontWeight: 900,
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                      }}
                    >
                      {isFa ? selectedReport.titleFa : (selectedReport.titleEn || selectedReport.titleFa)}
                    </div>
                  </div>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
                  {selectedReport.fileUrl && (
                    <a
                      href={selectedReport.fileUrl}
                      download
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: 6,
                        background: GOLD,
                        color: NAVY,
                        fontSize: 12,
                        fontWeight: 800,
                        padding: '6px 14px',
                        borderRadius: 8,
                        textDecoration: 'none',
                      }}
                    >
                      <Download size={14} />
                      <span>{isFa ? 'دانلود فایل' : 'Download'}</span>
                    </a>
                  )}

                  {selectedReport.fileUrl && (
                    <a
                      href={selectedReport.fileUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: 32,
                        height: 32,
                        borderRadius: 8,
                        background: 'rgba(255,255,255,0.1)',
                        color: '#fff',
                        textDecoration: 'none',
                      }}
                      title={isFa ? 'باز کردن در پنجره جدید' : 'Open in new tab'}
                    >
                      <ExternalLink size={15} />
                    </a>
                  )}

                  <button
                    onClick={closePreview}
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      width: 32,
                      height: 32,
                      borderRadius: 8,
                      background: 'rgba(255,255,255,0.1)',
                      border: 'none',
                      color: '#fff',
                      cursor: 'pointer',
                    }}
                    title={isFa ? 'بستن' : 'Close'}
                  >
                    <X size={18} />
                  </button>
                </div>
              </div>

              {/* Modal Viewer Body */}
              <div style={{ flex: '1 1 0', position: 'relative', background: '#e5e7eb' }}>
                {selectedReport.fileUrl ? (
                  <iframe
                    src={`${selectedReport.fileUrl}#toolbar=1&navpanes=0`}
                    style={{
                      width: '100%',
                      height: '100%',
                      border: 'none',
                    }}
                    title={selectedReport.titleFa}
                  />
                ) : (
                  <div style={{ display: 'grid', placeItems: 'center', height: '100%', color: '#6b7280' }}>
                    {isFa ? 'فایل PDF در دسترس نیست.' : 'PDF file not available.'}
                  </div>
                )}
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </section>
  )
}
