"use client";

import Image from "next/image";
import Link from "next/link";
import { ArrowRight, Share2 } from "lucide-react";
import Footer from "@/components/Footer";

export default function WorkDetailClient({ project, nextProject }: { project: any, nextProject: any }) {
    const isInstagram = (url: string) => {
        return url.includes('instagram.com');
    };

    const isVideo = (url: string) => {
        return url.includes('youtube.com') || url.includes('vimeo.com') || url.endsWith('.mp4');
    };

    // Ultra-safety check for gallery and category arrays
    const parseSafe = (data: any) => {
        let current = data;
        try {
            // Aggressively parse up to 3 times to handle double-quotes and double-encoding
            for (let i = 0; i < 3; i++) {
                if (typeof current === 'string' && (current.trim().startsWith('[') || current.trim().startsWith('"'))) {
                    current = JSON.parse(current);
                } else {
                    break;
                }
            }
            return Array.isArray(current) ? current : (typeof current === 'string' && current ? [current] : []);
        } catch (e) {
            return Array.isArray(current) ? current : (typeof current === 'string' && current ? [current] : []);
        }
    };

    const gallery = parseSafe(project.gallery);
    const categories = parseSafe(project.category);

    // Helper to get Instagram embed URL
    const getInstaEmbedUrl = (url: string) => {
        const cleanUrl = url.split('?')[0];
        return `${cleanUrl}${cleanUrl.endsWith('/') ? '' : '/'}embed`;
    };

    return (
        <main className="min-h-screen bg-[#f5f5f0] text-black pt-24">
            
            {/* 1. Editorial Header Section */}
            <section className="pt-32 pb-20 px-6 md:px-12 border-b border-black/10">
                <div className="max-w-7xl mx-auto">
                    {/* Top Line */}
                    <div className="w-full h-px bg-black/10 mb-20" />
                    
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-16 items-start">
                        {/* Left: Client Name */}
                        <div className="lg:col-span-5">
                            <span className="text-[10px] tracking-[0.3em] uppercase text-black/30 block mb-6">
                                {categories.join(" / ")} / {project.year}
                            </span>
                            <h1 className="editorial-headline text-5xl md:text-7xl lg:text-8xl text-black uppercase leading-none">
                                {project.client || project.title}
                            </h1>
                        </div>

                        {/* Middle: Minimalist Line (Reference style) */}
                        <div className="hidden lg:block lg:col-span-2 pt-12">
                            <div className="w-20 h-px bg-black/40 mx-auto" />
                        </div>

                        {/* Right: Description */}
                        <div className="lg:col-span-5 pt-2 lg:pt-8">
                            <p className="text-[15px] md:text-[18px] text-black/70 leading-[1.8] font-medium italic">
                                {project.narrative_desc || project.subtitle}
                            </p>
                            <div className="mt-12 flex flex-wrap gap-x-8 gap-y-4">
                                <div>
                                    <h4 className="text-[9px] tracking-[0.2em] uppercase text-black/30 mb-1">Rol</h4>
                                    <span className="text-[11px] font-bold uppercase">{project.role || "Kreatif Direktörlük"}</span>
                                </div>
                                <div>
                                    <h4 className="text-[9px] tracking-[0.2em] uppercase text-black/30 mb-1">Konum</h4>
                                    <span className="text-[11px] font-bold uppercase">{project.location || "Muğla / Dijital"}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Bottom Line */}
                    <div className="w-full h-px bg-black/10 mt-20" />
                </div>
            </section>

            {/* 2. Project Feed (Gallery & Instagram) */}
            <section className="py-24 px-6 md:px-12">
                <div className="max-w-4xl mx-auto space-y-32">
                    {/* Hero Image First */}
                    <div className="relative aspect-[16/10] w-full overflow-hidden border border-black/5 shadow-2xl bg-[#e2d1c1] p-1">
                         <div className="relative w-full h-full overflow-hidden">
                            <Image
                                src={project.hero_image || "https://images.unsplash.com/photo-1550745165-9bc0b252726f"}
                                alt={project.title}
                                fill
                                className="object-cover"
                                priority
                            />
                         </div>
                    </div>

                    {/* Gallery / Instagram Feed */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-24 mt-24">
                        {gallery.map((item: string, idx: number) => (
                            <div key={idx} className="space-y-8 animate-reveal">
                            <div className="flex items-center gap-4 text-[10px] font-bold text-black/20 tracking-widest uppercase">
                                <span>0{idx + 1}</span>
                                <div className="h-px flex-grow bg-black/5" />
                                <span>{isInstagram(item) ? "INSTAGRAM FEED" : "PRODUCTION VIEW"}</span>
                            </div>

                            {isInstagram(item) ? (
                                <div className="flex justify-center">
                                    <div className="w-full max-w-[540px] border border-black/10 bg-white shadow-xl overflow-hidden rounded-xl">
                                        <iframe
                                            src={getInstaEmbedUrl(item)}
                                            className="w-full h-[700px] border-0"
                                            scrolling="no"
                                            allowTransparency={true}
                                            allowFullScreen
                                        />
                                    </div>
                                </div>
                            ) : (
                                <div className="relative aspect-[16/10] border border-black/5 bg-black/5 shadow-lg overflow-hidden group">
                                    {isVideo(item) ? (
                                        <iframe
                                            src={item}
                                            className="w-full h-full"
                                            allowFullScreen
                                        />
                                    ) : (
                                        <Image 
                                            src={item} 
                                            alt={`Gallery ${idx}`} 
                                            fill 
                                            className="object-cover transition-transform duration-1000 group-hover:scale-105" 
                                        />
                                    )}
                                </div>
                            )}
                        </div>
                    ))}
                    </div>
                </div>
            </section>
            
            {/* Minimal CTA Section */}
            <section className="py-32 px-6 md:px-12 bg-[#f5f5f0]">
                <div className="max-w-7xl mx-auto text-center">
                    <div className="w-full h-px bg-black/10 mb-24" />
                    <h2 className="editorial-headline text-3xl md:text-5xl lg:text-6xl text-black uppercase leading-tight mb-16 max-w-4xl mx-auto">
                        CESUR, İNSANCIL VE <br /> İZ BIRAKAN PROJELERİ <br /> <span className="text-primary">BİRLİKTE</span> ŞEKİLLENDİRELİM.
                    </h2>
                    
                    <Link 
                        href="/contact" 
                        className="inline-flex items-center justify-center w-32 h-32 md:w-40 md:h-40 rounded-full bg-primary text-white text-[10px] font-bold uppercase tracking-widest hover:scale-110 transition-all duration-500 shadow-xl shadow-primary/20 group"
                    >
                        <span className="group-hover:scale-110 transition-transform">İLETİŞİME GEÇ</span>
                    </Link>
                </div>
            </section>

            {/* Next Project - Editorial Style */}
            {nextProject && (
                <section className="relative border-y border-black/10 group overflow-hidden bg-[#f9f6ef] hover:bg-[#e2d1c1] transition-colors duration-700">
                    <Link href={`/works/${nextProject.slug}`} className="block py-40 px-6 md:px-12">
                        <div className="max-w-7xl mx-auto text-center space-y-12">
                            <span className="text-[10px] tracking-[0.5em] text-black/30 uppercase block">SIRADAKİ ÇALIŞMA</span>
                            <h2 className="editorial-headline text-5xl md:text-8xl lg:text-9xl text-black uppercase transition-all duration-700 group-hover:scale-[0.98]">
                                {nextProject.title}
                            </h2>
                            <div className="flex items-center justify-center gap-6 text-black/40 font-bold text-[12px] tracking-[0.3em] uppercase">
                                <div className="w-12 h-px bg-black/20" />
                                PROJEYİ GÖR
                                <div className="w-12 h-px bg-black/20" />
                            </div>
                        </div>
                    </Link>
                </section>
            )}

            <Footer />
        </main>
    );
}