'use client';

import Link from 'next/link';
import Image from 'next/image';
import { motion } from 'framer-motion';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/Button';
import { HoverShineOverlay } from '@/components/ui/HoverShineOverlay';
import { StratumLines } from '@/components/ui/decorations/StratumLines';
import { DrillBitSpinner } from '@/components/ui/decorations/DrillBitSpinner';
import { DrillTeeth } from '@/components/ui/decorations/DrillTeeth';

interface CompetenceBentoGridProps {
  badge?: string;
  title?: string;
  ctaLabel?: string;
  ctaHref?: string;
  items?: {
    title?: string;
    description?: string;
    tag?: string;
    image?: {
      url?: string;
      alt?: string;
    } | any;
    size?: 'large' | 'medium' | 'small' | 'accent';
  }[];
  data?: {
    badge?: string;
    title?: string;
    ctaLabel?: string;
    ctaHref?: string;
    items?: {
      title?: string;
      description?: string;
      tag?: string;
      image?: {
        url?: string;
        alt?: string;
      } | any;
      size?: 'large' | 'medium' | 'small' | 'accent';
    }[];
  };
}

export function CompetenceBentoGrid(props: CompetenceBentoGridProps) {
  const { data } = props;
  const [isMounted, setIsMounted] = useState(false);
  
  useEffect(() => {
    setIsMounted(true);
  }, []);

  const badge = props.badge || data?.badge || 'Leistungsspektrum';
  const title = props.title || data?.title || 'Umfassende Lösungen für komplexe Netzwerke';
  const ctaLabel = props.ctaLabel || data?.ctaLabel || 'Alle Kompetenzen ansehen';
  const ctaHref = props.ctaHref || data?.ctaHref || '/kompetenzen';
  const items = props.items || data?.items || [];

  // Static fallback for SSR
  if (!isMounted) {
    return (
      <section className="py-24 bg-neutral text-neutral-dark overflow-hidden relative">
        <div className="container">
          <div className="flex flex-col md:flex-row justify-between items-end mb-12">
            <div className="max-w-2xl">
              <h2 className="text-primary font-bold tracking-wider uppercase text-sm mb-3">{badge}</h2>
              <h3 className="font-heading text-4xl md:text-5xl font-extrabold text-neutral-dark mb-4">{title}</h3>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4 auto-rows-[220px]">
             {/* Simplified static grid */}
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="py-24 bg-neutral text-neutral-dark relative overflow-hidden">
      <div className="container relative z-10 px-4">
        <div className="flex flex-col md:flex-row justify-between items-end mb-12">
          <div className="max-w-2xl">
            <h2 className="text-primary font-bold tracking-wider uppercase text-sm mb-3">{badge}</h2>
            <h3 className="font-heading text-4xl md:text-5xl font-extrabold text-neutral-dark mb-4">{title}</h3>
          </div>
          <Button href={ctaHref} variant="ghost" className="mt-6 md:mt-0 bg-primary/5 hover:bg-primary/10">
            {ctaLabel}
            <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5 ml-2 transform group-hover:translate-x-1 transition-transform" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
          </Button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4 auto-rows-[220px]">
          {items.map((item, idx) => {
            const isLarge = item.size === 'large';
            const isMedium = item.size === 'medium';
            const isAccent = item.size === 'accent';
            const imgSrc = item.image?.url;
            
            let gridClasses = "rounded-2xl overflow-hidden relative group select-none ";
            if (isLarge) gridClasses += "md:col-span-2 md:row-span-2";
            else if (isMedium) gridClasses += "md:col-span-2 lg:col-span-2";
            else if (isAccent) gridClasses += "md:col-span-1 bg-primary text-white p-6 md:p-8 flex flex-col justify-center border-none shadow-md";
            else gridClasses += "md:col-span-1";

            if (isAccent) {
              return (
                <motion.div 
                  key={idx}
                  initial={{ opacity: 0, y: 20 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ delay: idx * 0.1 }}
                  className={gridClasses}
                >
                  <div className="absolute top-0 right-0 w-32 h-32 bg-primary/30 blur-3xl rounded-full -mr-10 -mt-10 group-hover:bg-primary/50 transition-colors duration-500" />
                  <HoverShineOverlay shineColor="via-white/30" />
                  <h4 className="font-bold text-xl md:text-2xl relative z-10 leading-snug">{item.title}</h4>
                  {item.description && <p className="text-white/60 text-sm mt-3 relative z-10">{item.description}</p>}
                </motion.div>
              );
            }

            return (
              <motion.div 
                key={idx}
                initial={{ opacity: 0, scale: 0.95 }}
                whileInView={{ opacity: 1, scale: 1 }}
                viewport={{ once: true }}
                transition={{ delay: idx * 0.1 }}
                className={gridClasses}
              >
                {!imgSrc && (
                  <div className="absolute inset-0 bg-neutral-dark z-0 transition-colors duration-500 group-hover:bg-primary-dark" />
                )}
                {imgSrc && (
                  <>
                    <div className="absolute inset-0 bg-white z-0">
                      <Image
                        src={imgSrc}
                        alt={item.title || ''}
                        fill
                        className="object-cover opacity-90 group-hover:scale-105 group-hover:opacity-100 transition-all duration-700 ease-in-out"
                        sizes={isLarge ? "(max-width: 768px) 100vw, 50vw" : "(max-width: 768px) 100vw, 25vw"}
                      />
                    </div>
                    <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent opacity-90 transition-opacity duration-500 z-0" />
                  </>
                )}
                
                <HoverShineOverlay />
                
                <div className="relative z-10 p-8 flex flex-col justify-end h-full text-white">
                  {item.tag && (
                    <span className="inline-block px-3 py-1 bg-primary/20 backdrop-blur-md rounded-full text-xs font-bold uppercase tracking-wider text-primary-light mb-3 w-fit border border-primary/30">
                      {item.tag}
                    </span>
                  )}
                  <h4 className={`font-heading font-extrabold mb-2 ${isLarge ? 'text-3xl md:text-5xl' : 'text-xl md:text-2xl'}`}>
                    {item.title}
                  </h4>
                  {item.description && (
                    <p className={`text-white/80 ${isLarge ? 'text-lg md:text-xl max-w-sm' : 'text-sm'}`}>
                      {item.description}
                    </p>
                  )}
                </div>
              </motion.div>
            );
          })}
        </div>
      </div>
      {/* Decorative: large abstract drill bit spinning slowly in background */}
      <div className="absolute top-1/2 -translate-y-1/2 -right-48 pointer-events-none opacity-[0.03]">
        <DrillBitSpinner size={600} duration={25} glow={false} />
      </div>
      {/* Decorative: abstract earth strata / excavation layers */}
      <StratumLines placement="bottom-left" invert />
      <StratumLines placement="bottom-right" invert />
      {/* Organic wave divider */}
      <DrillTeeth position="bottom" fill="var(--color-neutral)" />
    </section>
  );
}
