'use client'

import React, { useEffect, useMemo, useRef, useState } from 'react'
import clsx from 'clsx'
import {
  ArchiveBoxIcon,
  CodeBracketIcon,
  CpuChipIcon,
  GlobeAltIcon,
  MagnifyingGlassIcon,
  ShareIcon,
  UserGroupIcon,
  CheckBadgeIcon,
} from '@heroicons/react/24/solid'

import { Container } from '@/components/Container'
import { H2, P, CT, CP } from '@/components/Texts'
import { motion, useInView } from 'framer-motion'

interface Review {
  title: string
  body: string
}

const reviews: Review[] = [
  { title: 'FungiStor: Long-Term AI Memory', body: 'Quantum-safe permanent storage preserving AI knowledge forever. Zero-knowledge architecture with mathematical dispersal ensures immortality.' },
  { title: 'HeroDB: Active AI Memory', body: 'High-performance datastore for AI working memory. Multi-modal indexing enables vector search with global accessibility.' },
  { title: 'MOS Sandboxes: Secure Agent Workspaces', body: 'Lightweight isolated environments deploying globally in five seconds. Hardware-level isolation ensures maximum security for agents.' },
  { title: 'Mycelium Mesh: Secure Communication Network', body: 'Peer-to-peer overlay network with end-to-end encryption. Self-healing shortest-path routing creates resilient agentic communication.' },
  { title: 'Deterministic Deployment: Verifiable Code Execution', body: 'Cryptographic guarantee system ensuring deployed code matches specifications. Prevents supply-chain attacks with immutable trails.' },
  { title: 'Agent Coordination: Sovereign Workflow Management', body: 'User-centric orchestration where HERO agents coordinate worker fleets. Planetary-scale coordination with instant spawning.' },
  { title: 'Universal Interface Layer: AI Service Gateway', body: 'Unified broker connecting agents to LLMs, APIs, and services. Integrated micropayments simplify development.' },
  { title: 'Semantic Index & Search: Navigable Knowledge Fabric', body: 'Transforms data chaos into unified knowledge graphs. Goes beyond keywords to understand meaning and context.' },
]

function getReviewIcon(title: string) {
  if (title.startsWith('FungiStor')) return ArchiveBoxIcon
  if (title.startsWith('HeroDB')) return CpuChipIcon
  if (title.startsWith('MOS Sandboxes')) return CodeBracketIcon
  if (title.startsWith('Mycelium Mesh')) return ShareIcon
  if (title.startsWith('Deterministic Deployment')) return CheckBadgeIcon
  if (title.startsWith('Agent Coordination')) return UserGroupIcon
  if (title.startsWith('Universal Interface Layer')) return GlobeAltIcon
  if (title.startsWith('Semantic Index & Search')) return MagnifyingGlassIcon
  return GlobeAltIcon
}

function Review({ title, body, className, ...props }: Omit<React.ComponentPropsWithoutRef<'figure'>, keyof Review> & Review) {
  const animationDelay = useMemo(() => {
    const delays = ['0s', '0.1s', '0.2s', '0.3s', '0.4s', '0.5s']
    return delays[Math.floor(Math.random() * delays.length)]
  }, [])

  return (
    <figure
      className={clsx(
        'animate-fade-in rounded-3xl bg-gray-900/50 p-6 opacity-0 shadow-md shadow-gray-900/5',
        className
      )}
      style={{ animationDelay }}
      {...props}
    >
      <blockquote className="text-white">
        {React.createElement(getReviewIcon(title), { className: 'h-6 w-6 text-white mb-2' })}
        <CT color="light" className="mt-4 text-lg font-semibold">{title}</CT>
        <CP color="light" className="mt-3 text-sm">{body}</CP>
      </blockquote>
    </figure>
  )
}

function splitArray<T>(array: T[], numParts: number) {
  const result: T[][] = []
  for (let i = 0; i < array.length; i++) {
    const index = i % numParts
    if (!result[index]) result[index] = []
    result[index].push(array[i])
  }
  return result
}

function ReviewColumn({ reviews, className, msPerPixel = 0 }: { reviews: Review[], className?: string, msPerPixel?: number }) {
  const columnRef = useRef<HTMLDivElement>(null)
  const [columnHeight, setColumnHeight] = useState(0)
  const duration = `${columnHeight * msPerPixel}ms`

  useEffect(() => {
    if (!columnRef.current) return
    const resizeObserver = new ResizeObserver(() =>
      setColumnHeight(columnRef.current?.offsetHeight ?? 0)
    )
    resizeObserver.observe(columnRef.current)
    return () => resizeObserver.disconnect()
  }, [])

  return (
    <div
      ref={columnRef}
      className={clsx('animate-marquee space-y-8 py-4', className)}
      style={{ '--marquee-duration': duration } as React.CSSProperties}
    >
      {reviews.concat(reviews).map((review, i) => (
        <Review key={i} aria-hidden={i >= reviews.length} {...review} />
      ))}
    </div>
  )
}

function ReviewGrid() {
  const containerRef = useRef<HTMLDivElement>(null)
  const isInView = useInView(containerRef, { once: true, amount: 0.4 })
  const columns = splitArray(reviews, 2)

  return (
    <div ref={containerRef} className="relative grid grid-cols-1 md:grid-cols-2 gap-8 overflow-hidden h-full">
      {isInView && (
        <>
          <ReviewColumn reviews={columns[0]} msPerPixel={10} />
          <ReviewColumn reviews={columns[1]} msPerPixel={15} />
        </>
      )}
      {/* Top Gradient */}
      <div className="pointer-events-none absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-black/90 to-transparent z-10" />
      {/* Bottom Gradient */}
      <div className="pointer-events-none absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-black/90 to-transparent z-10" />
    </div>
  )
}

export function UseCases() {
  const ref = useRef(null)
  const isInView = useInView(ref, { once: true })

  return (
    <section
      id="usecases"
      ref={ref}
      aria-labelledby="usecases-title"
      className="bg-black h-screen relative flex items-start py-12 -top-20"
    >
      <Container className="h-full">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-10 h-full">
          {/* Left Column */}
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 10 }}
            transition={{ duration: 0.8, delay: 0.1 }}
            className="flex flex-col items-start justify-start pt-10 lg:pr-12"
          >
            <H2 id="usecases-title" color="light" className="text-left">
              Mycelium Technologies
            </H2>
            <P className="mt-4 text-left" color="light">
              A robust infrastructure layer for autonomous AI agents, our technology stack
              delivers a secure, efficient, and intuitive platform for deploying and managing AI agents at scale.
            </P>
          </motion.div>

          {/* Right Columns */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={isInView ? { opacity: 1 } : { opacity: 0 }}
            transition={{ duration: 1, delay: 0.2 }}
            className="lg:col-span-2 h-full"
          >
            <ReviewGrid />
          </motion.div>
        </div>
      </Container>
    </section>
  )
}
