import React, { useState, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { useMockStore } from '../../data/mockStore';
import { SpotlightCard } from '../../components/SpotlightCard';
import { AnimatedCounter } from '../../components/AnimatedCounter';
import { motion } from 'framer-motion';
import {
    BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer
} from 'recharts';
import {
    ArrowLeft, CheckCircle, Clock, AlertTriangle, PauseCircle, ShieldAlert,
    FileText, DollarSign, GitPullRequest, AlertCircle, Activity, Milestone,
    Shield, ChevronRight, Phone, MessageSquare, Mail, AlertOctagon, TrendingUp, Key, Zap, Camera, Plus, Map, User, Crosshair, Image as ImageIcon, MapPin
} from 'lucide-react';
import ChangeOrderDrawer from '../../components/owner/ChangeOrderDrawer';
import InvoiceDetailModal from '../../components/owner/InvoiceDetailModal';
import CreateItemModal from '../../components/owner/CreateItemModal';

// --- NEOMORPHIC STYLING CONSTANTS ---
const NEO_PANEL_CLASS = "bg-zinc-900/60 backdrop-blur-3xl border border-white/5 shadow-[8px_8px_16px_rgba(0,0,0,0.6),-8px_-8px_16px_rgba(255,255,255,0.02)] rounded-3xl relative overflow-hidden transition-all duration-300";
const NEON_GREEN = "text-[#39ff14] drop-shadow-[0_0_8px_rgba(57,255,20,0.4)]";
const NEON_GOLD = "text-[#fda913] drop-shadow-[0_0_8px_rgba(253,169,19,0.4)]";
const NEON_ORANGE = "text-[#ff4500] drop-shadow-[0_0_8px_rgba(255,69,0,0.4)]";
const NEON_RED = "text-[#ff003c] drop-shadow-[0_0_8px_rgba(255,0,60,0.4)]";
const NEON_BLUE = "text-[#00f0ff] drop-shadow-[0_0_8px_rgba(0,240,255,0.4)]";

// -----------------------------------------------------------------
// SHARED UI COMPONENTS
// -----------------------------------------------------------------

const NeoCard = ({ children, className = "", innerClassName = "", spotlightColor = "rgba(255, 255, 255, 0.05)" }) => (
    <SpotlightCard className={`${NEO_PANEL_CLASS} h-full w-full ${className}`} spotlightColor={spotlightColor}>
        <div className={`relative z-10 w-full h-full p-5 lg:p-6 flex flex-col ${innerClassName}`}>
            {children}
        </div>
    </SpotlightCard>
);

const ProgressBar = ({ progress, goal = 100, colorClass = "bg-[#39ff14]", shadowClass = "shadow-[0_0_10px_#39ff14]", height = "h-1.5" }) => {
    const pct = Math.min((progress / goal) * 100, 100);
    return (
        <div className={`${height} w-full bg-black/80 rounded-full shadow-[inset_0_2px_4px_rgba(0,0,0,0.6)] border border-white/5 relative overflow-hidden flex-1`}>
            <motion.div
                initial={{ width: 0 }}
                animate={{ width: `${pct}%` }}
                transition={{ duration: 1.5, type: "spring", stiffness: 50, damping: 15 }}
                className={`absolute top-0 left-0 h-full rounded-full ${colorClass} ${shadowClass}`}
            />
        </div>
    );
};

const statusConfig = {
    active: { label: 'Active', color: 'text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-500/10', icon: Clock },
    completed: { label: 'Completed', color: 'text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-500/10', icon: CheckCircle },
    delayed: { label: 'Delayed', color: 'text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-500/10', icon: AlertTriangle },
    on_hold: { label: 'On Hold', color: 'text-purple-600 bg-purple-100 dark:text-purple-400 dark:bg-purple-500/10', icon: PauseCircle },
    disputed: { label: 'Disputed', color: 'text-red-600 bg-red-100 dark:text-red-400 dark:bg-red-500/10', icon: ShieldAlert },
};

const tabs = [
    { id: 'overview', label: 'Overview', icon: Activity },
    { id: 'budget', label: 'Budget & Costs', icon: DollarSign },
    { id: 'changeOrders', label: 'Change Orders', icon: GitPullRequest },
    { id: 'rfis', label: 'RFIs', icon: FileText },
    { id: 'milestones', label: 'Milestones', icon: Milestone },
    { id: 'invoices', label: 'Invoices', icon: DollarSign },
    { id: 'risks', label: 'Risk & Issues', icon: AlertCircle },
    { id: 'activity', label: 'Activity', icon: Clock },
];

const OwnerProjectDetail = () => {
    const { projectId } = useParams();
    const { user } = useAuth();
    const { projects, vendors } = useMockStore();
    const navigate = useNavigate();
    const [activeTab, setActiveTab] = useState('overview');
    const [selectedCO, setSelectedCO] = useState(null);
    const [selectedInvoice, setSelectedInvoice] = useState(null);
    const [createModalConfig, setCreateModalConfig] = useState(null);

    const handleCreateSubmit = (data) => {
        console.log("Mock submitted data:", data);
        alert("Action successful! (Mock interface)");
    };

    const project = useMemo(() =>
        projects.find(p => p.id === projectId && p.ownerId === user?.id)
        , [projects, projectId, user]);

    if (!project) {
        return (
            <div className="min-h-full bg-zinc-50 dark:bg-[#09090b] flex items-center justify-center text-zinc-500">
                <div className="text-center">
                    <ShieldAlert size={48} className="mx-auto mb-4 text-zinc-400" />
                    <h2 className="text-xl font-bold text-zinc-900 dark:text-white">Project Not Found</h2>
                    <p className="mt-2">This project doesn't exist or you don't have access.</p>
                    <button onClick={() => navigate('/owner/projects')} className="mt-4 px-4 py-2 bg-amber-500 text-black font-bold rounded-xl text-sm">
                        Back to Projects
                    </button>
                </div>
            </div>
        );
    }

    const cfg = statusConfig[project.status] || statusConfig.active;
    const StatusIcon = cfg.icon;

    const contractor = vendors.find(v => v.id === project.contractorId) || null;

    const formatCurrency = (amt) =>
        new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(amt);

    const getHealthColor = (s) => s >= 70 ? 'text-emerald-500' : s >= 40 ? 'text-amber-500' : 'text-red-500';

    const getMilestoneColor = (status) => {
        if (status === 'completed') return 'bg-emerald-500';
        if (status === 'in_progress') return 'bg-blue-500';
        return 'bg-zinc-300 dark:bg-zinc-700';
    };

    const getInvoiceStatusColor = (status) => {
        if (status === 'paid') return 'text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-500/10';
        if (status === 'pending') return 'text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-500/10';
        return 'text-red-600 bg-red-100 dark:text-red-400 dark:bg-red-500/10';
    };

    const CustomTooltip = ({ active, payload, label }) => {
        if (active && payload?.length) {
            return (
                <div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-white/10 rounded-xl px-4 py-3 shadow-xl text-sm">
                    <p className="font-bold text-zinc-900 dark:text-white mb-1">{label}</p>
                    {payload.map((p, i) => (
                        <p key={i} className="text-zinc-600 dark:text-zinc-400">
                            <span className="font-semibold" style={{ color: p.color }}>{p.name}:</span> {formatCurrency(p.value * 1000)}
                        </p>
                    ))}
                </div>
            );
        }
        return null;
    };

    // Budget chart data
    const budgetChartData = (project.budgetBreakdown || []).map(b => ({
        name: b.category.length > 12 ? b.category.slice(0, 12) + '...' : b.category,
        allocated: b.allocated / 1000,
        committed: b.committed / 1000,
        actual: b.actual / 1000,
    }));

    return (
        <div className="min-h-full bg-zinc-50 dark:bg-[#09090b] text-zinc-900 dark:text-white transition-colors duration-300 relative">
            {/* Ambient Background */}
            <div className="fixed top-0 left-0 w-full h-full overflow-hidden pointer-events-none z-0">
                <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] bg-purple-500/5 dark:bg-purple-900/10 rounded-full blur-[120px]" />
                <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-blue-500/5 dark:bg-blue-900/10 rounded-full blur-[120px]" />
            </div>

            <div className="relative z-10 p-4 sm:p-8 max-w-7xl mx-auto space-y-6 pb-20">

                {/* Back & Title */}
                <header>
                    <button
                        onClick={() => navigate('/owner/projects')}
                        className="flex items-center gap-2 text-sm text-zinc-500 hover:text-zinc-900 dark:hover:text-white transition-colors mb-4"
                    >
                        <ArrowLeft size={16} /> Back to Projects
                    </button>

                    <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-zinc-200 dark:border-white/5 pb-6">
                        <div>
                            <h1 className="text-2xl sm:text-3xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-zinc-900 to-zinc-600 dark:from-white dark:to-white/60 tracking-tight">
                                {project.projectType}
                            </h1>
                            <p className="text-zinc-500 dark:text-zinc-400 mt-1 text-sm">{project.address}</p>
                        </div>
                        <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-bold uppercase tracking-wide ${cfg.color}`}>
                            <StatusIcon size={14} /> {cfg.label}
                        </span>
                    </div>
                </header>

                {/* Key Metrics Row */}
                <section className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-4">
                    {[
                        { label: 'Budget', value: formatCurrency(project.approvedBudget || project.budget) },
                        { label: 'Spent', value: formatCurrency(project.actualCost || project.spent) },
                        { label: 'Variance', value: `${(project.variancePercent || 0) > 0 ? '+' : ''}${(project.variancePercent || 0).toFixed(1)}%` },
                        { label: 'Completion', value: `${project.completionPercentage || 0}%` },
                        { label: 'Health', value: project.healthScore != null ? project.healthScore : '—', color: getHealthColor(project.healthScore || 0) },
                        { label: 'Phase', value: project.phase || '—' },
                    ].map((m, i) => (
                        <SpotlightCard key={i} className="p-4">
                            <div className={`text-xl font-extrabold ${m.color || 'text-zinc-900 dark:text-white'}`}>{m.value}</div>
                            <div className="text-[10px] uppercase font-bold tracking-wider text-zinc-500 mt-1">{m.label}</div>
                        </SpotlightCard>
                    ))}
                </section>

                {/* Tab Navigation */}
                <div className="flex overflow-x-auto gap-0.5 sm:gap-1 border-b border-zinc-200 dark:border-white/5 pb-px scrollbar-hide">
                    {tabs.map(tab => {
                        const TabIcon = tab.icon;
                        const isActive = activeTab === tab.id;
                        return (
                            <button
                                key={tab.id}
                                onClick={() => setActiveTab(tab.id)}
                                className={`flex items-center gap-1.5 sm:gap-2 px-2.5 sm:px-4 py-3 text-xs sm:text-sm font-semibold whitespace-nowrap border-b-2 transition-colors ${isActive
                                    ? 'border-amber-500 text-amber-600 dark:text-amber-400'
                                    : 'border-transparent text-zinc-500 hover:text-zinc-900 dark:hover:text-white'
                                    }`}
                            >
                                <TabIcon size={16} /> <span className="hidden sm:inline">{tab.label}</span>
                            </button>
                        );
                    })}
                </div>

                {/* Tab Content */}
                <div>
                    {/* OVERVIEW TAB - COMMAND CENTER */}
                    {activeTab === 'overview' && (
                        <div className="flex flex-col gap-6 w-full max-w-7xl mx-auto">

                            {/* Row 1: The Macro View */}
                            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                                {/* Project Progression */}
                                <NeoCard spotlightColor="rgba(0, 240, 255, 0.1)" className="lg:col-span-2">
                                    <div className="flex items-center gap-3 mb-6">
                                        <Milestone className={NEON_BLUE} size={20} />
                                        <h3 className="text-sm font-mono font-bold text-white tracking-widest uppercase">Project Progression</h3>
                                    </div>
                                    <div className="relative pt-8 pb-4">
                                        {/* Stepper Line */}
                                        <div className="absolute top-[38px] left-[10%] right-[10%] h-1 bg-zinc-800 rounded-full shadow-[inset_0_1px_3px_rgba(0,0,0,0.8)] z-0" />
                                        <motion.div
                                            initial={{ width: 0 }} animate={{ width: `${project.completionPercentage || 0}%` }} transition={{ duration: 1.5 }}
                                            className="absolute top-[38px] left-[10%] h-1 bg-gradient-to-r from-blue-600 to-[#00f0ff] rounded-full shadow-[0_0_10px_#00f0ff] z-0"
                                        />

                                        <div className="relative z-10 flex justify-between">
                                            {/* Stepper Nodes */}
                                            {["Lead", "Inspection Scheduled", "Damage Verified", "Scope Approved", "Project Completed"].map((step, i) => {
                                                const isActive = (i * 25) <= (project.completionPercentage || 0);
                                                return (
                                                    <div key={i} className="flex flex-col items-center gap-3 w-20 relative">
                                                        <div className={`w-8 h-8 rounded-full flex items-center justify-center border-2 shadow-lg transition-colors
                                                            ${isActive ? 'bg-zinc-900 border-[#00f0ff] text-[#00f0ff] shadow-[0_0_15px_rgba(0,240,255,0.4)]' : 'bg-black border-zinc-700 text-zinc-600'}
                                                        `}>
                                                            {isActive ? <CheckCircle size={14} className="drop-shadow-[0_0_5px_rgba(0,240,255,0.8)]" /> : <span className="w-2 h-2 rounded-full bg-zinc-700" />}
                                                        </div>
                                                        <span className={`text-[10px] text-center font-bold tracking-wide uppercase leading-tight ${isActive ? 'text-white' : 'text-zinc-500'}`}>
                                                            {step}
                                                        </span>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    </div>
                                    <div className="mt-8 flex items-center gap-4">
                                        <ProgressBar progress={project.completionPercentage || 0} colorClass="bg-gradient-to-r from-blue-600 to-[#00f0ff]" shadowClass="shadow-[0_0_10px_#00f0ff]" height="h-2" />
                                        <span className="text-xs font-mono font-bold text-[#00f0ff] uppercase">{project.completionPercentage || 0}% CMP</span>
                                    </div>
                                </NeoCard>

                                {/* Relationship Intelligence */}
                                <NeoCard spotlightColor="rgba(253, 169, 19, 0.1)">
                                    <div className="flex items-center gap-3 mb-6">
                                        <User className={NEON_GOLD} size={20} />
                                        <h3 className="text-sm font-mono font-bold text-white tracking-widest uppercase">Relationship Intel</h3>
                                    </div>
                                    <div className="flex items-center gap-4 mb-6">
                                        <div className="w-16 h-16 rounded-full bg-zinc-800 border-2 border-amber-500/30 flex items-center justify-center shadow-[inset_0_2px_10px_rgba(0,0,0,0.5)] flex-shrink-0">
                                            <span className="text-xl font-black text-amber-500">{project.customerName?.[0] || 'C'}</span>
                                        </div>
                                        <div>
                                            <h4 className="text-lg font-black text-white leading-tight">{project.customerName || 'Customer Records'}</h4>
                                            <p className="text-xs text-zinc-400 mt-1 font-mono">{contractor?.vendorName || project.contractorId}</p>
                                        </div>
                                    </div>
                                    <div className="flex gap-2 w-full mb-6">
                                        <button className="flex-1 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded-lg flex justify-center items-center gap-2 transition border border-white/5 hover:border-white/10 shadow-sm text-xs font-bold">
                                            <Phone size={14} /> Call
                                        </button>
                                        <button className="flex-1 py-2 bg-[#39ff14]/10 hover:bg-[#39ff14]/20 text-[#39ff14] border border-[#39ff14]/30 rounded-lg flex justify-center items-center gap-2 transition shadow-sm text-xs font-bold">
                                            <MessageSquare size={14} /> Text
                                        </button>
                                        <button className="w-10 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded-lg flex justify-center items-center transition border border-white/5 hover:border-white/10 shadow-sm flex-shrink-0">
                                            <Mail size={14} />
                                        </button>
                                    </div>
                                    <div className="bg-black/40 rounded-xl p-3 border border-white/5 shadow-[inset_0_2px_10px_rgba(0,0,0,0.5)]">
                                        <p className="text-[10px] font-mono text-amber-500 mb-1.5 flex items-center gap-1"><AlertTriangle size={10} /> PREFERENTIAL ROUTING</p>
                                        <p className="text-xs text-zinc-300 leading-tight border-b border-white/5 pb-2 mb-2">Responds fastest to SMS in the evenings. Critical approvals required via email.</p>
                                        <p className="text-[10px] text-zinc-500">Last Contact: 2 hours ago</p>
                                    </div>
                                </NeoCard>
                            </div>

                            {/* Row 2: The Assessment */}
                            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

                                {/* Performance Snapshot */}
                                <NeoCard spotlightColor="rgba(57, 255, 20, 0.1)" innerClassName="justify-between h-full">
                                    <div className="flex items-center gap-3 mb-6">
                                        <Crosshair className={NEON_GREEN} size={20} />
                                        <h3 className="text-sm font-mono font-bold text-white tracking-widest uppercase">Performance Snapshot</h3>
                                    </div>
                                    <div className="flex items-center justify-between mb-6">
                                        <div className="flex items-center gap-4">
                                            <div className="relative w-16 h-16 flex items-center justify-center shrink-0">
                                                <svg className="absolute inset-0 w-full h-full -rotate-90">
                                                    <circle cx="32" cy="32" r="28" fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="6" />
                                                    <circle cx="32" cy="32" r="28" fill="none" stroke="#39ff14" strokeWidth="6" strokeDasharray="175" strokeDashoffset={175 - (175 * 0.96)} strokeLinecap="round" className="drop-shadow-[0_0_5px_#39ff14]" />
                                                </svg>
                                                <span className="text-lg font-black text-white">96%</span>
                                            </div>
                                            <div>
                                                <h4 className="text-sm font-bold text-white">Inspection Coverage</h4>
                                                <p className="text-[10px] text-zinc-500 font-mono mt-0.5 uppercase tracking-wider">Damage Verification Complete</p>
                                            </div>
                                        </div>
                                    </div>
                                    {/* Embedded Map/Evidence Thumbnails */}
                                    <div className="grid grid-cols-3 gap-2 mt-auto">
                                        {['Hail_Damaged_Shingles.jpg', 'Cracked_Storm_Shingles.jpg', 'Broken_Roof_Surface.jpg', 'Curled_Aging_Shingles.jpg', 'Storm_Worn_Roof.jpg', 'Red_Shingle_Cottage.jpg'].map((img, i) => (
                                            <div key={i} className="aspect-square bg-zinc-800 rounded-md overflow-hidden border border-white/5 relative group">
                                                <img src={`/assets/images/properties/${img}`} alt="Evidence" className="w-full h-full object-cover opacity-60 group-hover:opacity-100 transition duration-300 grayscale group-hover:grayscale-0" />
                                                <div className="absolute inset-0 shadow-[inset_0_0_15px_rgba(0,0,0,0.8)] pointer-events-none" />
                                            </div>
                                        ))}
                                    </div>
                                </NeoCard>

                                {/* Evidence Summary */}
                                <NeoCard spotlightColor="rgba(253, 169, 19, 0.1)">
                                    <div className="flex items-center gap-3 mb-6 border-b border-white/5 pb-4">
                                        <Shield className={NEON_GOLD} size={20} />
                                        <h3 className="text-sm font-mono font-bold text-white tracking-widest uppercase">Evidence Summary</h3>
                                    </div>
                                    <div className="space-y-4 mb-6 flex-1">
                                        <div className="flex justify-between items-center text-sm">
                                            <span className="flex items-center gap-2 text-white font-medium"><div className="w-1.5 h-1.5 rounded-full bg-amber-500" /> Hail Impacts Detected</span>
                                            <span className="font-bold text-xl text-white">178</span>
                                        </div>
                                        <div className="flex justify-between items-center text-sm">
                                            <span className="flex items-center gap-2 text-zinc-300"><div className="w-1.5 h-1.5 rounded-full bg-orange-500" /> Gutters Denting</span>
                                            <span className="font-medium text-amber-500 uppercase text-xs tracking-wider">Moderate</span>
                                        </div>
                                        <div className="flex justify-between items-center text-sm">
                                            <span className="flex items-center gap-2 text-zinc-300"><div className="w-1.5 h-1.5 rounded-full bg-yellow-500" /> Window Screens</span>
                                            <span className="font-medium text-white">4 / 12</span>
                                        </div>
                                    </div>
                                    <div className="mt-auto pt-4 border-t border-white/5 flex items-center justify-between">
                                        <div className="flex items-center gap-2">
                                            <Zap size={14} className="text-[#39ff14]" />
                                            <span className="text-[10px] font-mono text-zinc-400 uppercase tracking-widest">AI Confidence:</span>
                                            <span className="text-sm font-bold text-[#39ff14]">92%</span>
                                        </div>
                                        <button className="text-[10px] uppercase font-bold tracking-widest bg-zinc-800 hover:bg-zinc-700 text-zinc-300 px-3 py-1.5 rounded-md border border-white/10 transition flex items-center gap-1.5">
                                            Evidence Map <ChevronRight size={12} />
                                        </button>
                                    </div>
                                </NeoCard>

                                {/* Financial Overview */}
                                <NeoCard spotlightColor="rgba(0, 240, 255, 0.1)">
                                    <div className="flex items-center gap-3 mb-6 border-b border-white/5 pb-4">
                                        <DollarSign className={NEON_BLUE} size={20} />
                                        <h3 className="text-sm font-mono font-bold text-white tracking-widest uppercase">Financial Overview</h3>
                                    </div>
                                    <div className="space-y-5">
                                        <div className="flex justify-between items-end">
                                            <span className="text-xs text-zinc-400 font-medium">Estimated Scope</span>
                                            <span className="text-xl font-bold text-white">{formatCurrency(project.approvedBudget || 34190)}</span>
                                        </div>
                                        <div className="flex justify-between items-end">
                                            <span className="text-xs text-zinc-400 font-medium">Supplements Potential</span>
                                            <span className="text-sm font-bold text-blue-400">+ {formatCurrency(4800)}</span>
                                        </div>
                                        <div className="flex justify-between items-end pb-4 border-b border-white/5">
                                            <span className="text-xs text-zinc-400 font-medium">Insurance Probability</span>
                                            <span className="text-sm font-bold text-[#39ff14]">82%</span>
                                        </div>
                                        <div className="flex justify-between items-end pt-2">
                                            <span className="text-sm font-bold text-zinc-300">Net Profit Projection</span>
                                            <span className={`text-2xl font-black ${NEON_GREEN}`}>{formatCurrency(project.budget - project.spent || 14200)}</span>
                                        </div>
                                    </div>
                                </NeoCard>
                            </div>

                            {/* Row 3: Action & Log */}
                            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                                {/* Action Needed & Timeline */}
                                <NeoCard spotlightColor="rgba(255, 69, 0, 0.1)" className="lg:col-span-2">
                                    <div className="flex items-center gap-3 mb-6">
                                        <AlertOctagon className={NEON_ORANGE} size={20} />
                                        <h3 className="text-sm font-mono font-bold text-white tracking-widest uppercase">Action Needed</h3>
                                    </div>
                                    <div className="space-y-3 mb-8">
                                        {/* Pulled from Project Risks / Mocks */}
                                        <div className="flex items-center gap-3 text-sm bg-red-500/10 border border-red-500/20 px-4 py-3 rounded-lg">
                                            <AlertTriangle size={14} className="text-red-500 shrink-0" />
                                            <span className="text-red-200">Missing downspout photos for final supplement push.</span>
                                        </div>
                                        <div className="flex items-center gap-3 text-sm bg-amber-500/10 border border-amber-500/20 px-4 py-3 rounded-lg">
                                            <AlertCircle size={14} className="text-amber-500 shrink-0" />
                                            <span className="text-amber-200">Adjuster meeting not scheduled within SLA.</span>
                                        </div>
                                    </div>

                                    <div className="border-t border-white/5 pt-6 mt-auto">
                                        <h4 className="text-[10px] uppercase font-mono font-bold text-zinc-500 tracking-widest mb-4">Project Timeline Highlights</h4>
                                        <div className="space-y-4">
                                            <div className="flex items-center justify-between text-xs">
                                                <div className="flex items-center gap-3 text-zinc-300"><CheckCircle size={14} className="text-[#39ff14]" /> Inspection Completed</div>
                                                <div className="flex items-center gap-3 font-mono">
                                                    <span className="text-zinc-500">Feb 20</span>
                                                    <span className="bg-zinc-800 text-zinc-400 px-2 py-0.5 rounded border border-white/5">Pending QC</span>
                                                </div>
                                            </div>
                                            <div className="flex items-center justify-between text-xs">
                                                <div className="flex items-center gap-3 text-zinc-300"><Clock size={14} className="text-orange-500" /> Claim Filed</div>
                                                <div className="flex items-center gap-3 font-mono">
                                                    <span className="text-zinc-600">Not Scheduled</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </NeoCard>

                                {/* Quick Actions Palette */}
                                <NeoCard spotlightColor="rgba(0, 240, 255, 0.1)" innerClassName="justify-between h-full relative">
                                    <div className="flex items-center gap-3 mb-6">
                                        <Activity className={NEON_BLUE} size={20} />
                                        <h3 className="text-sm font-mono font-bold text-white tracking-widest uppercase">Quick Actions</h3>
                                    </div>
                                    <div className="space-y-2.5 flex-1 z-10">
                                        <button className="w-full flex items-center gap-3 px-4 py-3 bg-zinc-800 hover:bg-zinc-700 hover:border-blue-500/50 text-white rounded-xl border border-white/5 transition-all group text-sm font-medium">
                                            <Camera size={16} className="text-zinc-500 group-hover:text-blue-400 transition-colors" /> Capture Missing Photos
                                        </button>
                                        <button className="w-full flex items-center gap-3 px-4 py-3 bg-zinc-800 hover:bg-zinc-700 hover:border-amber-500/50 text-white rounded-xl border border-white/5 transition-all group text-sm font-medium">
                                            <Map size={16} className="text-zinc-500 group-hover:text-amber-400 transition-colors" /> Generate Estimate Link
                                        </button>
                                        <button className="w-full flex items-center gap-3 px-4 py-3 bg-zinc-800 hover:bg-zinc-700 hover:border-purple-500/50 text-white rounded-xl border border-white/5 transition-all group text-sm font-medium">
                                            <FileText size={16} className="text-zinc-500 group-hover:text-purple-400 transition-colors" /> Send Homeowner Report
                                        </button>
                                    </div>
                                    <button className="absolute bottom-6 right-6 w-12 h-12 bg-blue-600 hover:bg-blue-500 rounded-full flex items-center justify-center text-white shadow-[0_0_20px_rgba(37,99,235,0.6)] cursor-pointer hover:scale-105 transition-transform z-20 border border-blue-400/50">
                                        <Plus size={24} />
                                    </button>
                                </NeoCard>
                            </div>
                        </div>
                    )}

                    {/* BUDGET TAB */}
                    {activeTab === 'budget' && (
                        <div className="space-y-6 max-w-7xl mx-auto">
                            {budgetChartData.length > 0 ? (
                                <>
                                    <NeoCard spotlightColor="rgba(0, 240, 255, 0.1)">
                                        <div className="flex items-center justify-between mb-1">
                                            <div className="flex items-center gap-3">
                                                <DollarSign className={NEON_BLUE} size={20} />
                                                <h3 className="text-lg font-bold text-white tracking-widest uppercase">Budget Breakdown</h3>
                                            </div>
                                            <button
                                                onClick={() => setCreateModalConfig({
                                                    title: 'Add Budget Cost', icon: DollarSign, iconColor: 'text-[#39ff14]', iconBg: 'bg-[#39ff14]/10',
                                                    submitLabel: 'Save Cost', submitColor: 'bg-[#39ff14]/20 text-[#39ff14] border-[#39ff14]/30',
                                                    fields: [
                                                        { name: 'category', label: 'Category', type: 'text', required: true },
                                                        { name: 'allocated', label: 'Allocated Amount', type: 'number', required: true },
                                                        { name: 'spent', label: 'Actual Spent', type: 'number' }
                                                    ],
                                                    onSubmit: handleCreateSubmit
                                                })}
                                                className="bg-blue-500/10 hover:bg-blue-500/20 text-[#00f0ff] border border-blue-500/30 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2"
                                            >
                                                <Plus size={14} /> Add Cost
                                            </button>
                                        </div>
                                        <p className="text-xs text-zinc-400 mb-6 font-mono">Allocated vs Committed vs Actual ($k)</p>
                                        <div className="h-64 bg-black/20 rounded-xl p-4 border border-white/5 shadow-inner">
                                            <ResponsiveContainer width="99%" height={256} minWidth={1} minHeight={1}>
                                                <BarChart data={budgetChartData} barGap={2}>
                                                    <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
                                                    <YAxis tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
                                                    <Tooltip content={<CustomTooltip />} />
                                                    <Bar dataKey="allocated" name="Allocated" fill="#3b82f6" radius={[4, 4, 0, 0]} />
                                                    <Bar dataKey="committed" name="Committed" fill="#f59e0b" radius={[4, 4, 0, 0]} />
                                                    <Bar dataKey="actual" name="Actual" fill="#22c55e" radius={[4, 4, 0, 0]} />
                                                </BarChart>
                                            </ResponsiveContainer>
                                        </div>
                                    </NeoCard>
                                    <NeoCard spotlightColor="rgba(253, 169, 19, 0.1)" innerClassName="p-0 lg:p-0">
                                        <div className="overflow-x-auto w-full rounded-2xl">
                                            <table className="w-full text-left border-collapse min-w-[600px]">
                                                <thead className="bg-[#18181b]/80 border-b border-white/10">
                                                    <tr>
                                                        {['Category', 'Allocated', 'Committed', 'Actual', 'Variance'].map(h => (
                                                            <th key={h} className={`px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-400 ${h !== 'Category' ? 'text-right' : ''}`}>{h}</th>
                                                        ))}
                                                    </tr>
                                                </thead>
                                                <tbody className="divide-y divide-white/5">
                                                    {(project.budgetBreakdown || []).map((b, i) => {
                                                        const variance = b.actual - b.allocated;
                                                        return (
                                                            <tr key={i} className="hover:bg-white/5 transition-colors">
                                                                <td className="px-5 py-4 font-bold text-sm text-white">{b.category}</td>
                                                                <td className="px-5 py-4 text-right font-mono text-sm text-zinc-300">{formatCurrency(b.allocated)}</td>
                                                                <td className="px-5 py-4 text-right font-mono text-sm text-amber-500">{formatCurrency(b.committed)}</td>
                                                                <td className="px-5 py-4 text-right font-mono text-sm text-[#00f0ff]">{formatCurrency(b.actual)}</td>
                                                                <td className={`px-5 py-4 text-right font-mono text-sm font-bold ${variance > 0 ? 'text-[#ff4500]' : 'text-[#39ff14]'}`}>
                                                                    {variance > 0 ? '+' : ''}{formatCurrency(variance)}
                                                                </td>
                                                            </tr>
                                                        );
                                                    })}
                                                </tbody>
                                            </table>
                                        </div>
                                    </NeoCard>
                                </>
                            ) : (
                                <NeoCard className="p-12 text-center text-zinc-500">
                                    <DollarSign size={48} className="mx-auto mb-4 text-zinc-600" />
                                    <p className="font-bold text-lg text-white">No detailed budget breakdown available.</p>
                                    <p className="text-sm mt-2 text-zinc-400 font-mono">Budget: {formatCurrency(project.approvedBudget || project.budget)} &nbsp;&middot;&nbsp; Spent: {formatCurrency(project.actualCost || project.spent)}</p>
                                </NeoCard>
                            )}
                        </div>
                    )}

                    {/* CHANGE ORDERS TAB */}
                    {activeTab === 'changeOrders' && (
                        <NeoCard spotlightColor="rgba(253, 169, 19, 0.1)" innerClassName="p-0 lg:p-0">
                            <div className="p-5 border-b border-white/5 flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <GitPullRequest className={NEON_GOLD} size={20} />
                                    <h3 className="text-lg font-bold text-white tracking-widest uppercase">Change Orders</h3>
                                </div>
                                <button
                                    onClick={() => setCreateModalConfig({
                                        title: 'New Change Order', icon: GitPullRequest, iconColor: 'text-[#fda913]', iconBg: 'bg-amber-500/10',
                                        submitLabel: 'Submit Change Order', submitColor: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
                                        fields: [
                                            { name: 'title', label: 'Title', type: 'text', required: true },
                                            { name: 'amount', label: 'Requested Amount ($)', type: 'number', required: true },
                                            { name: 'description', label: 'Description/Justification', type: 'textarea', required: true }
                                        ],
                                        onSubmit: handleCreateSubmit
                                    })}
                                    className="bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 border border-amber-500/30 px-4 py-2 rounded-lg text-xs font-bold transition flex items-center gap-2"
                                >
                                    <Plus size={14} /> New Change Order
                                </button>
                            </div>
                            <div className="overflow-x-auto w-full">
                                {(project.changeOrders || []).length > 0 ? (
                                    <table className="w-full text-left border-collapse min-w-[700px]">
                                        <thead className="bg-[#18181b]/80 border-b border-white/10">
                                            <tr>
                                                {['ID', 'Title', 'Amount', 'Status', 'Date'].map(h => (
                                                    <th key={h} className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-400">{h}</th>
                                                ))}
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-white/5">
                                            {project.changeOrders.map((co, i) => (
                                                <tr key={i} className="hover:bg-white/5 transition-colors cursor-pointer" tabIndex="0" onClick={() => setSelectedCO(co)} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedCO(co); } }}>
                                                    <td className="px-5 py-4 font-mono text-xs text-zinc-500">{co.id}</td>
                                                    <td className="px-5 py-4">
                                                        <div className="font-bold text-sm text-white">{co.title}</div>
                                                        {co.description && <div className="text-xs text-zinc-400 mt-1">{co.description}</div>}
                                                    </td>
                                                    <td className="px-5 py-4 font-mono text-sm text-[#00f0ff]">{formatCurrency(co.amount)}</td>
                                                    <td className="px-5 py-4">
                                                        <span className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest ${co.status === 'approved' ? 'text-[#39ff14] bg-[#39ff14]/10 border border-[#39ff14]/20' :
                                                            co.status === 'pending' ? 'text-amber-400 bg-amber-500/10 border border-amber-500/20' :
                                                                'text-[#ff4500] bg-[#ff4500]/10 border border-[#ff4500]/20'
                                                            }`}>
                                                            {co.status}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-4 text-sm text-zinc-400 font-mono">{co.dateSubmitted}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                ) : (
                                    <div className="p-16 text-center text-zinc-500">
                                        <GitPullRequest size={48} className="mx-auto mb-4 text-zinc-600" />
                                        <p className="font-bold text-lg text-white">No change orders found.</p>
                                    </div>
                                )}
                            </div>
                        </NeoCard>
                    )}

                    {/* RFIs TAB */}
                    {activeTab === 'rfis' && (
                        <NeoCard spotlightColor="rgba(0, 240, 255, 0.1)" innerClassName="p-0 lg:p-0">
                            <div className="p-5 border-b border-white/5 flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <FileText className={NEON_BLUE} size={20} />
                                    <h3 className="text-lg font-bold text-white tracking-widest uppercase">Requests for Information (RFI)</h3>
                                </div>
                                <button
                                    onClick={() => setCreateModalConfig({
                                        title: 'Create RFI', icon: FileText, iconColor: 'text-[#00f0ff]', iconBg: 'bg-blue-500/10',
                                        submitLabel: 'Submit RFI', submitColor: 'bg-blue-500/20 text-[#00f0ff] border-blue-500/30',
                                        fields: [
                                            { name: 'subject', label: 'Subject', type: 'text', required: true },
                                            { name: 'priority', label: 'Priority', type: 'select', options: [{ label: 'Normal', value: 'normal' }, { label: 'High', value: 'high' }], required: true },
                                            { name: 'question', label: 'Question', type: 'textarea', required: true },
                                            { name: 'attachment', label: 'Attachment', type: 'file' }
                                        ],
                                        onSubmit: handleCreateSubmit
                                    })}
                                    className="bg-blue-500/10 hover:bg-blue-500/20 text-[#00f0ff] border border-blue-500/30 px-4 py-2 rounded-lg text-xs font-bold transition flex items-center gap-2"
                                >
                                    <Plus size={14} /> Create RFI
                                </button>
                            </div>
                            <div className="overflow-x-auto w-full">
                                {(project.rfis || []).length > 0 ? (
                                    <table className="w-full text-left border-collapse min-w-[800px]">
                                        <thead className="bg-[#18181b]/80 border-b border-white/10">
                                            <tr>
                                                {['ID', 'Subject', 'Status', 'Submitted By', 'Opened', 'Closed'].map(h => (
                                                    <th key={h} className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-400">{h}</th>
                                                ))}
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-white/5">
                                            {project.rfis.map((rfi, i) => (
                                                <tr key={i} className="hover:bg-white/5 transition-colors">
                                                    <td className="px-5 py-4 font-mono text-xs text-zinc-500">{rfi.id}</td>
                                                    <td className="px-5 py-4 font-bold text-sm text-white">{rfi.subject}</td>
                                                    <td className="px-5 py-4">
                                                        <span className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest ${rfi.status === 'closed' ? 'text-[#39ff14] bg-[#39ff14]/10 border border-[#39ff14]/20' :
                                                            'text-amber-400 bg-amber-500/10 border border-amber-500/20'
                                                            }`}>
                                                            {rfi.status}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-4 text-sm text-zinc-400">{rfi.submittedBy}</td>
                                                    <td className="px-5 py-4 text-sm text-zinc-500 font-mono">{rfi.dateOpened}</td>
                                                    <td className="px-5 py-4 text-sm text-zinc-500 font-mono">{rfi.dateClosed || '—'}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                ) : (
                                    <div className="p-16 text-center text-zinc-500">
                                        <FileText size={48} className="mx-auto mb-4 text-zinc-600" />
                                        <p className="font-bold text-lg text-white">No RFIs for this project.</p>
                                    </div>
                                )}
                            </div>
                        </NeoCard>
                    )}

                    {/* MILESTONES TAB */}
                    {activeTab === 'milestones' && (
                        <NeoCard spotlightColor="rgba(255, 255, 255, 0.1)">
                            <div className="flex items-center gap-3 mb-8">
                                <MapPin className="text-white" size={20} />
                                <h3 className="text-lg font-bold text-white tracking-widest uppercase">Milestone Timeline</h3>
                            </div>
                            <div className="relative">
                                {/* Timeline line */}
                                <div className="absolute left-6 top-0 bottom-0 w-px bg-white/10" />
                                <div className="space-y-6">
                                    {(project.milestones || []).map((ms, i) => (
                                        <div key={i} className="relative flex items-start gap-4 pl-12">
                                            <div className={`absolute left-[21px] top-1.5 w-2.5 h-2.5 rounded-full bg-[#09090b] border-2 shadow-[0_0_8px_rgba(255,255,255,0.4)] ${ms.status === 'completed' ? 'border-[#39ff14]' : ms.status === 'in_progress' ? 'border-[#00f0ff]' : 'border-zinc-500'}`} />
                                            <div className="flex-1 p-4 rounded-xl bg-white/5 border border-white/5 hover:bg-white/10 transition-colors">
                                                <div className="flex justify-between items-start">
                                                    <div>
                                                        <div className="font-bold text-white">{ms.name}</div>
                                                        <div className="text-xs text-zinc-400 mt-1">Due: <span className="text-zinc-300 font-mono">{ms.dueDate}</span> &middot; Assigned to: <span className="text-[#00f0ff] uppercase tracking-wider">{ms.assignedTo}</span></div>
                                                    </div>
                                                    <span className={`text-[10px] font-bold uppercase tracking-wider px-3 py-1 rounded-full ${ms.status === 'completed' ? 'text-[#39ff14] bg-[#39ff14]/10 border border-[#39ff14]/20' :
                                                        ms.status === 'in_progress' ? 'text-[#00f0ff] bg-blue-500/10 border border-blue-500/20' :
                                                            'text-zinc-500 bg-white/5 border border-white/10'
                                                        }`}>
                                                        {ms.status.replace('_', ' ')}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </NeoCard>
                    )}

                    {/* INVOICES TAB */}
                    {activeTab === 'invoices' && (
                        <NeoCard spotlightColor="rgba(0, 240, 255, 0.1)" innerClassName="p-0 lg:p-0">
                            <div className="p-5 border-b border-white/5 flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <DollarSign className={NEON_BLUE} size={20} />
                                    <h3 className="text-lg font-bold text-white tracking-widest uppercase">Invoices</h3>
                                </div>
                                <button
                                    onClick={() => setCreateModalConfig({
                                        title: 'Add Invoice', icon: DollarSign, iconColor: 'text-[#00f0ff]', iconBg: 'bg-blue-500/10',
                                        submitLabel: 'Submit Invoice', submitColor: 'bg-blue-500/20 text-[#00f0ff] border-blue-500/30',
                                        fields: [
                                            { name: 'amount', label: 'Amount ($)', type: 'number', required: true },
                                            { name: 'dueDate', label: 'Due Date', type: 'date', required: true },
                                            { name: 'attachment', label: 'Invoice Document', type: 'file' }
                                        ],
                                        onSubmit: handleCreateSubmit
                                    })}
                                    className="bg-blue-500/10 hover:bg-blue-500/20 text-[#00f0ff] border border-blue-500/30 px-4 py-2 rounded-lg text-xs font-bold transition flex items-center gap-2"
                                >
                                    <Plus size={14} /> Add Invoice
                                </button>
                            </div>
                            <div className="overflow-x-auto w-full">
                                {(project.invoices || []).length > 0 ? (
                                    <table className="w-full text-left border-collapse min-w-[700px]">
                                        <thead className="bg-[#18181b]/80 border-b border-white/10">
                                            <tr>
                                                {['Invoice ID', 'Amount', 'Submitted By', 'Status', 'Due Date', 'Paid Date'].map(h => (
                                                    <th key={h} className={`px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-400 ${h === 'Amount' ? 'text-right' : ''}`}>{h}</th>
                                                ))}
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-white/5">
                                            {project.invoices.map((inv, i) => (
                                                <tr key={i} className="hover:bg-white/5 transition-colors cursor-pointer" tabIndex="0" onClick={() => setSelectedInvoice(inv)} onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedInvoice(inv); } }}>
                                                    <td className="px-5 py-4 font-mono text-xs text-zinc-500">{inv.id}</td>
                                                    <td className="px-5 py-4 text-right font-mono text-sm font-bold text-[#00f0ff]">
                                                        {formatCurrency(inv.amount)}
                                                    </td>
                                                    <td className="px-5 py-4 text-sm text-zinc-400 uppercase tracking-wider">{inv.submittedBy}</td>
                                                    <td className="px-5 py-4">
                                                        <span className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest ${inv.status === 'paid' ? 'text-[#39ff14] bg-[#39ff14]/10 border border-[#39ff14]/20' :
                                                            inv.status === 'pending' ? 'text-amber-400 bg-amber-500/10 border border-amber-500/20' :
                                                                inv.status === 'overdue' ? 'text-[#ff4500] bg-[#ff4500]/10 border border-[#ff4500]/20' :
                                                                    'text-zinc-400 bg-white/5 border border-white/10'
                                                            }`}>
                                                            {inv.status}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-4 text-sm text-zinc-500 font-mono">{inv.dueDate}</td>
                                                    <td className="px-5 py-4 text-sm text-zinc-500 font-mono">{inv.datePaid || '—'}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                ) : (
                                    <div className="p-16 text-center text-zinc-500">
                                        <DollarSign size={48} className="mx-auto mb-4 text-zinc-600" />
                                        <p className="font-bold text-lg text-white">No invoices for this project.</p>
                                    </div>
                                )}
                            </div>
                        </NeoCard>
                    )}

                    {/* RISK & ISSUES TAB */}
                    {activeTab === 'risks' && (
                        <div className="space-y-6">
                            {/* Risk Log */}
                            <NeoCard spotlightColor="rgba(253, 169, 19, 0.1)" innerClassName="p-0 lg:p-0">
                                <div className="p-5 border-b border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <Shield className={NEON_GOLD} size={20} />
                                        <h3 className="text-lg font-bold text-white tracking-widest uppercase">Risk Log</h3>
                                    </div>
                                    <button
                                        onClick={() => setCreateModalConfig({
                                            title: 'Log New Risk', icon: Shield, iconColor: 'text-[#fda913]', iconBg: 'bg-amber-500/10',
                                            submitLabel: 'Log Risk', submitColor: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
                                            fields: [
                                                { name: 'description', label: 'Risk Description', type: 'textarea', required: true },
                                                { name: 'severity', label: 'Severity', type: 'select', options: [{ label: 'Low', value: 'Low' }, { label: 'Medium', value: 'Medium' }, { label: 'High', value: 'High' }], required: true },
                                                { name: 'likelihood', label: 'Likelihood', type: 'select', options: [{ label: 'Unlikely', value: 'Unlikely' }, { label: 'Possible', value: 'Possible' }, { label: 'Likely', value: 'Likely' }], required: true },
                                                { name: 'mitigation', label: 'Mitigation Plan', type: 'textarea' }
                                            ],
                                            onSubmit: handleCreateSubmit
                                        })}
                                        className="bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 border border-amber-500/30 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2"
                                    >
                                        <Plus size={14} /> Log Risk
                                    </button>
                                </div>
                                <div className="overflow-x-auto w-full">
                                    {(project.riskLog || []).length > 0 ? (
                                        <table className="w-full text-left border-collapse min-w-[800px]">
                                            <thead className="bg-[#18181b]/80 border-b border-white/10">
                                                <tr>
                                                    {['ID', 'Description', 'Severity', 'Likelihood', 'Status', 'Mitigation'].map(h => (
                                                        <th key={h} className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-400">{h}</th>
                                                    ))}
                                                </tr>
                                            </thead>
                                            <tbody className="divide-y divide-white/5">
                                                {project.riskLog.map((r, i) => (
                                                    <tr key={i} className="hover:bg-white/5 transition-colors">
                                                        <td className="px-5 py-4 font-mono text-xs text-zinc-500">{r.id}</td>
                                                        <td className="px-5 py-4 text-sm font-medium text-white max-w-xs">{r.description}</td>
                                                        <td className="px-5 py-4">
                                                            <span className={`text-[10px] font-bold uppercase px-3 py-1 rounded-full ${r.severity === 'High' ? 'text-[#ff4500] bg-[#ff4500]/10 border border-[#ff4500]/20' :
                                                                r.severity === 'Medium' ? 'text-amber-400 bg-amber-500/10 border border-amber-500/20' :
                                                                    'text-[#00f0ff] bg-blue-500/10 border border-blue-500/20'
                                                                }`}>
                                                                {r.severity}
                                                            </span>
                                                        </td>
                                                        <td className="px-5 py-4 text-sm text-zinc-400 capitalize">{r.likelihood}</td>
                                                        <td className="px-5 py-4 text-sm text-zinc-400 capitalize">{r.status}</td>
                                                        <td className="px-5 py-4 text-xs text-zinc-500 max-w-xs">{r.mitigation}</td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    ) : (
                                        <div className="p-16 text-center text-zinc-500">
                                            <Shield size={48} className="mx-auto mb-4 text-zinc-600" />
                                            <p className="font-bold text-lg text-white">No risk entries for this project.</p>
                                        </div>
                                    )}
                                </div>
                            </NeoCard>

                            {/* Issue Log */}
                            <NeoCard spotlightColor="rgba(255, 69, 0, 0.1)" innerClassName="p-0 lg:p-0">
                                <div className="p-5 border-b border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <AlertCircle className={NEON_RED} size={20} />
                                        <h3 className="text-lg font-bold text-white tracking-widest uppercase">Issue Log</h3>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <button
                                            onClick={() => setCreateModalConfig({
                                                title: 'Add Photo to Issue', icon: Camera, iconColor: 'text-zinc-300', iconBg: 'bg-zinc-800',
                                                submitLabel: 'Upload Photo', submitColor: 'bg-zinc-800 text-white border-white/20',
                                                fields: [
                                                    { name: 'issueId', label: 'Target Issue ID', type: 'text', placeholder: 'e.g. issue_001', required: true },
                                                    { name: 'photo', label: 'Photo Upload', type: 'file', accept: 'image/*', required: true },
                                                    { name: 'notes', label: 'Notes', type: 'textarea' }
                                                ],
                                                onSubmit: handleCreateSubmit
                                            })}
                                            className="bg-zinc-800/50 hover:bg-zinc-800 text-zinc-300 border border-white/10 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2"
                                        >
                                            <Camera size={14} /> Add Photo
                                        </button>
                                        <button
                                            onClick={() => setCreateModalConfig({
                                                title: 'Report Issue', icon: AlertCircle, iconColor: 'text-[#ff4500]', iconBg: 'bg-[#ff4500]/10',
                                                submitLabel: 'Submit Issue', submitColor: 'bg-[#ff4500]/20 text-[#ff4500] border-[#ff4500]/30',
                                                fields: [
                                                    { name: 'title', label: 'Issue Title', type: 'text', required: true },
                                                    { name: 'priority', label: 'Priority', type: 'select', options: [{ label: 'Medium', value: 'Medium' }, { label: 'High', value: 'High' }, { label: 'Critical', value: 'Critical' }], required: true },
                                                    { name: 'description', label: 'Detailed Description', type: 'textarea', required: true },
                                                    { name: 'photo', label: 'Attach Photo', type: 'file', accept: 'image/*' }
                                                ],
                                                onSubmit: handleCreateSubmit
                                            })}
                                            className="bg-[#ff4500]/10 hover:bg-[#ff4500]/20 text-[#ff4500] border border-[#ff4500]/30 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2"
                                        >
                                            <Plus size={14} /> Report Issue
                                        </button>
                                    </div>
                                </div>
                                <div className="overflow-x-auto w-full">
                                    {(project.issueLog || []).length > 0 ? (
                                        <table className="w-full text-left border-collapse min-w-[800px]">
                                            <thead className="bg-[#18181b]/80 border-b border-white/10">
                                                <tr>
                                                    {['ID', 'Title', 'Priority', 'Status', 'Assigned To', 'Reported'].map(h => (
                                                        <th key={h} className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-400">{h}</th>
                                                    ))}
                                                </tr>
                                            </thead>
                                            <tbody className="divide-y divide-white/5">
                                                {project.issueLog.map((issue, i) => (
                                                    <tr key={i} className="hover:bg-white/5 transition-colors">
                                                        <td className="px-5 py-4 font-mono text-xs text-zinc-500">{issue.id}</td>
                                                        <td className="px-5 py-4 font-bold text-sm text-white">{issue.title}</td>
                                                        <td className="px-5 py-4">
                                                            <span className={`text-[10px] font-bold uppercase px-3 py-1 rounded-full ${issue.priority === 'High' || issue.priority === 'critical' ? 'text-[#ff4500] bg-[#ff4500]/10 border border-[#ff4500]/20' :
                                                                issue.priority === 'Medium' || issue.priority === 'high' ? 'text-amber-400 bg-amber-500/10 border border-amber-500/20' :
                                                                    'text-[#00f0ff] bg-blue-500/10 border border-blue-500/20'
                                                                }`}>
                                                                {issue.priority}
                                                            </span>
                                                        </td>
                                                        <td className="px-5 py-4 text-sm text-zinc-400 capitalize">{issue.status}</td>
                                                        <td className="px-5 py-4 text-sm text-zinc-400">{issue.assignedTo}</td>
                                                        <td className="px-5 py-4 text-sm text-zinc-500 font-mono">{issue.dateReported}</td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    ) : (
                                        <div className="p-16 text-center text-zinc-500">
                                            <AlertCircle size={48} className="mx-auto mb-4 text-zinc-600" />
                                            <p className="font-bold text-lg text-white">No issues logged for this project.</p>
                                        </div>
                                    )}
                                </div>
                            </NeoCard>
                        </div>
                    )}

                    {/* ACTIVITY TAB */}
                    {activeTab === 'activity' && (
                        <NeoCard spotlightColor="rgba(57, 255, 20, 0.1)">
                            <div className="flex items-center gap-3 mb-8">
                                <Clock className={NEON_GREEN} size={20} />
                                <h3 className="text-lg font-bold text-white tracking-widest uppercase">Activity Timeline</h3>
                            </div>
                            {(project.activityTimeline || []).length > 0 ? (
                                <div className="relative">
                                    <div className="absolute left-6 top-0 bottom-0 w-px bg-white/10" />
                                    <div className="space-y-6">
                                        {project.activityTimeline.map((a, i) => (
                                            <div key={i} className="relative flex items-start gap-4 pl-12">
                                                <div className={`absolute left-[21px] top-1.5 w-2.5 h-2.5 rounded-full bg-[#09090b] border-2 shadow-[0_0_8px_rgba(57,255,20,0.4)] ${a.action.includes('Payment') ? 'border-amber-400' : a.action.includes('Issue') ? 'border-[#ff4500]' : 'border-[#39ff14]'}`} />
                                                <div className="flex-1 p-4 rounded-xl bg-white/5 border border-white/5 hover:bg-white/10 transition-colors">
                                                    <div className="flex justify-between items-start">
                                                        <div>
                                                            <div className="font-bold text-white text-sm">{a.action}</div>
                                                            {a.details && <div className="text-xs text-zinc-400 mt-1">{a.details}</div>}
                                                        </div>
                                                        <div className="text-right shrink-0 ml-4">
                                                            <div className="text-xs font-mono text-zinc-500">{a.date}</div>
                                                            {a.user && <div className="text-[10px] uppercase tracking-wider text-[#00f0ff] mt-1">{a.user}</div>}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            ) : (
                                <div className="text-center text-zinc-500 py-16">
                                    <Clock size={48} className="mx-auto mb-4 text-zinc-600" />
                                    <p className="font-bold text-lg text-white">No activity logged yet.</p>
                                </div>
                            )}
                        </NeoCard>
                    )}
                </div>
            </div>

            {/* Modals & Drawers */}
            <ChangeOrderDrawer
                isOpen={!!selectedCO}
                onClose={() => setSelectedCO(null)}
                changeOrder={selectedCO}
            />
            <InvoiceDetailModal
                isOpen={!!selectedInvoice}
                onClose={() => setSelectedInvoice(null)}
                invoice={selectedInvoice}
            />
            {createModalConfig && (
                <CreateItemModal
                    isOpen={!!createModalConfig}
                    onClose={() => setCreateModalConfig(null)}
                    {...createModalConfig}
                />
            )}
            <span className="attribution-ghost">igotsar.matyas | LynkedUpPro - Turns out roofing CRMs don't build themselves. Who knew?</span>
        </div>
    );
};

export default OwnerProjectDetail;
