'use client';

import { motion } from 'framer-motion';
import { useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';
import {
  staggerContainerWide,
  slideLeftVariants,
  fadeVariants,
  viewportOnce,
} from '@/lib/animations';
import { Link } from '@/i18n/navigation';
import { Lock, Clock, ArrowRight } from 'lucide-react';

// ─── Types ────────────────────────────────────────────────────────────────────

interface Project {
  title: string;
  description: string;
  tags: string[];
  slug: string;
  featured?: boolean;
}

interface ComingSoonItem {
  title: string;
  subtitle: string;
}

// ─── Data ──────────────────────────────────────────────────────────────────────

const PROJECTS: Project[] = [
  {
    title: 'Monaco Ocean Protection Challenge',
    description:
      "A comprehensive judging and analytics system with advanced AI jury integration for one of the Mediterranean's most prestigious conservation events.",
    tags: ['AI Integration', 'Platform'],
    slug: 'monaco-ocean',
    featured: true,
  },
  {
    title: 'Port Nimara',
    description: 'Scalable digital hub for maritime logistics.',
    tags: ['Website', 'Infrastructure'],
    slug: 'port-nimara',
  },
  {
    title: 'Port Amador',
    description: 'Premium digital experience for elite nautical services.',
    tags: ['Website', 'Infrastructure'],
    slug: 'port-amador',
  },
];

const COMING_SOON: ComingSoonItem[] = [
  { title: 'Confidential Riviera Project', subtitle: 'Coming Soon' },
  { title: 'Sophia Antipolis AI Startup', subtitle: 'Launching Q4' },
];

// ─── Animation Variants ───────────────────────────────────────────────────────

const ease = [0.16, 1, 0.3, 1] as const;

const featuredCardVariants = {
  hidden: { opacity: 0, y: 48 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.7, ease },
  },
};

const smallCardVariants = {
  hidden: { opacity: 0, y: 32 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.6, ease },
  },
};

const comingSoonVariants = {
  hidden: { opacity: 0, y: 24 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.55, ease },
  },
};

// ─── Geometric Placeholder ────────────────────────────────────────────────────

function GeometricPlaceholder({
  variant = 'featured',
  cardVariant = 'default',
  className,
}: {
  variant?: 'featured' | 'small';
  cardVariant?: 'default' | 'nimara' | 'amador';
  className?: string;
}) {
  const isFeatured = variant === 'featured';

  // Different gradient bases per card so secondary cards look distinct
  const gradientMap = {
    default: 'from-primary-dark/90 to-primary/70',
    nimara: 'from-navy/95 to-primary-dark/75',
    amador: 'from-[#1a3a4a]/95 to-primary/60',
  };

  return (
    <div
      className={cn(
        'relative overflow-hidden bg-gradient-to-br',
        gradientMap[cardVariant],
        className,
      )}
      aria-hidden="true"
    >
      <div className="absolute inset-0">

        {isFeatured ? (
          /* ── Featured (Monaco): blueprint feel ── */
          <>
            {/* Large filled circle top-right */}
            <div
              className="absolute rounded-full bg-white/[0.06]"
              style={{ width: '55%', height: '55%', top: '-15%', right: '-10%' }}
            />
            {/* Large circle ring — blueprint layer */}
            <div
              className="absolute rounded-full"
              style={{
                width: '45%',
                height: '45%',
                top: '10%',
                left: '5%',
                border: '1px solid rgba(255,255,255,0.12)',
                opacity: 0.4,
              }}
            />
            {/* Medium circle bottom-left */}
            <div
              className="absolute rounded-full bg-white/[0.08]"
              style={{ width: '40%', height: '40%', bottom: '-20%', left: '-5%' }}
            />
            {/* Subtle grid overlay (blueprint feel) */}
            <div
              className="absolute inset-0 opacity-[0.035]"
              style={{
                backgroundImage:
                  'linear-gradient(rgba(255,255,255,1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,1) 1px, transparent 1px)',
                backgroundSize: '32px 32px',
              }}
            />
            {/* Diagonal stripes very subtle */}
            <div
              className="absolute inset-0 opacity-[0.025]"
              style={{
                backgroundImage:
                  'repeating-linear-gradient(-45deg, #fff 0, #fff 1px, transparent 0, transparent 50%)',
                backgroundSize: '28px 28px',
              }}
            />
            {/* Small dot cluster */}
            <div
              className="absolute opacity-[0.12]"
              style={{
                width: '20%',
                height: '20%',
                top: '55%',
                right: '18%',
                backgroundImage: 'radial-gradient(circle, #fff 1.5px, transparent 1.5px)',
                backgroundSize: '8px 8px',
              }}
            />
            {/* Blueprint horizontal line — wide, white/20 */}
            <div
              className="absolute bg-white/[0.22] rounded-full"
              style={{ width: '60%', height: '1px', top: '50%', left: '5%' }}
            />
            {/* Second thinner line below */}
            <div
              className="absolute bg-white/[0.10] rounded-full"
              style={{ width: '40%', height: '1px', top: 'calc(50% + 10px)', left: '5%' }}
            />
            {/* Accent rotated rectangle */}
            <div
              className="absolute bg-white/[0.10] rounded-sm"
              style={{
                width: '18%',
                height: '28%',
                bottom: '18%',
                right: '15%',
                transform: 'rotate(-6deg)',
              }}
            />
            {/* Small diagonal accent line */}
            <div
              className="absolute bg-white/[0.15]"
              style={{
                width: '25%',
                height: '1px',
                top: '28%',
                right: '8%',
                transform: 'rotate(-30deg)',
                transformOrigin: 'left center',
              }}
            />
          </>
        ) : cardVariant === 'nimara' ? (
          /* ── Port Nimara: horizontal bands + arc ── */
          <>
            {/* Large arc ring top-left */}
            <div
              className="absolute rounded-full"
              style={{
                width: '80%',
                height: '80%',
                top: '-30%',
                left: '-20%',
                border: '1px solid rgba(255,255,255,0.10)',
                opacity: 0.5,
              }}
            />
            {/* Smaller ring center */}
            <div
              className="absolute rounded-full"
              style={{
                width: '45%',
                height: '70%',
                bottom: '-15%',
                right: '-10%',
                border: '1px solid rgba(91,164,217,0.25)',
              }}
            />
            {/* Horizontal rule band */}
            <div
              className="absolute bg-white/[0.06]"
              style={{ height: '28%', bottom: 0, left: 0, right: 0 }}
            />
            {/* Fine horizontal lines */}
            <div
              className="absolute bg-white/20 rounded-full"
              style={{ width: '50%', height: '1px', top: '35%', right: '8%' }}
            />
            <div
              className="absolute bg-white/10 rounded-full"
              style={{ width: '30%', height: '1px', top: '45%', right: '8%' }}
            />
            {/* Dot cluster top-right */}
            <div
              className="absolute opacity-[0.14]"
              style={{
                width: '25%',
                height: '30%',
                top: '5%',
                right: '5%',
                backgroundImage: 'radial-gradient(circle, #fff 1.5px, transparent 1.5px)',
                backgroundSize: '8px 8px',
              }}
            />
            {/* Diagonal line */}
            <div
              className="absolute bg-white/[0.12]"
              style={{
                width: '40%',
                height: '1px',
                top: '60%',
                left: '5%',
                transform: 'rotate(-20deg)',
                transformOrigin: 'left center',
              }}
            />
          </>
        ) : (
          /* ── Port Amador: triangular/radial composition ── */
          <>
            {/* Central radial glow */}
            <div
              className="absolute"
              style={{
                width: '70%',
                height: '70%',
                top: '-10%',
                right: '-15%',
                background:
                  'radial-gradient(circle, rgba(91,164,217,0.18) 0%, transparent 70%)',
              }}
            />
            {/* Diamond/rotated square accent */}
            <div
              className="absolute"
              style={{
                width: '30%',
                height: '50%',
                bottom: '-10%',
                left: '10%',
                border: '1px solid rgba(255,255,255,0.12)',
                transform: 'rotate(45deg)',
              }}
            />
            {/* Diagonal stripes (different angle) */}
            <div
              className="absolute inset-0 opacity-[0.03]"
              style={{
                backgroundImage:
                  'repeating-linear-gradient(30deg, #fff 0, #fff 1px, transparent 0, transparent 50%)',
                backgroundSize: '20px 20px',
              }}
            />
            {/* Top horizontal line */}
            <div
              className="absolute bg-white/20 rounded-full"
              style={{ width: '40%', height: '1px', top: '22%', left: '8%' }}
            />
            {/* Small filled rectangle */}
            <div
              className="absolute bg-white/[0.12] rounded-sm"
              style={{
                width: '20%',
                height: '32%',
                top: '15%',
                right: '12%',
                transform: 'rotate(8deg)',
              }}
            />
            {/* Dot accent bottom-right */}
            <div
              className="absolute opacity-[0.16]"
              style={{
                width: '22%',
                height: '22%',
                bottom: '8%',
                right: '8%',
                backgroundImage: 'radial-gradient(circle, #fff 1.5px, transparent 1.5px)',
                backgroundSize: '7px 7px',
              }}
            />
          </>
        )}
      </div>

      {/* Bottom gradient fade — card bg color bleed for text readability */}
      <div
        className="absolute inset-x-0 bottom-0 h-2/5"
        style={{
          background: isFeatured
            ? 'linear-gradient(to top, rgba(0,100,148,0.55) 0%, transparent 100%)'
            : cardVariant === 'nimara'
              ? 'linear-gradient(to top, rgba(28,43,58,0.60) 0%, transparent 100%)'
              : 'linear-gradient(to top, rgba(26,58,74,0.55) 0%, transparent 100%)',
        }}
      />
    </div>
  );
}

// ─── Tag Chip ─────────────────────────────────────────────────────────────────

function TagChip({ label, showDot = false }: { label: string; showDot?: boolean }) {
  return (
    <span className="inline-flex items-center gap-1.5 bg-primary/10 text-primary-dark text-[0.75rem] font-semibold px-3 py-1 rounded-full leading-none tracking-wide">
      {showDot && (
        <span className="w-1 h-1 rounded-full bg-primary/50 shrink-0" aria-hidden="true" />
      )}
      {label}
    </span>
  );
}

// ─── Featured Card ────────────────────────────────────────────────────────────

function FeaturedCard({ project, readLabel }: { project: Project; readLabel: string }) {
  return (
    <motion.article
      variants={featuredCardVariants}
      className={cn(
        'group relative flex flex-col bg-surface-high rounded-2xl overflow-hidden',
        'shadow-subtle',
        'transition-shadow duration-300 hover:shadow-[0_24px_48px_rgba(25,28,29,0.10)]',
      )}
    >
      {/* Geometric image placeholder */}
      <GeometricPlaceholder
        variant="featured"
        cardVariant="default"
        className="w-full aspect-[16/9] md:aspect-[2/1]"
      />

      {/* Content */}
      <div className="flex flex-col flex-1 p-7 gap-4">
        {/* Tags */}
        <div className="flex flex-wrap gap-2">
          {project.tags.map((tag, i) => (
            <TagChip key={tag} label={tag} showDot={i > 0} />
          ))}
        </div>

        {/* Title */}
        <h3 className="font-serif text-2xl font-semibold text-on-surface leading-snug">
          {project.title}
        </h3>

        {/* Description */}
        <p className="text-sm text-outline leading-relaxed flex-1">
          {project.description}
        </p>

        {/* CTA */}
        <Link
          href={`/work/${project.slug}`}
          className={cn(
            'inline-flex items-center gap-2 text-sm font-medium text-primary-dark',
            'mt-1 group/link',
          )}
        >
          <span className="relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:bg-primary-dark after:origin-left after:scale-x-100 after:transition-transform after:duration-200">
            {readLabel}
          </span>
          <ArrowRight
            size={15}
            className="transition-transform duration-200 group-hover/link:translate-x-1.5"
          />
        </Link>
      </div>
    </motion.article>
  );
}

// ─── Small Card ───────────────────────────────────────────────────────────────

const SLUG_TO_VARIANT: Record<string, 'nimara' | 'amador'> = {
  'port-nimara': 'nimara',
  'port-amador': 'amador',
};

function SmallCard({ project, readLabel }: { project: Project; readLabel: string }) {
  const cardVariant = SLUG_TO_VARIANT[project.slug] ?? 'nimara';

  return (
    <motion.article
      variants={smallCardVariants}
      className={cn(
        'group relative flex flex-col bg-surface-high rounded-xl overflow-hidden',
        'shadow-card',
        'transition-all duration-300',
        'hover:shadow-subtle',
      )}
    >
      {/* Geometric placeholder — grayscale to color on hover */}
      <div className="relative overflow-hidden">
        <div
          className={cn(
            'transition-all duration-500',
            'grayscale group-hover:grayscale-0',
            'opacity-80 group-hover:opacity-100',
          )}
        >
          <GeometricPlaceholder
            variant="small"
            cardVariant={cardVariant}
            className="w-full aspect-[16/7]"
          />
        </div>
      </div>

      {/* Content */}
      <div className="flex flex-col flex-1 p-5 gap-3">
        {/* Tags */}
        <div className="flex flex-wrap gap-1.5">
          {project.tags.map((tag, i) => (
            <TagChip key={tag} label={tag} showDot={i > 0} />
          ))}
        </div>

        {/* Title */}
        <h3 className="font-serif text-lg font-semibold text-on-surface leading-snug">
          {project.title}
        </h3>

        {/* Description */}
        <p className="text-xs text-outline leading-relaxed flex-1">
          {project.description}
        </p>

        {/* CTA */}
        <Link
          href={`/work/${project.slug}`}
          className="inline-flex items-center gap-1.5 text-xs font-medium text-primary-dark group/link"
        >
          <span className="relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:bg-primary-dark after:origin-left after:scale-x-100 after:transition-transform after:duration-200">
            {readLabel}
          </span>
          <ArrowRight
            size={13}
            className="transition-transform duration-200 group-hover/link:translate-x-1"
          />
        </Link>
      </div>
    </motion.article>
  );
}

// ─── Coming Soon Card ─────────────────────────────────────────────────────────

function ComingSoonCard({ item }: { item: ComingSoonItem }) {
  const isConfidential = item.subtitle === 'Coming Soon';
  const Icon = isConfidential ? Lock : Clock;

  return (
    <motion.div
      variants={comingSoonVariants}
      className={cn(
        'relative flex flex-col items-center justify-center gap-4',
        'rounded-xl p-8 min-h-[160px]',
        'border border-dashed border-outline-variant/30',
        'coming-soon-card',
        'overflow-hidden',
      )}
    >
      {/* Subtle animated pulse overlay */}
      <div
        className="absolute inset-0 rounded-xl opacity-0 coming-soon-pulse"
        aria-hidden="true"
      />

      <div className="relative z-10 flex flex-col items-center gap-3 text-center">
        <Icon
          size={20}
          className="text-outline/40"
          strokeWidth={1.5}
        />
        <div>
          <p className="font-serif text-base font-medium text-on-surface/40 leading-snug">
            {item.title}
          </p>
          <p className="label-md text-outline/50 mt-1">{item.subtitle}</p>
        </div>
      </div>
    </motion.div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function SelectedWorks() {
  const t = useTranslations();

  const featuredProject = PROJECTS.find((p) => p.featured)!;
  const secondaryProjects = PROJECTS.filter((p) => !p.featured);

  return (
    <section id="work" className="bg-surface-low py-24">
      <style>{`
        @keyframes dashed-drift {
          0%   { background-position: 0 0, 100% 0, 100% 100%, 0 100%; }
          100% { background-position: 100% 0, 100% 100%, 0 100%, 0 0; }
        }
        @keyframes coming-soon-bg-pulse {
          0%, 100% { background-color: var(--color-surface-low); }
          50%      { background-color: var(--color-surface); }
        }
        @keyframes coming-soon-fade {
          0%, 100% { opacity: 0; }
          50% { opacity: 1; }
        }
        .coming-soon-card {
          animation: coming-soon-bg-pulse 4s ease-in-out infinite;
        }
        .coming-soon-pulse {
          background: radial-gradient(
            ellipse at center,
            rgba(91, 164, 217, 0.06) 0%,
            transparent 70%
          );
          animation: coming-soon-fade 4s ease-in-out infinite;
        }
      `}</style>

      <div className="container mx-auto px-6">

        {/* ── Section Header ── */}
        <motion.div
          variants={slideLeftVariants}
          initial="hidden"
          whileInView="visible"
          viewport={viewportOnce}
          className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-14"
        >
          <div>
            <p className="label-md text-primary mb-2">{t('work.eyebrow')}</p>
            <h2 className="font-serif text-4xl md:text-5xl font-semibold text-on-surface leading-[1.1] tracking-[-0.02em]">
              {t('work.title')}
            </h2>
          </div>
          <motion.div
            variants={fadeVariants}
            initial="hidden"
            whileInView="visible"
            viewport={viewportOnce}
          >
            <Link
              href="/work"
              className="inline-flex items-center gap-2 text-sm font-medium text-outline hover:text-primary-dark transition-colors duration-200 group"
            >
              <span>View all work</span>
              <ArrowRight
                size={14}
                className="transition-transform duration-200 group-hover:translate-x-1"
              />
            </Link>
          </motion.div>
        </motion.div>

        {/* ── Primary Grid: Featured + 2 Small ── */}
        <motion.div
          variants={staggerContainerWide}
          initial="hidden"
          whileInView="visible"
          viewport={viewportOnce}
          className="grid grid-cols-1 md:grid-cols-12 gap-5 mb-5"
        >
          {/* Featured card — 8 cols */}
          <div className="md:col-span-8">
            <FeaturedCard
              project={featuredProject}
              readLabel={t('work.readCaseStudy')}
            />
          </div>

          {/* Secondary column — 4 cols, 2 stacked */}
          <div className="md:col-span-4 flex flex-col gap-5">
            {secondaryProjects.map((project) => (
              <SmallCard
                key={project.slug}
                project={project}
                readLabel={t('work.readCaseStudy')}
              />
            ))}
          </div>
        </motion.div>

        {/* ── Coming Soon Row ── */}
        <motion.div
          variants={staggerContainerWide}
          initial="hidden"
          whileInView="visible"
          viewport={viewportOnce}
          className="grid grid-cols-1 sm:grid-cols-2 gap-5"
        >
          {COMING_SOON.map((item) => (
            <ComingSoonCard key={item.title} item={item} />
          ))}
        </motion.div>

      </div>
    </section>
  );
}
