import AltivateLayout from '@/Layouts/AltivateLayout';
import { Head, Link } from '@inertiajs/react';
import { useState, useRef, useEffect } from 'react';
import { ArrowUpRight } from "lucide-react";

const structure = [
  { n: "1", t: "The situation", b: "Who the client is, what their business does, and what was happening before they came to us. The metric that was broken or missing." },
  { n: "2", t: "The diagnosis", b: "What the Growth Audit revealed. The root cause — not the symptom. Why the obvious fix wasn't the right fix." },
  { n: "3", t: "The system we built", b: "Exactly what we did. Which services. Which strategies. What the execution looked like. No vague language — specifics only." },
  { n: "4", t: "The results", b: "Numbers only. Revenue generated, leads captured, conversion rates, traffic, engagement that converted — tied to the original metric that was broken." },
];

interface Metric {
  k: string;
  v: string;
}

interface CaseStudy {
  id: number;
  title: string;
  slug: string;
  tag: string | null;
  location: string | null;
  excerpt: string | null;
  metrics: Metric[] | null;
  media?: {
    url: string;
  };
}

export default function CaseStudies({ caseStudies }: { caseStudies: CaseStudy[] }) {
  const [activeIndex, setActiveIndex] = useState(0);
  const scrollRef = useRef<HTMLDivElement>(null);

  const handleScroll = () => {
    if (!scrollRef.current) return;
    const { scrollLeft, offsetWidth } = scrollRef.current;
    const children = scrollRef.current.children;
    
    let closestIndex = 0;
    let minDistance = Infinity;

    for (let i = 0; i < children.length; i++) {
        const child = children[i] as HTMLElement;
        const distance = Math.abs(child.offsetLeft - scrollLeft - (offsetWidth / 2) + (child.offsetWidth / 2));
        if (distance < minDistance) {
            minDistance = distance;
            closestIndex = i;
        }
    }
    
    if (closestIndex !== activeIndex) {
        setActiveIndex(closestIndex);
    }
  };

  const scrollTo = (index: number) => {
    if (!scrollRef.current) return;
    const children = scrollRef.current.children;
    if (children[index]) {
        (children[index] as HTMLElement).scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    }
  };
  return (
    <AltivateLayout title="Case Studies" description="Real work. Real clients. Real numbers. Selected case studies from our work with Nigerian SMEs and African diaspora businesses.">
      <div>
        <section className="container-x pt-32 pb-24 md:pt-40 md:pb-32">
          <p className="eyebrow">Case studies</p>
          <h1 className="font-display mt-6 text-[clamp(2.5rem,7vw,5.5rem)] leading-[0.95]">
            Real work. Real clients. <span className="italic">Real numbers.</span>
          </h1>
          <p className="mt-8 max-w-2xl text-lg text-muted-foreground">
            We don't publish case studies to look impressive. We publish them because they show you exactly how we think, how we work, and what kind of results your business could realistically expect.
          </p>
        </section>

        {/* STRUCTURE */}
        <section className="border-y border-border bg-secondary/30">
          <div className="container-x py-20">
            <p className="eyebrow">How each case study is written</p>
            <h2 className="font-display mt-4 text-4xl">Every post follows the same format.</h2>
            <div className="mt-12 grid gap-px bg-border sm:grid-cols-2 lg:grid-cols-4 rounded-3xl overflow-hidden border border-border">
              {structure.map((s) => (
                <div key={s.n} className="bg-background p-8">
                  <div className="font-display text-4xl text-accent">{s.n}</div>
                  <h3 className="font-display mt-6 text-xl">{s.t}</h3>
                  <p className="mt-3 text-sm text-muted-foreground">{s.b}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* CASES SLIDER */}
        <section className="container-x py-24 relative group/slider">
            <div className="flex items-center justify-between mb-12">
                <h2 className="font-display text-4xl">Success Stories</h2>
                <div className="flex items-center gap-3">
                    <button 
                        onClick={() => {
                            const el = document.getElementById('case-slider');
                            el?.scrollBy({ left: -400, behavior: 'smooth' });
                        }}
                        className="h-12 w-12 rounded-full border border-border flex items-center justify-center hover:bg-ink hover:text-white transition-all shadow-sm"
                    >
                        <ArrowUpRight className="h-5 w-5 rotate-[-135deg]" />
                    </button>
                    <button 
                        onClick={() => {
                            const el = document.getElementById('case-slider');
                            el?.scrollBy({ left: 400, behavior: 'smooth' });
                        }}
                        className="h-12 w-12 rounded-full border border-border flex items-center justify-center hover:bg-ink hover:text-white transition-all shadow-sm"
                    >
                        <ArrowUpRight className="h-5 w-5" />
                    </button>
                </div>
            </div>

            <div 
                ref={scrollRef}
                onScroll={handleScroll}
                className="flex gap-6 md:gap-10 overflow-x-auto snap-x snap-mandatory scrollbar-hide pb-12 -mx-4 px-4 md:-mx-8 md:px-8"
                style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
            >
                {caseStudies.length > 0 ? caseStudies.map((c) => (
                    <div key={c.id} className="min-w-[88vw] md:min-w-[48%] snap-center">
                        <article className="flex flex-col h-full rounded-3xl border border-border bg-card p-6 md:p-12 transition-all hover:shadow-xl">
                            <div className="flex flex-wrap items-center justify-between gap-3 text-[10px] uppercase tracking-wider text-muted-foreground">
                                <span className="rounded-full border border-border px-2.5 py-1">{c.tag}</span>
                                <span>{c.location}</span>
                            </div>
                            <h2 className="font-display mt-6 md:mt-8 max-w-3xl text-xl md:text-2xl leading-[1.1]">{c.title}</h2>
                            <p className="mt-4 md:mt-6 text-sm text-muted-foreground line-clamp-3">{c.excerpt}</p>
                            
                            <div className="flex-1" /> {/* Spacer to force bottom alignment */}

                            <div className="mt-8 md:mt-12 grid grid-cols-2 sm:grid-cols-3 gap-y-6 md:gap-y-8 gap-x-4">
                                {c.metrics?.map((m, i) => (
                                    <div key={i} className="flex flex-col">
                                        <div className="font-display text-2xl md:text-3xl text-accent leading-none">{m.k}</div>
                                        <div className="mt-2 text-[9px] md:text-[10px] uppercase tracking-wider text-muted-foreground leading-relaxed max-w-[120px]">{m.v}</div>
                                    </div>
                                ))}
                            </div>

                            <Link href={route('case_studies.show', c.slug)} className="mt-8 md:mt-10 inline-flex items-center gap-2 text-sm hover:text-accent group/btn">
                                View Full Study 
                                <ArrowUpRight className="h-4 w-4 group-hover/btn:translate-x-0.5 group-hover/btn:-translate-y-0.5 transition-transform" />
                            </Link>
                        </article>
                    </div>
                )) : (
                    <div className="w-full py-20 text-center text-muted-foreground italic">
                        No case studies found. Check back soon.
                    </div>
                )}
            </div>

            {/* DOTS */}
            {caseStudies.length > 1 && (
                <div className="flex items-center justify-center gap-3 mt-4">
                    {caseStudies.map((_, i) => (
                        <button
                            key={i}
                            onClick={() => scrollTo(i)}
                            className={`h-1.5 transition-all duration-300 rounded-full ${
                                activeIndex === i ? 'w-8 bg-accent' : 'w-1.5 bg-border hover:bg-muted-foreground'
                            }`}
                        />
                    ))}
                </div>
            )}

            <style dangerouslySetInnerHTML={{ __html: `
                .scrollbar-hide::-webkit-scrollbar { display: none; }
            `}} />
        </section>

        <section className="container-x pb-24">
          <div className="rounded-3xl border border-border bg-primary p-12 text-primary-foreground md:p-16">
            <p className="eyebrow !text-primary-foreground/60">These results didn't happen by accident.</p>
            <h2 className="font-display mt-4 max-w-3xl text-4xl md:text-5xl leading-[1.05]">
              They happened because of <span className="italic text-accent">a system.</span>
            </h2>
            <p className="mt-6 max-w-xl text-primary-foreground/70">
              Book your free Growth Audit call and find out what a system built for your business could look like.
            </p>
            <Link
              href="/audit"
              className="mt-8 inline-flex h-12 items-center gap-3 rounded-full bg-accent px-6 text-sm font-medium text-accent-foreground transition-all hover:-translate-y-0.5"
            >
              Book a free audit call <ArrowUpRight className="h-4 w-4" />
            </Link>
          </div>
        </section>
      </div>
    </AltivateLayout>
  );
}
