"use client";

import { cn } from "@/lib/utils";
import { H2, P } from "@/components/Texts";
import React, { useState, useEffect, useRef } from "react";
import { BentoGrid, MotionBentoGridItem } from "@/components/ui/bento-grid";
import { AnimatePresence, motion } from "framer-motion";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { FadeIn } from "./FadeIn";

const items = [
  {
    title: 'FungiStor',
    subtitle: 'Long-Term AI Memory',
    description: 'Erasure coding + compression slash storage bloat by up to 10× vs basic replication. Source-encrypted shards are geo-dispersed—lose pieces, rebuild perfectly from a quorum.',
    video: "/videos/fungistor.mp4",
  },
  {
    title: 'HeroDB',
    subtitle: 'Active AI Memory',
    description: 'Multimodal vector+keyword retrieval makes RAG feel instant across text, image, audio. Time-aware, policy-guarded context keeps results fresh while access stays governed.',
    video: "/videos/herodb.mp4",
  },
  {
    title: 'MOS Sandboxes',
    subtitle: 'Secure Agent Workspaces',
    description: 'Attested, signed workspaces spin up ≈5s worldwide—ready to execute. Hardware isolation and scoped egress: run hard, tear down clean, zero residue.',
    video: "/videos/sandbox.mp4",
  },
  {
    title: 'Mycelium Mesh',
    subtitle: 'Secure Communication Network',
    description: 'A private, public-key fabric with self-healing multi-path routing. Glides through NATs and firewalls—direct, low-latency, no middlemen.',
    video: "/videos/mesh.mp4",
  },
  {
    title: 'Deterministic Deployment',
    subtitle: 'Verifiable Code Execution',
    description: 'Declare intent, get a hash; remote attestation proves that’s what runs. Reproducible builds, signed artifacts, immutable logs—supply chain, sealed.',
    video: "/videos/deterministic.mp4",
  },
  {
    title: 'Agent Coordination',
    subtitle: 'Sovereign Workflow Management',
    description: 'Your private agent conducts swarms of specialists in parallel. Policies fan out work; human checkpoints keep you in command.',
    video: "/videos/agent.mp4",
  },
  {
    title: 'Universal Interface Layer',
    subtitle: 'AI Service Gateway',
    description: 'One gateway to open-source LLMs, tools, APIs, and data—bring your own models & keys. Semantic retrieval, function calling, and metered micropayments built in.',
    video: "/videos/universal.mp4",
  },
];

export function BentoReviews() {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (!isPaused) {
      intervalRef.current = setInterval(() => {
        setActiveIndex((prevIndex) => (prevIndex + 1) % items.length);
      }, 3000);
    } else {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [isPaused]);

    const handleCardTap = () => {
    setIsPaused(true);
  };

  const handlePrev = () => {
    setActiveIndex((prevIndex) => (prevIndex - 1 + items.length) % items.length);
    setIsPaused(true);
  };

  const handleNext = () => {
    setActiveIndex((prevIndex) => (prevIndex + 1) % items.length);
    setIsPaused(true);
  };

  return (
    <div>
      <div className="relative isolate pt-24 pb-12 bg-black text-center w-full lg:px-0 px-4">
        <FadeIn transition={{ duration: 0.8, delay: 0.1 }}>
          <div className="mx-auto max-w-5xl ">
            <H2 className="text-center">Augmented Intelligence Fabric</H2>
          </div>
        </FadeIn>
        <FadeIn transition={{ duration: 0.8, delay: 0.2 }}>
          <div className="mx-auto max-w-4xl mt-6 mb-8">
            <P className="text-center" color="primary">
            The sovereign substrate for autonomous AI. Stateless, geo-aware, end-to-end encrypted—and verifiable from intent to execution.
            </P>
          </div>
        </FadeIn>
      </div>

      {/* Desktop Grid */}
      <div className="hidden lg:block">
        <BentoGrid className="max-w-8xl lg:px-12 px-4 pb-12 lg:grid-cols-3">
          {items.map((item, i) => (
            <MotionBentoGridItem
              key={i}
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: false, margin: '0px 0px -100px 0px' }}
              transition={{ duration: 0.8, delay: 0.3 + i * 0.1 }}
              className={cn(i === 3 || i === 6 ? "md:col-span-2" : "")}
              rowHeight={i >= 3 ? "h-[22rem]" : ""}
              title={item.title}
              subtitle={item.subtitle}
              description={item.description}
              video={item.video}
            />
          ))}
        </BentoGrid>
      </div>

      {/* Mobile Carousel */}
      <div className="lg:hidden block px-4 pb-12">
                <div className="relative h-[24rem] w-full overflow-hidden">
          <div className="absolute inset-0" onTouchStart={handleCardTap} />
          <AnimatePresence initial={false}>
            <motion.div
              key={activeIndex}
              className="absolute h-full w-full"
              initial={{ x: "100%", opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              exit={{ x: "-100%", opacity: 0 }}
              transition={{ type: "spring", stiffness: 300, damping: 30 }}
            >
              <MotionBentoGridItem
                className="h-full"
                title={items[activeIndex].title}
                subtitle={items[activeIndex].subtitle}
                description={items[activeIndex].description}
                video={items[activeIndex].video}
              />
            </motion.div>
          </AnimatePresence>
          <button
            onClick={handlePrev}
            className="absolute left-2 top-[58%] -translate-y-1/2 rounded-full bg-black/50 p-2 text-white z-10"
          >
            <ChevronLeft className="h-6 w-6" />
          </button>
          <button
            onClick={handleNext}
            className="absolute right-2 top-[58%] -translate-y-1/2 rounded-full bg-black/50 p-2 text-white z-10"
          >
            <ChevronRight className="h-6 w-6" />
          </button>
        </div>
      </div>
    </div>
  );
}

