'use client';

import { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft, CheckCircle, AlertTriangle, Clock, Eye, FileText,
  Loader2, RotateCcw, ChevronRight, Zap, GitBranch, Package,
  BarChart3, Code, Layers, Database, FileCode, BookOpen, TestTube,
  Settings, Trash2, Copy, Download
} from 'lucide-react';
import MermaidDiagram from '@/components/dark-factory/mermaid-diagram';

interface Visual {
  id: string;
  type: string;
  title: string;
  description: string | null;
  content: string;
  status: string;
  feedback: string | null;
}

interface Deliverable {
  id: string;
  name: string;
  type: string;
  description: string | null;
  acceptanceCriteria: string | null;
  status: string;
}

interface Entity {
  id: string;
  name: string;
  description: string | null;
  fields: { name: string; type: string }[];
  relationships: { target: string; type: string }[];
  isCore: boolean;
}

interface Criterion {
  id: string;
  description: string;
  category: string;
  priority: string;
}

interface Artifact {
  id: string;
  type: string;
  path: string;
  version: number;
}

interface RevisionEntry {
  id: string;
  gate: string;
  action: string;
  changedBy: string;
  reason: string | null;
  createdAt: string;
}

interface Intake {
  id: string;
  title: string;
  clientName: string | null;
  clientCompany: string | null;
  businessDomain: string;
  problemStatement: string;
  targetUsers: string[];
  coreWorkflows: string[];
  constraints: string[];
  integrations: string[];
  targetLanguage: string;
  targetDatabase: string;
  budget: string | null;
  timeline: string | null;
  notes: string | null;
  gate: string;
  complexityScore: number | null;
  estimatedHours: number | null;
  estimatedCost: number | null;
  entityCount: number | null;
  intakeApprovedAt: string | null;
  intakeApprovedBy: string | null;
  visualsApprovedAt: string | null;
  visualsApprovedBy: string | null;
  deliverablesApprovedAt: string | null;
  deliverablesApprovedBy: string | null;
  createdAt: string;
  generationRequestId: string | null;
  entities: Entity[];
  visuals: Visual[];
  deliverables: Deliverable[];
  acceptanceCriteria: Criterion[];
  revisionLog: RevisionEntry[];
}

const GATE_CONFIG: Record<string, { label: string; color: string; step: number }> = {
  intake_draft: { label: 'Intake Draft', color: 'text-gray-400', step: 0 },
  intake_revision: { label: 'Intake Revision', color: 'text-amber-400', step: 0 },
  intake_approved: { label: 'Intake Approved', color: 'text-green-400', step: 1 },
  visuals_generated: { label: 'Visuals Ready for Review', color: 'text-blue-400', step: 2 },
  visuals_revision: { label: 'Visual Revision Needed', color: 'text-amber-400', step: 2 },
  visuals_approved: { label: 'Visuals Approved', color: 'text-green-400', step: 3 },
  deliverables_defined: { label: 'Deliverables Defined', color: 'text-sky-400', step: 4 },
  deliverables_revision: { label: 'Deliverable Revision', color: 'text-amber-400', step: 4 },
  deliverables_approved: { label: 'Ready for Code Generation', color: 'text-green-400', step: 5 },
  code_generating: { label: 'Generating Code...', color: 'text-orange-400', step: 6 },
  complete: { label: 'Complete', color: 'text-emerald-400', step: 7 },
};

const PIPELINE_STEPS = [
  { label: 'Intake', icon: FileText },
  { label: 'Approved', icon: CheckCircle },
  { label: 'Visuals', icon: Eye },
  { label: 'Vis. Approved', icon: CheckCircle },
  { label: 'Deliverables', icon: Package },
  { label: 'Del. Approved', icon: CheckCircle },
  { label: 'Code Gen', icon: Code },
  { label: 'Complete', icon: Zap },
];

const DELIVERABLE_ICONS: Record<string, typeof Code> = {
  api_route: GitBranch,
  ui_component: Layers,
  data_model: Database,
  config: Settings,
  documentation: BookOpen,
  test: TestTube,
};

export default function IntakeDetailPage() {
  const params = useParams();
  const router = useRouter();
  const [intake, setIntake] = useState<Intake | null>(null);
  const [artifacts, setArtifacts] = useState<Artifact[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState('');
  const [revisionReason, setRevisionReason] = useState('');
  const [showRevisionInput, setShowRevisionInput] = useState(false);
  const [estimate, setEstimate] = useState<Record<string, unknown> | null>(null);
  const [error, setError] = useState('');

  // Per-visual feedback state
  const [visualFeedback, setVisualFeedback] = useState<Record<string, string>>({});
  const [showVisualFeedback, setShowVisualFeedback] = useState<string | null>(null);

  // Edit mode state
  const [editMode, setEditMode] = useState(false);
  const [editData, setEditData] = useState<Record<string, unknown>>({});

  const fetchIntake = useCallback(async () => {
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}`);
      const data = await res.json();
      if (data.intake) {
        setIntake(data.intake);
        if (data.artifacts) setArtifacts(data.artifacts);
      } else setError('Intake not found');
    } catch { setError('Failed to load intake'); }
    setLoading(false);
  }, [params.id]);

  useEffect(() => { fetchIntake(); }, [fetchIntake]);

  const handleApprove = async () => {
    setActionLoading('approve');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/approve`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason: 'Approved' }),
      });
      if (res.ok) await fetchIntake();
      else { const d = await res.json(); setError(d.error); }
    } catch { setError('Approval failed'); }
    setActionLoading('');
  };

  const handleRevision = async () => {
    if (!revisionReason.trim()) return;
    setActionLoading('revision');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/approve`, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason: revisionReason }),
      });
      if (res.ok) { setShowRevisionInput(false); setRevisionReason(''); await fetchIntake(); }
      else { const d = await res.json(); setError(d.error); }
    } catch { setError('Revision request failed'); }
    setActionLoading('');
  };

  const handleEstimate = async () => {
    setActionLoading('estimate');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/estimate`, { method: 'POST' });
      const data = await res.json();
      if (data.estimate) { setEstimate(data.estimate); await fetchIntake(); }
      else setError(data.error);
    } catch { setError('Estimation failed'); }
    setActionLoading('');
  };

  const handleGenerateVisuals = async () => {
    setActionLoading('visuals');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/visuals`, { method: 'POST' });
      if (res.ok) await fetchIntake();
      else { const d = await res.json(); setError(d.error); }
    } catch { setError('Visual generation failed'); }
    setActionLoading('');
  };

  const handleGenerateDeliverables = async () => {
    setActionLoading('deliverables');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/deliverables`, { method: 'POST' });
      if (res.ok) await fetchIntake();
      else { const d = await res.json(); setError(d.error); }
    } catch { setError('Deliverable generation failed'); }
    setActionLoading('');
  };

  // H1: Code Generation bridge
  const handleGenerateCode = async () => {
    setActionLoading('generate');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/generate`, { method: 'POST' });
      const data = await res.json();
      if (res.ok) {
        await fetchIntake();
        setError('');
      } else {
        setError(data.error || 'Code generation failed');
      }
    } catch { setError('Code generation failed'); }
    setActionLoading('');
  };

  // H2: Per-visual approve/revise
  const handleVisualAction = async (visualId: string, action: 'approve' | 'request_revision') => {
    const feedback = visualFeedback[visualId] || '';
    if (action === 'request_revision' && !feedback.trim()) return;
    setActionLoading(`visual-${visualId}`);
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/visuals/${visualId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action, feedback }),
      });
      if (res.ok) {
        setShowVisualFeedback(null);
        setVisualFeedback(prev => { const next = { ...prev }; delete next[visualId]; return next; });
        await fetchIntake();
      } else {
        const d = await res.json();
        setError(d.error);
      }
    } catch { setError('Visual action failed'); }
    setActionLoading('');
  };

  // L1: Live-edit visual content
  const handleVisualContentChange = async (visualId: string, newContent: string) => {
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/visuals/${visualId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: newContent }),
      });
      if (res.ok) {
        await fetchIntake();
      } else {
        const d = await res.json();
        setError(d.error || 'Failed to save visual edit');
      }
    } catch { setError('Failed to save visual edit'); }
  };

  // H3: Edit mode save
  const enterEditMode = () => {
    if (!intake) return;
    setEditData({
      title: intake.title,
      problemStatement: intake.problemStatement,
      businessDomain: intake.businessDomain,
      clientName: intake.clientName || '',
      clientCompany: intake.clientCompany || '',
      budget: intake.budget || '',
      timeline: intake.timeline || '',
      notes: intake.notes || '',
    });
    setEditMode(true);
  };

  const handleSaveEdit = async () => {
    setActionLoading('save');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editData),
      });
      if (res.ok) {
        setEditMode(false);
        await fetchIntake();
      } else {
        const d = await res.json();
        setError(d.error);
      }
    } catch { setError('Save failed'); }
    setActionLoading('');
  };

  const handleClone = async () => {
    setActionLoading('clone');
    try {
      const res = await fetch(`/api/dark-factory/intake/${params.id}/clone`, { method: 'POST' });
      const data = await res.json();
      if (res.ok && data.intake) {
        router.push(`/dark-factory/app/intake/${data.intake.id}`);
      } else {
        setError(data.error || 'Clone failed');
      }
    } catch { setError('Clone failed'); }
    setActionLoading('');
  };

  if (loading) return <div className="text-center py-16 text-gray-500">Loading intake...</div>;
  if (!intake) return <div className="text-center py-16 text-red-400">{error || 'Not found'}</div>;

  const gateConfig = GATE_CONFIG[intake.gate] || GATE_CONFIG.intake_draft;
  const currentStep = gateConfig.step;

  const canApprove = ['intake_draft', 'intake_revision', 'visuals_generated', 'visuals_revision', 'deliverables_defined', 'deliverables_revision'].includes(intake.gate);
  const canRevise = ['intake_draft', 'intake_approved', 'visuals_generated', 'visuals_approved', 'deliverables_defined', 'deliverables_approved'].includes(intake.gate);
  const canGenerateVisuals = intake.gate === 'intake_approved';
  const canGenerateDeliverables = intake.gate === 'visuals_approved';
  const canGenerateCode = intake.gate === 'deliverables_approved';
  const canEdit = ['intake_draft', 'intake_revision'].includes(intake.gate);
  const isGenerating = intake.gate === 'code_generating';

  return (
    <div className="space-y-6 max-w-5xl mx-auto">
      {/* Header */}
      <div className="flex items-start gap-3">
        <Link href="/dark-factory/app/intake" className="text-gray-400 hover:text-white mt-1"><ArrowLeft className="w-5 h-5" /></Link>
        <div className="flex-1">
          <h1 className="text-2xl font-bold text-white">{intake.title}</h1>
          <p className="text-gray-400 text-sm mt-1">
            {intake.clientCompany || intake.clientName || 'Internal'} · {intake.businessDomain} · {intake.targetLanguage} + {intake.targetDatabase}
          </p>
        </div>
        <div className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium ${gateConfig.color} bg-white/5`}>
          {gateConfig.label}
        </div>
      </div>

      {error && <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">{error} <button onClick={() => setError('')} className="ml-2 underline">dismiss</button></div>}

      {/* Pipeline Progress */}
      <div className="bg-slate-900 border border-slate-700 rounded-xl p-4">
        <div className="flex items-center justify-between overflow-x-auto gap-1">
          {PIPELINE_STEPS.map((step, i) => {
            const StepIcon = step.icon;
            const isActive = i === currentStep;
            const isDone = i < currentStep;
            return (
              <div key={step.label} className="flex items-center gap-1 min-w-0">
                <div className={`flex items-center gap-1.5 px-2 py-1 rounded-lg text-xs whitespace-nowrap ${
                  isActive ? 'bg-brand-deep/20 text-brand border border-brand-deep/40' :
                  isDone ? 'bg-green-500/10 text-green-400' : 'text-gray-600'
                }`}>
                  <StepIcon className="w-3.5 h-3.5 flex-shrink-0" />
                  <span className="hidden sm:inline">{step.label}</span>
                </div>
                {i < PIPELINE_STEPS.length - 1 && <ChevronRight className={`w-3 h-3 flex-shrink-0 ${isDone ? 'text-green-600' : 'text-gray-700'}`} />}
              </div>
            );
          })}
        </div>
      </div>

      {/* Action Bar */}
      <div className="bg-slate-900 border border-slate-700 rounded-xl p-4">
        <div className="flex flex-wrap gap-2">
          {canApprove && (
            <button onClick={handleApprove} disabled={!!actionLoading}
              className="flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
              {actionLoading === 'approve' ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
              Approve Gate
            </button>
          )}
          {canRevise && (
            <button onClick={() => setShowRevisionInput(!showRevisionInput)} disabled={!!actionLoading}
              className="flex items-center gap-2 px-4 py-2 bg-amber-600 hover:bg-amber-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
              <RotateCcw className="w-4 h-4" /> Request Revision
            </button>
          )}
          {canEdit && !editMode && (
            <button onClick={enterEditMode} disabled={!!actionLoading}
              className="flex items-center gap-2 px-4 py-2 bg-slate-700 hover:bg-slate-600 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
              <Settings className="w-4 h-4" /> Edit Intake
            </button>
          )}
          {canGenerateVisuals && (
            <button onClick={handleGenerateVisuals} disabled={!!actionLoading}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
              {actionLoading === 'visuals' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
              Generate Visuals
            </button>
          )}
          {canGenerateDeliverables && (
            <button onClick={handleGenerateDeliverables} disabled={!!actionLoading}
              className="flex items-center gap-2 px-4 py-2 bg-sky-600 hover:bg-sky-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
              {actionLoading === 'deliverables' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Package className="w-4 h-4" />}
              Generate Deliverables
            </button>
          )}
          {canGenerateCode && (
            <button onClick={handleGenerateCode} disabled={!!actionLoading}
              className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-orange-600 to-pink-600 hover:from-orange-700 hover:to-pink-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium shadow-lg shadow-orange-500/20">
              {actionLoading === 'generate' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
              Generate Code
            </button>
          )}
          {isGenerating && (
            <div className="flex items-center gap-2 px-4 py-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-orange-400 text-sm">
              <Loader2 className="w-4 h-4 animate-spin" /> Pipeline running... Poll status for progress.
            </div>
          )}
          {intake.gate === 'intake_approved' && !intake.complexityScore && (
            <button onClick={handleEstimate} disabled={!!actionLoading}
              className="flex items-center gap-2 px-4 py-2 bg-orange-600 hover:bg-orange-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
              {actionLoading === 'estimate' ? <Loader2 className="w-4 h-4 animate-spin" /> : <BarChart3 className="w-4 h-4" />}
              Run Estimate
            </button>
          )}
          <button onClick={handleClone} disabled={!!actionLoading}
            className="flex items-center gap-2 px-4 py-2 bg-slate-700 hover:bg-slate-600 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
            {actionLoading === 'clone' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Copy className="w-4 h-4" />}
            Duplicate
          </button>
          <button
            onClick={async () => {
              setActionLoading('pdf');
              try {
                const res = await fetch(`/api/dark-factory/intake/${params.id}/export-pdf`);
                if (res.ok) {
                  const blob = await res.blob();
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement('a');
                  a.href = url;
                  a.download = `${intake.title.replace(/[^a-zA-Z0-9_-]/g, '_')}_intake.pdf`;
                  a.click();
                  URL.revokeObjectURL(url);
                } else {
                  const d = await res.json().catch(() => ({ error: 'PDF export failed' }));
                  setError(d.error || 'PDF export failed');
                }
              } catch { setError('PDF export failed'); }
              setActionLoading('');
            }}
            disabled={!!actionLoading}
            className="flex items-center gap-2 px-4 py-2 bg-slate-700 hover:bg-slate-600 disabled:opacity-50 text-white rounded-lg text-sm font-medium"
          >
            {actionLoading === 'pdf' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
            Export PDF
          </button>
        </div>

        {showRevisionInput && (
          <div className="mt-3 flex gap-2">
            <input className="flex-1 bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm placeholder-gray-500"
              value={revisionReason} onChange={e => setRevisionReason(e.target.value)}
              placeholder="Reason for revision (required)..." />
            <button onClick={handleRevision} disabled={!revisionReason.trim() || !!actionLoading}
              className="px-4 py-2 bg-amber-600 hover:bg-amber-700 disabled:opacity-50 text-white rounded-lg text-sm">
              {actionLoading === 'revision' ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Send Back'}
            </button>
          </div>
        )}
      </div>

      {/* H3: Edit Mode Panel */}
      {editMode && (
        <div className="bg-slate-900 border border-blue-500/30 rounded-xl p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-white flex items-center gap-2"><Settings className="w-5 h-5 text-blue-400" /> Edit Intake</h3>
            <div className="flex gap-2">
              <button onClick={() => setEditMode(false)} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white">Cancel</button>
              <button onClick={handleSaveEdit} disabled={!!actionLoading}
                className="flex items-center gap-2 px-4 py-1.5 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium">
                {actionLoading === 'save' ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Save Changes'}
              </button>
            </div>
          </div>
          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs text-gray-500 mb-1">Title</label>
              <input className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm"
                value={(editData.title as string) || ''} onChange={e => setEditData(d => ({ ...d, title: e.target.value }))} />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Business Domain</label>
              <input className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm"
                value={(editData.businessDomain as string) || ''} onChange={e => setEditData(d => ({ ...d, businessDomain: e.target.value }))} />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Client Name</label>
              <input className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm"
                value={(editData.clientName as string) || ''} onChange={e => setEditData(d => ({ ...d, clientName: e.target.value }))} />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Client Company</label>
              <input className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm"
                value={(editData.clientCompany as string) || ''} onChange={e => setEditData(d => ({ ...d, clientCompany: e.target.value }))} />
            </div>
            <div className="md:col-span-2">
              <label className="block text-xs text-gray-500 mb-1">Problem Statement</label>
              <textarea className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm min-h-[120px]"
                value={(editData.problemStatement as string) || ''} onChange={e => setEditData(d => ({ ...d, problemStatement: e.target.value }))} />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Budget</label>
              <input className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm"
                value={(editData.budget as string) || ''} onChange={e => setEditData(d => ({ ...d, budget: e.target.value }))} />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Timeline</label>
              <input className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm"
                value={(editData.timeline as string) || ''} onChange={e => setEditData(d => ({ ...d, timeline: e.target.value }))} />
            </div>
            <div className="md:col-span-2">
              <label className="block text-xs text-gray-500 mb-1">Notes</label>
              <textarea className="w-full bg-slate-800 border border-slate-600 rounded-lg px-3 py-2 text-white text-sm min-h-[80px]"
                value={(editData.notes as string) || ''} onChange={e => setEditData(d => ({ ...d, notes: e.target.value }))} />
            </div>
          </div>
        </div>
      )}

      {/* Estimation Results */}
      {(intake.complexityScore || estimate) && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-lg font-semibold text-white mb-3 flex items-center gap-2"><BarChart3 className="w-5 h-5 text-orange-400" /> Complexity Estimate</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="text-center">
              <div className="text-2xl font-bold text-white">{intake.complexityScore || (estimate as Record<string, number>)?.complexityScore || '—'}<span className="text-sm text-gray-500">/10</span></div>
              <div className="text-xs text-gray-500">Complexity</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-white">{intake.estimatedHours || (estimate as Record<string, number>)?.estimatedHours || '—'}h</div>
              <div className="text-xs text-gray-500">Traditional Est.</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-green-400">{(estimate as Record<string, number>)?.dfEstimatedHours || Math.round((intake.estimatedHours || 80) * 0.25)}h</div>
              <div className="text-xs text-gray-500">With The Hearth</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-brand">${((estimate as Record<string, number>)?.dfEstimatedCost || (intake.estimatedCost ? intake.estimatedCost * 0.25 : 0)).toLocaleString()}</div>
              <div className="text-xs text-gray-500">DF Cost Est.</div>
            </div>
          </div>
          {(estimate as Record<string, string[]>)?.riskFactors?.length > 0 && (
            <div className="mt-3 text-xs text-gray-500">
              <span className="text-amber-400">Risks:</span> {((estimate as Record<string, string[]>).riskFactors).join(', ')}
            </div>
          )}
        </div>
      )}

      {/* Problem Statement & Scope */}
      <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
        <h3 className="text-lg font-semibold text-white mb-3">Problem Statement</h3>
        <p className="text-gray-300 text-sm whitespace-pre-wrap">{intake.problemStatement}</p>
        
        <div className="grid md:grid-cols-2 gap-6 mt-6">
          {intake.targetUsers.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-400 mb-2">Target Users</h4>
              <div className="flex flex-wrap gap-1.5">
                {intake.targetUsers.map((u, i) => <span key={i} className="px-2 py-0.5 bg-slate-800 rounded text-xs text-gray-300">{String(u)}</span>)}
              </div>
            </div>
          )}
          {intake.coreWorkflows.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-400 mb-2">Core Workflows</h4>
              <div className="flex flex-wrap gap-1.5">
                {intake.coreWorkflows.map((w, i) => <span key={i} className="px-2 py-0.5 bg-brand-deep/10 border border-brand-deep/20 rounded text-xs text-brand">{String(w)}</span>)}
              </div>
            </div>
          )}
          {intake.constraints.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-400 mb-2">Constraints</h4>
              <div className="flex flex-wrap gap-1.5">
                {intake.constraints.map((c, i) => <span key={i} className="px-2 py-0.5 bg-red-500/10 border border-red-500/20 rounded text-xs text-red-400">{String(c)}</span>)}
              </div>
            </div>
          )}
          {intake.integrations.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-400 mb-2">Integrations</h4>
              <div className="flex flex-wrap gap-1.5">
                {intake.integrations.map((ig, i) => <span key={i} className="px-2 py-0.5 bg-orange-500/10 border border-orange-500/20 rounded text-xs text-orange-400">{String(ig)}</span>)}
              </div>
            </div>
          )}
        </div>

        {(intake.budget || intake.timeline) && (
          <div className="flex gap-6 mt-4 pt-4 border-t border-slate-700/50">
            {intake.budget && <div><span className="text-xs text-gray-500">Budget:</span> <span className="text-sm text-gray-300">{intake.budget}</span></div>}
            {intake.timeline && <div><span className="text-xs text-gray-500">Timeline:</span> <span className="text-sm text-gray-300">{intake.timeline}</span></div>}
          </div>
        )}
      </div>

      {/* Entities */}
      {intake.entities.length > 0 && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-lg font-semibold text-white mb-3 flex items-center gap-2"><Database className="w-5 h-5 text-sky-400" /> Data Entities ({intake.entities.length})</h3>
          <div className="grid md:grid-cols-2 gap-3">
            {intake.entities.map(entity => (
              <div key={entity.id} className="p-3 bg-slate-800/50 border border-slate-700/50 rounded-lg">
                <div className="flex items-center gap-2">
                  <span className="text-white font-medium text-sm">{entity.name}</span>
                  {entity.isCore && <span className="text-[10px] px-1.5 py-0.5 bg-brand-deep/20 text-brand rounded">core</span>}
                </div>
                {entity.description && <p className="text-gray-500 text-xs mt-1">{entity.description}</p>}
                {entity.fields.length > 0 && (
                  <div className="mt-2 flex flex-wrap gap-1">
                    {entity.fields.map((f, i) => (
                      <span key={i} className="text-[10px] px-1.5 py-0.5 bg-slate-700 rounded text-gray-400">
                        {f.name}: <span className="text-gray-500">{f.type}</span>
                      </span>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Acceptance Criteria */}
      {intake.acceptanceCriteria.length > 0 && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-lg font-semibold text-white mb-3">Acceptance Criteria ({intake.acceptanceCriteria.length})</h3>
          <div className="space-y-2">
            {intake.acceptanceCriteria.map(c => (
              <div key={c.id} className="flex items-start gap-2 text-sm">
                <span className={`text-[10px] px-1.5 py-0.5 rounded mt-0.5 ${
                  c.priority === 'must' ? 'bg-red-500/10 text-red-400' :
                  c.priority === 'should' ? 'bg-amber-500/10 text-amber-400' :
                  'bg-gray-500/10 text-gray-400'
                }`}>{c.priority}</span>
                <span className="text-gray-300">{c.description}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Visuals */}
      {intake.visuals.length > 0 && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2"><Eye className="w-5 h-5 text-blue-400" /> Visual Artifacts ({intake.visuals.length})</h3>
          <div className="space-y-4">
            {intake.visuals.map(visual => (
              <div key={visual.id} className={`border rounded-lg overflow-hidden ${
                visual.status === 'approved' ? 'border-green-500/30' :
                visual.status === 'revision_requested' ? 'border-amber-500/30' :
                'border-slate-700/50'
              }`}>
                <div className="flex items-center justify-between px-4 py-2 bg-slate-800/50">
                  <div className="flex items-center gap-2">
                    <span className="text-white font-medium text-sm">{visual.title}</span>
                    <span className="text-[10px] px-1.5 py-0.5 bg-slate-700 rounded text-gray-400">{visual.type}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className={`text-xs ${visual.status === 'approved' ? 'text-green-400' : visual.status === 'revision_requested' ? 'text-amber-400' : 'text-gray-500'}`}>
                      {visual.status === 'approved' ? '✓ Approved' : visual.status === 'revision_requested' ? '↩ Revision' : 'Draft'}
                    </span>
                    {/* Per-visual approve/revise buttons */}
                    {['visuals_generated', 'visuals_revision'].includes(intake.gate) && visual.status !== 'approved' && (
                      <>
                        <button
                          onClick={() => handleVisualAction(visual.id, 'approve')}
                          disabled={!!actionLoading}
                          className="flex items-center gap-1 px-2 py-1 bg-green-600/80 hover:bg-green-600 disabled:opacity-50 text-white rounded text-[10px] font-medium"
                        >
                          {actionLoading === `visual-${visual.id}` ? <Loader2 className="w-3 h-3 animate-spin" /> : <CheckCircle className="w-3 h-3" />}
                          Approve
                        </button>
                        <button
                          onClick={() => setShowVisualFeedback(showVisualFeedback === visual.id ? null : visual.id)}
                          disabled={!!actionLoading}
                          className="flex items-center gap-1 px-2 py-1 bg-amber-600/80 hover:bg-amber-600 disabled:opacity-50 text-white rounded text-[10px] font-medium"
                        >
                          <RotateCcw className="w-3 h-3" /> Revise
                        </button>
                      </>
                    )}
                  </div>
                </div>
                {/* Per-visual feedback input */}
                {showVisualFeedback === visual.id && (
                  <div className="flex gap-2 px-4 py-2 bg-amber-500/5 border-t border-amber-500/20">
                    <input
                      className="flex-1 bg-slate-800 border border-slate-600 rounded px-2 py-1 text-white text-xs placeholder-gray-500"
                      value={visualFeedback[visual.id] || ''}
                      onChange={e => setVisualFeedback(prev => ({ ...prev, [visual.id]: e.target.value }))}
                      placeholder="What needs to change? (required)"
                    />
                    <button
                      onClick={() => handleVisualAction(visual.id, 'request_revision')}
                      disabled={!(visualFeedback[visual.id] || '').trim() || !!actionLoading}
                      className="px-3 py-1 bg-amber-600 hover:bg-amber-700 disabled:opacity-50 text-white rounded text-xs"
                    >
                      Send Feedback
                    </button>
                  </div>
                )}
                {visual.feedback && visual.status === 'revision_requested' && (
                  <div className="px-4 py-2 bg-amber-500/5 border-t border-amber-500/20 text-xs text-amber-400">
                    <span className="font-medium">Feedback:</span> {visual.feedback}
                  </div>
                )}
                <MermaidDiagram
                  code={visual.content}
                  editable={['visuals_generated', 'visuals_revision'].includes(intake.gate) && visual.status !== 'approved'}
                  onCodeChange={(newCode) => handleVisualContentChange(visual.id, newCode)}
                />
                {visual.description && <p className="px-4 py-2 text-xs text-gray-500 border-t border-slate-700/30">{visual.description}</p>}
              </div>
            ))}
            {/* All-approved hint */}
            {intake.visuals.length > 0 && intake.visuals.every(v => v.status === 'approved') && ['visuals_generated', 'visuals_revision'].includes(intake.gate) && (
              <div className="p-3 bg-green-500/10 border border-green-500/20 rounded-lg text-green-400 text-sm text-center">
                All visuals approved. Use <strong>Approve Gate</strong> above to advance to the deliverables stage.
              </div>
            )}
          </div>
        </div>
      )}

      {/* Deliverables */}
      {intake.deliverables.length > 0 && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2"><Package className="w-5 h-5 text-sky-400" /> Deliverables ({intake.deliverables.length})</h3>
          <div className="space-y-2">
            {intake.deliverables.map(d => {
              const DIcon = DELIVERABLE_ICONS[d.type] || FileCode;
              return (
                <div key={d.id} className="flex items-start gap-3 p-3 bg-slate-800/30 border border-slate-700/30 rounded-lg">
                  <DIcon className="w-4 h-4 text-gray-500 mt-0.5 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-white text-sm font-medium">{d.name}</span>
                      <span className="text-[10px] px-1.5 py-0.5 bg-slate-700 rounded text-gray-400">{d.type}</span>
                    </div>
                    {d.description && <p className="text-gray-500 text-xs mt-0.5">{d.description}</p>}
                    {d.acceptanceCriteria && <p className="text-green-500/60 text-xs mt-0.5">✓ {d.acceptanceCriteria}</p>}
                  </div>
                  <span className={`text-xs whitespace-nowrap ${
                    d.status === 'approved' ? 'text-green-400' :
                    d.status === 'generated' ? 'text-blue-400' :
                    d.status === 'reviewed' ? 'text-orange-400' :
                    'text-gray-500'
                  }`}>{d.status}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Generated Artifacts (M4 traceability) */}
      {artifacts.length > 0 && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <FileCode className="w-5 h-5 text-green-400" /> Generated Artifacts ({artifacts.length})
          </h3>
          <div className="space-y-1.5">
            {artifacts.map(a => (
              <div key={a.id} className="flex items-center gap-3 px-3 py-2 bg-slate-800/30 border border-slate-700/30 rounded-lg text-sm">
                <Code className="w-3.5 h-3.5 text-gray-500 flex-shrink-0" />
                <span className="text-gray-300 font-mono text-xs truncate flex-1">{a.path}</span>
                <span className="text-[10px] px-1.5 py-0.5 bg-slate-700 rounded text-gray-400">{a.type}</span>
                <span className="text-[10px] text-gray-600">v{a.version}</span>
              </div>
            ))}
          </div>
          {intake.generationRequestId && (
            <div className="mt-3 text-xs text-gray-600">
              Generation Request: <span className="font-mono text-gray-500">{intake.generationRequestId}</span>
            </div>
          )}
        </div>
      )}

      {/* Revision Log */}
      {intake.revisionLog.length > 0 && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-lg font-semibold text-white mb-3 flex items-center gap-2"><Clock className="w-5 h-5 text-gray-400" /> Audit Trail</h3>
          <div className="space-y-2">
            {intake.revisionLog.map(entry => (
              <div key={entry.id} className="flex items-start gap-3 text-sm">
                <div className={`w-2 h-2 rounded-full mt-1.5 flex-shrink-0 ${
                  entry.action === 'approved' ? 'bg-green-400' :
                  entry.action === 'revision_requested' ? 'bg-amber-400' :
                  entry.action === 'created' ? 'bg-blue-400' :
                  'bg-gray-500'
                }`} />
                <div className="flex-1">
                  <span className="text-gray-300">{entry.action.replace(/_/g, ' ')}</span>
                  <span className="text-gray-600 mx-1">at</span>
                  <span className="text-gray-500">{entry.gate.replace(/_/g, ' ')}</span>
                  {entry.reason && <span className="text-gray-500"> — {entry.reason}</span>}
                </div>
                <span className="text-gray-600 text-xs whitespace-nowrap">{new Date(entry.createdAt).toLocaleDateString()}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {intake.notes && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl p-5">
          <h3 className="text-sm font-medium text-gray-400 mb-2">Notes</h3>
          <p className="text-gray-300 text-sm whitespace-pre-wrap">{intake.notes}</p>
        </div>
      )}
    </div>
  );
}
