"use client";

import { useParams } from "next/navigation";
import Link from "next/link";
import { useState, useRef, useEffect } from "react";
import { getCaseStudyBySlug } from "@/data/casestudies";

// ── Count-up hook ─────────────────────────────────────────────────────────────
function useCountUp(target: number, duration: number = 1800, start: boolean = false) {
    const [count, setCount] = useState(0);
    useEffect(() => {
        if (!start || target === 0) return;
        let startTime: number | null = null;
        const step = (timestamp: number) => {
            if (!startTime) startTime = timestamp;
            const progress = Math.min((timestamp - startTime) / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 3);
            setCount(Math.floor(eased * target));
            if (progress < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
    }, [start, target, duration]);
    return count;
}

function parseStatNumber(val: string): { num: number; suffix: string } {
    const match = val.match(/^(\d+(?:\.\d+)?)(.*)/);
    if (match) return { num: parseFloat(match[1]), suffix: match[2].trim() };
    return { num: 0, suffix: val };
}

function AnimatedStat({ val, label }: { val: string; label: string }) {
    const { num, suffix } = parseStatNumber(val);
    const hasNumber = num > 0;
    const [started, setStarted] = useState(false);
    const ref = useRef<HTMLDivElement>(null);
    const count = useCountUp(num, 1800, started && hasNumber);

    useEffect(() => {
        if (!ref.current) return;
        const observer = new IntersectionObserver(
            ([entry]) => { if (entry.isIntersecting) setStarted(true); },
            { threshold: 0.3 }
        );
        observer.observe(ref.current);
        return () => observer.disconnect();
    }, []);

    return (
        <div ref={ref}>
            <div className="cs-stat-value">
                {hasNumber ? `${count}${suffix ? " " + suffix : ""}` : val}
            </div>
            <div className="cs-stat-label">{label}</div>
        </div>
    );
}

// Split title: ceil(n/2) words on line 1, rest on line 2
// e.g. 6 words → 3+3, 4 words → 2+2, 5 words → 3+2
function splitTitle(title: string): [string, string] {
    const words = title.trim().split(/\s+/);
    const mid = Math.ceil(words.length / 2);
    return [words.slice(0, mid).join(" "), words.slice(mid).join(" ")];
}

export default function CaseStudySlugPage() {
    const params = useParams();
    const slugValue = typeof params?.slug === "string"
        ? params.slug
        : Array.isArray(params?.slug) ? params.slug[0] : null;
    const caseStudy = slugValue ? getCaseStudyBySlug(slugValue) || null : null;

    if (!caseStudy) {
        const slug = slugValue || "unknown";
        return (
            <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "#fff" }}>
                <div style={{ textAlign: "center", padding: "32px" }}>
                    <h1 style={{ fontSize: "36px", fontWeight: 700, marginBottom: "16px", color: "#0F1B43", fontFamily: "Helvetica, Arial, sans-serif" }}>
                        Case Study Not Found
                    </h1>
                    <p style={{ fontSize: "20px", marginBottom: "24px", color: "#5D6371", fontFamily: "Helvetica, Arial, sans-serif" }}>
                        The case study &quot;{slug}&quot; could not be found.
                    </p>
                    <Link href="/case-studies" style={{ display: "inline-block", background: "#b53855", color: "#fff", padding: "12px 32px", borderRadius: "8px", textDecoration: "none", fontWeight: 700, fontFamily: "Helvetica, Arial, sans-serif" }}>
                        Back to Case Studies
                    </Link>
                </div>
            </div>
        );
    }

    const approachTitle = caseStudy.approachTitle ?? "In Depth Approach";
    const aspirationsLabel = caseStudy.aspirationsLabel ?? "Aspirations";
    const stats = [
        { val: caseStudy.stat1Value, label: caseStudy.stat1Label },
        { val: caseStudy.stat2Value, label: caseStudy.stat2Label },
        ...(caseStudy.stat3Value ? [{ val: caseStudy.stat3Value, label: caseStudy.stat3Label ?? "" }] : []),
    ];

    return (
        <>
            <style>{`
                /* ── Content wrapper ── */
                .cs-cw {
                    max-width: 1400px;
                    margin: 0 auto;
                    padding: 0 5.5%;
                    box-sizing: border-box;
                }
                @media (max-width: 1200px) { .cs-cw { padding: 0 4.5%; } }
                @media (max-width: 767px)  { .cs-cw { padding: 0 20px; } }

                /* ── Hero — position UNCHANGED: bottom -60px ── */
                .cs-hero {
                    position: relative;
                    margin-top: 105px;
                    margin-bottom: 60px;
                }
                .cs-hero-banner {
                    background: center 30% / cover no-repeat;
                    min-height: 320px;
                    height: 60vh;
                    width: 100%;
                }
                .cs-hero-badge-wrap {
                    position: absolute;
                    bottom: -60px;
                    left: 0;
                    right: 0;
                    z-index: 10;
                }
                .cs-hero-badge {
                    background: linear-gradient(-90deg, #b53855, #62c0e2);
                    padding: 45px 85px;
                    border-radius: 10px 15px 0 0;
                    display: inline-block;
                    max-width: 85%;
                }
                .cs-hero-badge h1 {
                    color: #fff;
                    font-size: 38px;
                    font-weight: 700;
                    margin: 0;
                    font-family: Helvetica, Arial, sans-serif;
                    line-height: 1.3;
                    white-space: normal;
                    word-wrap: break-word;
                }

                /* Scale title box — bottom stays -60px on desktop/tablet */
                @media (max-width: 1024px) {
                    .cs-hero-banner { min-height: 280px; height: 55vh; }
                    .cs-hero-badge { padding: 35px 50px; max-width: 90%; }
                    .cs-hero-badge h1 { font-size: 28px; }
                }
                @media (max-width: 767px) {
                    .cs-hero { margin-bottom: 30px; }
                    .cs-hero-banner { min-height: 260px; height: 70vw; }
                    .cs-hero-badge-wrap { bottom: -30px; }
                    .cs-hero-badge { padding: 22px 28px; max-width: 95%; border-radius: 8px 10px 0 0; }
                    .cs-hero-badge h1 { font-size: 20px; }
                }
                @media (max-width: 480px) {
                    .cs-hero { margin-bottom: 25px; }
                    .cs-hero-banner { min-height: 220px; height: 75vw; }
                    .cs-hero-badge-wrap { bottom: -25px; }
                    .cs-hero-badge { padding: 16px 20px; max-width: 96%; }
                    .cs-hero-badge h1 { font-size: 16px; }
                }

                /* ── Shared ── */
                .cs-underline {
                    width: 120px;
                    border-bottom: 2px solid #b53855;
                    margin-top: 8px;
                    margin-bottom: 28px;
                }
                .cs-cyan-bar { width: 100%; height: 8px; background: #62c0e2; }

                /* ── Two-col ── */
                .cs-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 60px; }
                @media (max-width: 1024px) { .cs-two-col { gap: 40px; } }
                @media (max-width: 767px)  { .cs-two-col { grid-template-columns: 1fr; gap: 32px; } }

                /* ── Stats ── */
                .cs-stats { display: grid; gap: 0; }
                .cs-stat-value { font-family: Helvetica, Arial, sans-serif; font-size: 52px; font-weight: 700; color: #1a1a1a; line-height: 1; margin-bottom: 8px; }
                .cs-stat-label { font-family: Helvetica, Arial, sans-serif; font-size: 15px; color: #5D6371; }

                @media (max-width: 767px) {
                    .cs-stats { grid-template-columns: 1fr 1fr !important; gap: 32px !important; }
                    .cs-stat-value { font-size: 34px; }
                }
                @media (max-width: 480px) {
                    .cs-stats { grid-template-columns: 1fr !important; gap: 24px !important; }
                    .cs-stat-value { font-size: 28px; }
                }

                /* ── Typography ── */
                .cs-section-heading { font-family: Helvetica, Arial, sans-serif; font-size: 28px; font-weight: 700; color: #1a1a1a; margin-bottom: 0; }
                .cs-body { font-family: Helvetica, Arial, sans-serif; font-size: 16px; color: #5D6371; line-height: 1.75; margin: 0; }

                @media (max-width: 1024px) { .cs-section-heading { font-size: 24px; } }
                @media (max-width: 767px) {
                    .cs-section-heading { font-size: 20px; }
                    .cs-body { font-size: 15px; }
                }

                /* ── Section spacing ── */
                .cs-section-pad { padding-top: 60px; padding-bottom: 40px; }
                .cs-section-inner { padding: 60px 0; }
                @media (max-width: 767px) {
                    .cs-section-pad  { padding-top: 36px; padding-bottom: 24px; }
                    .cs-section-inner { padding: 40px 0; }
                }
            `}</style>

            <div style={{ minHeight: "100vh", background: "#fff" }}>

                {/* ── HERO ── */}
                <section className="cs-hero">
                    <div
                        className="cs-hero-banner"
                        style={{ backgroundImage: `url('${caseStudy.image}')` }}
                    />
                    <div className="cs-cw cs-hero-badge-wrap">
                        <div className="cs-hero-badge">
                            <h1>
                                {splitTitle(caseStudy.title)[0]}
                                {splitTitle(caseStudy.title)[1] && <><br />{splitTitle(caseStudy.title)[1]}</>}
                            </h1>
                        </div>
                    </div>
                </section>

                {/* ── AT A GLANCE + COMPANY ── */}
                <section className="cs-section-pad">
                    <div className="cs-cw">
                        <div className="cs-two-col">
                            <div>
                                <h2 className="cs-section-heading">At a Glance</h2>
                                <div className="cs-underline" />
                                <p className="cs-body">{caseStudy.atAGlanceDescription}</p>
                            </div>
                            <div>
                                <h2 className="cs-section-heading">{caseStudy.companyName}</h2>
                                <div className="cs-underline" />
                                <p className="cs-body">{caseStudy.companyDescription}</p>
                            </div>
                        </div>
                    </div>
                </section>

                <div style={{ borderTop: "1px solid #e5e7eb" }} />

                {/* ── STATS ROW ── */}
                <section style={{ paddingTop: "48px", paddingBottom: "48px" }}>
                    <div className="cs-cw">
                        <div className="cs-stats" style={{ gridTemplateColumns: `repeat(${stats.length}, 1fr)` }}>
                            {stats.map((stat, i) => (
                                <AnimatedStat key={i} val={stat.val} label={stat.label} />
                            ))}
                        </div>
                    </div>
                </section>

                {/* ── ASPIRATIONS ── */}
                <section style={{ background: "#CF87B0", padding: "52px 0" }}>
                    <div className="cs-cw">
                        <h2 style={{ fontFamily: "Helvetica, Arial, sans-serif", fontSize: "28px", fontWeight: 700, color: "#fff", marginBottom: 0 }}>
                            {aspirationsLabel}
                        </h2>
                        <div style={{ width: "120px", borderBottom: "2px dotted rgba(255,255,255,0.6)", marginTop: "8px", marginBottom: "24px" }} />
                        <p style={{ fontFamily: "Helvetica, Arial, sans-serif", fontSize: "16px", color: "#fff", lineHeight: 1.8, margin: 0, maxWidth: "900px" }}>
                            {caseStudy.aspirationsText}
                        </p>
                    </div>
                </section>

                <div className="cs-cyan-bar" />

                {/* ── SOLUTION OFFERED ── */}
                <section className="cs-section-inner">
                    <div className="cs-cw">
                        <p style={{ fontFamily: "Helvetica, Arial, sans-serif", fontSize: "13px", color: "#9CA3AF", letterSpacing: "0.05em", textTransform: "uppercase", marginBottom: "20px" }}>
                            Solution offered
                        </p>
                        <p style={{ fontFamily: "Helvetica, Arial, sans-serif", fontSize: "22px", fontWeight: 700, color: "#1a1a1a", lineHeight: 1.6, marginBottom: "32px" }}>
                            {caseStudy.solutionDescription}
                        </p>
                        {caseStudy.solutionPoints.length > 0 && (
                            <ul style={{ margin: 0, padding: 0, listStyle: "none" }}>
                                {caseStudy.solutionPoints.map((pt, i) => (
                                    <li key={i} style={{ fontFamily: "Helvetica, Arial, sans-serif", fontSize: "16px", color: "#5D6371", lineHeight: 1.7, marginBottom: "12px" }}>
                                        — {pt}
                                    </li>
                                ))}
                            </ul>
                        )}
                    </div>
                </section>

                <div className="cs-cyan-bar" />

                {/* ── IN DEPTH APPROACH ── */}
                {caseStudy.approachPoints.length > 0 && (
                    <section className="cs-section-inner">
                        <div className="cs-cw">
                            <h2 className="cs-section-heading">{approachTitle}</h2>
                            <div className="cs-underline" />
                            <ul style={{ margin: 0, paddingLeft: "20px" }}>
                                {caseStudy.approachPoints.map((pt, i) => (
                                    <li key={i} style={{ fontFamily: "Helvetica, Arial, sans-serif", fontSize: "15px", color: "#5D6371", lineHeight: 1.75, marginBottom: "10px" }}>
                                        {pt}
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </section>
                )}
            </div>
        </>
    );
}