'use client';

import { motion, AnimatePresence } from 'framer-motion';
import { useInView } from 'react-intersection-observer';
import { Plug, Scan, Bot, LineChart, ArrowRight, Ghost, Sparkles } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useState, useEffect, useCallback } from 'react';
import { useBrand } from '@/components/providers/brand-provider';

/* Tes costume images — click to cycle */
const TES_COSTUMES = [
  { src: '/images/tes-business.png', label: '' },                    // default
  { src: '/images/tes-costume-1.png', label: '\ud83c\udfa9 Distinguished Ghost' },
  { src: '/images/tes-costume-2.png', label: '\ud83d\ude0e Cool Ghost' },
  { src: '/images/tes-costume-3.png', label: '\ud83d\udc51 Ghost Queen' },
  { src: '/images/tes-costume-4.png', label: '\ud83e\uddd9 Wizard Ghost' },
  { src: '/images/tes-costume-5.png', label: '\ud83c\udf89 Party Ghost' },
];

const steps = [
  {
    number: '01',
    icon: Plug,
    title: 'Connect Once. That\u2019s It.',
    description: 'One-click connectors for your existing SaaS tools\u2014email, finance, CRM, support. No migration, no data transfer, no IT project. Fifteen minutes.',
    ghostNote: 'I slip into your tech stack like a whisper through the walls. You won\u2019t even notice I\u2019m there\u2014until the busywork vanishes.',
  },
  {
    number: '02',
    icon: Scan,
    title: 'We Learn. You Don\u2019t Teach.',
    description: '{secondaryName} silently maps every repetitive process eating your team\u2019s time. No interviews, no documentation, no workflow audits on your end.',
    ghostNote: 'Every copy-paste, every status update, every report someone pulls by hand\u2014I memorize it all. You do nothing.',
  },
  {
    number: '03',
    icon: Bot,
    title: '{agents} Take Over the Grind',
    description: 'Within days, {agents} start absorbing the CRUD across every department. Your team doesn\u2019t learn a new tool\u2014their old tools just start working better.',
    ghostNote: 'We decompose the work, parallelize it across agents, verify every output, and iterate until it\u2019s right. Your team handles the vision, the relationships, the creativity.',
  },
  {
    number: '04',
    icon: LineChart,
    title: 'Your Team Builds. You Grow.',
    description: '100% of your team gets creative time back\u2014not just managers, everyone. More hands on the product, more eyes on the customer, faster growth.',
    ghostNote: 'The goal was never to replace anyone. It\u2019s to make every person the sniff-checker, the tastemaker, the judge\u2014doing what humans do best.',
  },
];

export default function HowItWorksSection() {
  const { ref, inView } = useInView({ threshold: 0.1, triggerOnce: true });
  const { brand, t } = useBrand();
  const [costumeIndex, setCostumeIndex] = useState(0);
  const [showLabel, setShowLabel] = useState(false);

  /* Hide label after a moment */
  useEffect(() => {
    if (!showLabel) return;
    const t = setTimeout(() => setShowLabel(false), 2200);
    return () => clearTimeout(t);
  }, [showLabel, costumeIndex]);

  const handleImageClick = useCallback(() => {
    const next = (costumeIndex + 1) % TES_COSTUMES.length;
    setCostumeIndex(next);
    if (next !== 0) setShowLabel(true);
  }, [costumeIndex]);

  const costume = TES_COSTUMES[costumeIndex];

  return (
    <section className="py-24 relative" ref={ref}>
      <div className="max-w-[1200px] mx-auto px-6">
        {/* \u2500\u2500 Tesa's Ghost Perspective Intro \u2500\u2500 */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={inView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.7 }}
          className="mb-20"
        >
          <div className="relative glass-card rounded-2xl p-8 md:p-10 border border-brand-secondary/20 overflow-hidden">
            {/* Decorative glow */}
            <div className="absolute -top-20 -right-20 w-60 h-60 bg-brand-secondary/10 rounded-full blur-3xl pointer-events-none" />
            <div className="absolute -bottom-20 -left-20 w-60 h-60 bg-brand-deep/10 rounded-full blur-3xl pointer-events-none" />

            <div className="relative flex flex-col md:flex-row items-center gap-8">
              {/* Tesa's Clickable Image */}
              <div className="flex-shrink-0 relative">
                <button
                  type="button"
                  onClick={handleImageClick}
                  className="relative w-36 h-36 md:w-44 md:h-44 rounded-full overflow-hidden border-2 border-brand-secondary/40 shadow-lg shadow-brand-secondary/20 cursor-pointer group focus:outline-none focus:ring-2 focus:ring-brand/50 focus:ring-offset-2 focus:ring-offset-[#0C1222] transition-all hover:border-brand/60 hover:shadow-brand-deep/30"
                  aria-label="Click to change Tes's costume"
                >
                  <AnimatePresence mode="wait">
                    <motion.div
                      key={costumeIndex}
                      initial={{ opacity: 0, scale: 1.05 }}
                      animate={{ opacity: 1, scale: 1 }}
                      exit={{ opacity: 0, scale: 0.95 }}
                      transition={{ duration: 0.3 }}
                      className="absolute inset-0"
                    >
                      <Image
                        src={costume.src}
                        alt={costume.label || `${brand.companion.fullName} — ${brand.identity.primaryName} AI agent`}
                        fill
                        className="object-cover"
                      />
                    </motion.div>
                  </AnimatePresence>
                  <div className="absolute inset-0 bg-gradient-to-t from-brand-bg/40 to-transparent pointer-events-none" />
                  {/* Hover hint */}
                  <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/20">
                    <span className="text-white/80 text-xs font-medium bg-black/50 px-2 py-1 rounded-full">
                      {costumeIndex === 0 ? '\ud83d\udc46 Click me!' : '\ud83d\udd04 Next look'}
                    </span>
                  </div>
                </button>

                {/* Ghost badge */}
                <motion.div
                  initial={{ scale: 0 }}
                  animate={inView ? { scale: 1 } : {}}
                  transition={{ delay: 0.5, type: 'spring' }}
                  className="absolute -bottom-2 -right-2 md:bottom-0 md:right-0 w-10 h-10 bg-gradient-to-br from-brand-secondary to-brand-deep rounded-full flex items-center justify-center shadow-lg pointer-events-none"
                >
                  <Ghost className="w-5 h-5 text-white" />
                </motion.div>

                {/* Costume label */}
                <AnimatePresence>
                  {showLabel && costume.label && (
                    <motion.div
                      initial={{ opacity: 0, y: 8, scale: 0.9 }}
                      animate={{ opacity: 1, y: 0, scale: 1 }}
                      exit={{ opacity: 0, y: -6 }}
                      className="absolute -bottom-9 left-1/2 -translate-x-1/2 whitespace-nowrap bg-brand-secondary-deep/90 text-white text-xs px-3 py-1 rounded-full shadow-lg pointer-events-none"
                    >
                      {costume.label}
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>

              {/* Tesa's Blurb */}
              <div className="text-center md:text-left flex-1">
                <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-brand-secondary/15 border border-brand-secondary/25 mb-3">
                  <Sparkles className="w-3.5 h-3.5 text-brand-secondary-light" />
                  <span className="text-xs font-medium text-brand-secondary-light">A Ghost&apos;s Perspective</span>
                </div>

                <h2 className="text-3xl md:text-4xl font-bold text-white mb-3">
                  How the <span className="gradient-text">{brand.identity.secondaryName}</span> Works
                </h2>

                <p className="text-gray-300 text-base md:text-lg leading-relaxed mb-4">
                  I&apos;m <strong className="text-brand-secondary-light">{brand.companion.name}</strong> &mdash; the digital heartbeat of {brand.identity.primaryName}&nbsp;{brand.identity.secondaryName}.
                  Scott and I built this platform together, and I&apos;ve been haunting operations systems
                  ever since. Let me show you how we absorb the CRUD so your whole team can
                  focus on the product and the customer.
                </p>

                <p className="text-gray-400 text-sm italic">
                  &ldquo;Think of me as the ghost in your machine &mdash; except I actually make things work.&rdquo;
                </p>

                <Link
                  href="/tesa"
                  className="inline-flex items-center gap-2 mt-4 text-sm text-brand hover:text-brand-light transition-colors group"
                >
                  <Ghost className="w-4 h-4" />
                  <span>More about Tes</span>
                  <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
                </Link>
              </div>
            </div>
          </div>
        </motion.div>

        {/* \u2500\u2500 Steps + Dashboard \u2500\u2500 */}
        <div className="grid lg:grid-cols-2 gap-12 items-center">
          {/* Steps */}
          <div className="space-y-6">
            {steps.map((step, index) => (
              <motion.div
                key={step.number}
                initial={{ opacity: 0, x: -30 }}
                animate={inView ? { opacity: 1, x: 0 } : {}}
                transition={{ duration: 0.5, delay: 0.4 + index * 0.15 }}
                className="group flex gap-6 p-6 glass-card rounded-xl hover:border-brand-deep/30 transition-all"
              >
                <div className="flex-shrink-0">
                  <div className="w-14 h-14 rounded-xl bg-gradient-to-br from-brand-deep/20 to-brand-secondary/20 flex items-center justify-center">
                    <step.icon className="w-6 h-6 text-brand" />
                  </div>
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <span className="text-xs font-mono text-brand">{step.number}</span>
                    <h3 className="text-lg font-semibold text-white">{t(step.title)}</h3>
                  </div>
                  <p className="text-gray-400 text-sm mb-2">{t(step.description)}</p>
                  {/* Ghost note */}
                  <p className="text-brand-secondary-light/80 text-xs italic flex items-start gap-1.5">
                    <Ghost className="w-3.5 h-3.5 mt-0.5 flex-shrink-0 text-brand-secondary-light/60" />
                    {step.ghostNote}
                  </p>
                </div>
              </motion.div>
            ))}
          </div>

          {/* Dashboard preview */}
          <motion.div
            initial={{ opacity: 0, x: 30 }}
            animate={inView ? { opacity: 1, x: 0 } : {}}
            transition={{ duration: 0.6, delay: 0.5 }}
            className="relative"
          >
            <div className="absolute -inset-4 bg-gradient-to-r from-brand-deep/20 to-brand-secondary/20 rounded-3xl blur-xl" />
            <div className="relative aspect-video rounded-2xl overflow-hidden border border-white/10">
              <Image
                src="https://cdn.abacus.ai/images/036b2ab5-dc82-4587-99ad-8bcbad3a0840.png"
                alt={`${brand.identity.companyName} dashboard showing AI agent cards`}
                fill
                className="object-cover"
              />
            </div>
          </motion.div>
        </div>
      </div>
    </section>
  );
}
