import React, { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes, FaPlus, FaCheckCircle,
  FaTimesCircle, FaTasks, FaClock, FaExternalLinkAlt,
  FaChevronDown, FaChevronRight, FaSpinner, FaMoneyBillWave,
  FaChartLine, FaBell, FaFolderOpen,
  FaBoxes,
  FaShoppingCart,
  FaBullhorn,
  FaTrash,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import {
  useProjectDetails, useProjectTasks, useProjectTimesheets, useProjectMutations,
} from '../hooks/useProject';
import LinkField from '../components/LinkField';
import ActivityLog from '../components/ActivityLog';
import type { Project } from '../services/projectService';
import projectService, {
  CUSTOM_PROJECT_UPDATES,
  serializeProgressUpdateRows,
  type ProgressUpdateChildRow,
} from '../services/projectService';
import salesOrderService from '../services/salesOrderService';
import { DEFAULT_COMPANY, formatOrgCurrencyAmount } from '../constants/orgDefaults';
import { formatFrappeApiError } from '../utils/frappeErrorMessage';
import { formatProjectNotesForDisplay } from '../utils/projectNotesDisplay';

// ─── Collapsible Section ─────────────────────────────────────────────────────
const CollapsibleSection: React.FC<{
  title: string;
  icon?: React.ReactNode;
  defaultOpen?: boolean;
  children: React.ReactNode;
  badge?: React.ReactNode;
}> = ({ title, icon, defaultOpen = true, children, badge }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        className="w-full flex items-center justify-between px-5 py-3.5 hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors text-left"
      >
        <div className="flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-200">
          {icon}
          <span>{title}</span>
          {badge}
        </div>
        {open
          ? <FaChevronDown className="text-gray-400 text-xs flex-shrink-0" />
          : <FaChevronRight className="text-gray-400 text-xs flex-shrink-0" />}
      </button>
      {open && (
        <div className="px-5 py-5 bg-white dark:bg-gray-800 border-t border-gray-100 dark:border-gray-700/50">
          {children}
        </div>
      )}
    </div>
  );
};

// ─── Field label ──────────────────────────────────────────────────────────────
const FL: React.FC<{ children: React.ReactNode; required?: boolean }> = ({ children, required }) => (
  <label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">
    {children}{required && <span className="text-red-500 ml-0.5">*</span>}
  </label>
);

// Read-only value cell
const RV: React.FC<{ children?: React.ReactNode }> = ({ children }) => (
  <div className="px-3 py-2.5 text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-900/30 rounded-lg min-h-[38px] flex items-center border border-gray-100 dark:border-gray-700/50">
    {children || <span className="text-gray-400 dark:text-gray-600">—</span>}
  </div>
);

// ─── Stat chip in header ─────────────────────────────────────────────────────
const StatChip: React.FC<{
  icon: React.ReactNode;
  label: string;
  value: number | string;
  loading?: boolean;
  color: string;
  onClick?: () => void;
}> = ({ icon, label, value, loading, color, onClick }) => (
  <button
    onClick={onClick}
    disabled={!onClick}
    className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-xs font-semibold transition-all ${color} ${onClick ? 'hover:shadow-sm hover:scale-105 cursor-pointer' : 'cursor-default'}`}
  >
    <span>{icon}</span>
    {loading
      ? <FaSpinner className="animate-spin" size={10} />
      : <span className="font-bold">{value}</span>}
    <span className="font-normal opacity-80">{label}</span>
  </button>
);

// ─── Style helpers ────────────────────────────────────────────────────────────
/** Status / priority chips: align with list “export” (green) and “print” (purple) accents used on assets / work orders */
const statusBadge = (s: string) => {
  switch (s?.toLowerCase()) {
    case 'open':      return 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300 border border-green-200/90 dark:border-green-800';
    case 'completed': return 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300 border border-emerald-200/90 dark:border-emerald-800';
    case 'cancelled': return 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400 border border-slate-200 dark:border-slate-600';
    default:          return 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400 border border-slate-200 dark:border-slate-600';
  }
};
const priorityBadge = (p: string) => {
  switch (p?.toLowerCase()) {
    case 'high':   return 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300 border border-red-200 dark:border-red-800';
    case 'medium': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300 border border-purple-200 dark:border-purple-700';
    case 'low':    return 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300 border border-green-200 dark:border-green-800';
    case 'urgent': return 'bg-red-200 text-red-900 dark:bg-red-800/50 dark:text-red-200 border border-red-300 dark:border-red-700';
    default:       return 'bg-slate-100 text-slate-600 dark:bg-slate-700 border border-slate-200 dark:border-slate-600';
  }
};
const fmtDate = (d?: string) =>
  d ? new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '—';
const fmtCurrency = formatOrgCurrencyAmount;
const fmtTime = (t?: string) => (t ? t.substring(0, 8) : '');

// ─── Component ────────────────────────────────────────────────────────────────
const ProjectDetail: React.FC = () => {
  const { t } = useTranslation();
  const { projectName } = useParams<{ projectName: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const isNew = projectName === 'new';
  const effectiveName = isNew ? null : projectName || null;
  const sourceSo = searchParams.get('source_so') || '';
  const duplicateFrom = useMemo(() => (isNew ? (searchParams.get('duplicate') || '') : ''), [isNew, searchParams]);
  const startInEditMode = useMemo(() => (!isNew && (searchParams.get('edit') || '') === '1'), [isNew, searchParams]);

  const [isEditing, setIsEditing] = useState(isNew);
  const [salesOrderCount, setSalesOrderCount] = useState<number | null>(null);
  const [selectedSalesOrder, setSelectedSalesOrder] = useState<string>('');
  const [salesOrderNames, setSalesOrderNames] = useState<string[]>([]);

  const { project, loading, error, refetch } = useProjectDetails(effectiveName);
  const { tasks, loading: tasksLoading } = useProjectTasks(effectiveName);
  const { timesheets, loading: tsLoading } = useProjectTimesheets(effectiveName);
  const { createProject, updateProject, loading: saving } = useProjectMutations();

  const submittedTs = timesheets.filter(ts => (ts as any).docstatus === 1);
  const tsTotal = {
    costing:  submittedTs.reduce((s, ts) => s + ((ts as any).total_costing_amount  || 0), 0),
    billable: submittedTs.reduce((s, ts) => s + ((ts as any).total_billable_amount || 0), 0),
    hours:    submittedTs.reduce((s, ts) => s + (ts.total_hours || 0), 0),
  };

  const blankForm: Partial<Project> = {
    project_name: '', status: 'Open', is_active: 'Yes', priority: 'Medium',
    company: DEFAULT_COMPANY, customer: '', project_template: '', project_type: '', custom_project_manager: '',
    expected_start_date: '', expected_end_date: '', department: '',
    percent_complete_method: 'Task Completion', percent_complete: 0,
    description: '', notes: '',
    estimated_costing: undefined,
    collect_progress: 0, holiday_list: '', frequency: 'Hourly', day_to_send: 'Monday',
    from_time: '', to_time: '', first_email: '', second_email: '',
    daily_time_to_send: '', weekly_time_to_send: '',
    subject: '', message: '',
  };
  const [form, setForm] = useState<Partial<Project>>(blankForm);
  const [isDuplicating, setIsDuplicating] = useState(false);
  /** Rows saved on Project (`custom_project_updates`). */
  const [projectOnlyUpdates, setProjectOnlyUpdates] = useState<ProgressUpdateChildRow[]>([]);
  /** Rows pulled from tasks’ `custom_task_updates` (read-only on this screen). */
  const [taskPulledUpdates, setTaskPulledUpdates] = useState<ProgressUpdateChildRow[]>([]);

  const syncForm = (p: Project) => setForm({
    project_name:            p.project_name || '',
    status:                  p.status || 'Open',
    is_active:               p.is_active || 'Yes',
    priority:                p.priority || 'Medium',
    company:                 p.company || DEFAULT_COMPANY,
    customer:                p.customer || '',
    project_template:        p.project_template || '',
    project_type:            p.project_type || '',
    custom_project_manager:  (p as any).custom_project_manager || '',
    expected_start_date:     p.expected_start_date || '',
    expected_end_date:       p.expected_end_date || '',
    department:              p.department || '',
    percent_complete_method: p.percent_complete_method || 'Task Completion',
    percent_complete:        p.percent_complete ?? 0,
    description:             p.description || '',
    notes:                   formatProjectNotesForDisplay(p.notes || '') || '',
    estimated_costing:       p.estimated_costing != null ? p.estimated_costing : undefined,
    collect_progress:        p.collect_progress ?? 0,
    holiday_list:            (p as any).holiday_list || '',
    frequency:               p.frequency || 'Hourly',
    from_time:               p.from_time || '',
    to_time:                 p.to_time || '',
    first_email:             p.first_email || '',
    second_email:            p.second_email || '',
    daily_time_to_send:      p.daily_time_to_send || '',
    day_to_send:             p.day_to_send || 'Monday',
    weekly_time_to_send:     p.weekly_time_to_send || '',
    subject:                 (p as any).subject || '',
    message:                 (p as any).message || '',
  });

  useEffect(() => { if (project && !isNew) syncForm(project); }, [project, isNew]);
  useEffect(() => { if (startInEditMode) setIsEditing(true); }, [startInEditMode]);

  useEffect(() => {
    if (isNew && !duplicateFrom) setProjectOnlyUpdates([]);
  }, [isNew, duplicateFrom]);

  useEffect(() => {
    if (!project || isNew) return;
    setProjectOnlyUpdates(
      (((project as any)[CUSTOM_PROJECT_UPDATES] || []) as ProgressUpdateChildRow[]).map(r => ({
        name: r.name,
        update_: r.update_,
        date: r.date ? String(r.date).slice(0, 10) : '',
        task: r.task,
      })),
    );
  }, [project, isNew]);

  useEffect(() => {
    if (!effectiveName || isNew) {
      setTaskPulledUpdates([]);
      return;
    }
    let cancelled = false;
    const names = tasks.map(t => t.name).filter(Boolean).slice(0, 120);
    (async () => {
      const docs = await Promise.all(names.map(n => projectService.getTask(n).catch(() => null)));
      if (cancelled) return;
      const acc: ProgressUpdateChildRow[] = [];
      for (const doc of docs) {
        if (!doc) continue;
        const rows = (doc as any).custom_task_updates || [];
        for (const r of rows) {
          acc.push({
            ...r,
            task: r.task || doc.name,
            date: r.date ? String(r.date).slice(0, 10) : r.date,
          });
        }
      }
      setTaskPulledUpdates(acc);
    })();
    return () => { cancelled = true; };
  }, [effectiveName, isNew, tasks]);

  const mergedProgressDisplay = useMemo(() => {
    type Row = { row: ProgressUpdateChildRow; source: 'task' | 'project'; projectIndex?: number };
    const fromTasks: Row[] = taskPulledUpdates.map(row => ({ row, source: 'task' as const }));
    const fromProject: Row[] = projectOnlyUpdates.map((row, projectIndex) => ({ row, source: 'project' as const, projectIndex }));
    const key = (r: ProgressUpdateChildRow) => String(r.date || '').slice(0, 10) || '';
    return [...fromTasks, ...fromProject].sort((a, b) => key(b.row).localeCompare(key(a.row)));
  }, [taskPulledUpdates, projectOnlyUpdates]);

  // Duplicate: prefill new project form from an existing project
  useEffect(() => {
    if (!isNew) return;
    if (!duplicateFrom) return;
    let cancelled = false;
    setIsDuplicating(true);
    projectService
      .getProject(duplicateFrom)
      .then((p) => {
        if (cancelled) return;
        const clone: Project = {
          ...p,
          name: '',
          project_name: p.project_name ? `${p.project_name} (Copy)` : '',
        };
        syncForm(clone);
        const pu = ((clone as any)[CUSTOM_PROJECT_UPDATES] || []) as ProgressUpdateChildRow[];
        setProjectOnlyUpdates(
          pu.map(r => ({
            update_: r.update_,
            date: r.date ? String(r.date).slice(0, 10) : '',
            task: r.task,
          })),
        );
        setIsEditing(true);
      })
      .catch(() => {
        // If duplicate fetch fails, keep blank form; user can continue creating manually.
      })
      .finally(() => {
        if (!cancelled) setIsDuplicating(false);
      });
    return () => { cancelled = true; };
  }, [isNew, duplicateFrom]);

  useEffect(() => {
    if (!effectiveName || isNew) { setSalesOrderCount(null); setSalesOrderNames([]); return; }
    let cancelled = false;
    salesOrderService
      .getSalesOrderCount([['Sales Order', 'project', '=', effectiveName]])
      .then(c => { if (!cancelled) setSalesOrderCount(c); })
      .catch(() => { if (!cancelled) setSalesOrderCount(0); });
    return () => { cancelled = true; };
  }, [effectiveName, isNew]);

  useEffect(() => {
    if (sourceSo) { setSelectedSalesOrder(sourceSo); return; }
    if (!effectiveName || isNew) { setSelectedSalesOrder(''); return; }
    // Default selection: most recently modified SO for this project
    salesOrderService
      .getSalesOrderNamesForProject(effectiveName, 1)
      .then((names) => setSelectedSalesOrder(names?.[0] || ''))
      .catch(() => setSelectedSalesOrder(''));
  }, [effectiveName, isNew, sourceSo]);

  useEffect(() => {
    // Sales Order selection is now a LinkField filtered by project.
    // Keep this state reset to avoid holding unused data.
    setSalesOrderNames([]);
  }, [effectiveName, isNew, salesOrderCount]);

  const set = (k: keyof Project, v: any) => setForm(f => ({ ...f, [k]: v }));
  const editable = isNew || isEditing;
  /** New projects: always show. Existing: only if “Collect progress” is on, or while editing so it can be enabled. */
  const showMonitorProgress = isNew || isEditing || !!Number(form.collect_progress);

  const inputCls = 'w-full px-3 py-2.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-blue-400 focus:outline-none transition-colors';
  const selectCls = 'w-full px-3 py-2.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-blue-400 focus:outline-none transition-colors';

  const handleSave = async () => {
    if (!form.project_name?.trim()) { toast.error('Project Name is required', { icon: <FaTimesCircle /> }); return; }
    const savePayload: Partial<Project> = {
      ...form,
      estimated_costing: form.estimated_costing ?? 0,
      [CUSTOM_PROJECT_UPDATES]: serializeProgressUpdateRows(projectOnlyUpdates) as any,
    };
    try {
      if (isNew) {
        const created = await createProject(savePayload);
        toast.success('Project created successfully', { icon: <FaCheckCircle /> });
        setIsEditing(false);
        // If this project was created from a Sales Order, link it back in the background
        // but keep the user on the Project page (do not navigate away).
        if (sourceSo) {
          try {
            await salesOrderService.updateSalesOrder(sourceSo, { project: created.name } as any);
          } catch (e) {
            toast.error(formatFrappeApiError(e) || 'Failed to link Sales Order', { icon: <FaTimesCircle /> });
          }
          navigate(`/projects/list/${created.name}?source_so=${encodeURIComponent(sourceSo)}`);
          return;
        }
        navigate(`/projects/list/${created.name}`);
      } else {
        await updateProject(projectName!, savePayload);
        toast.success('Project saved', { icon: <FaCheckCircle /> });
        setIsEditing(false);
        refetch();
      }
    } catch (err) {
      toast.error(formatFrappeApiError(err) || 'Error saving project', { icon: <FaTimesCircle /> });
    }
  };

  const handleCancel = () => {
    if (project) {
      syncForm(project);
      setProjectOnlyUpdates(
        (((project as any)[CUSTOM_PROJECT_UPDATES] || []) as ProgressUpdateChildRow[]).map(r => ({
          name: r.name,
          update_: r.update_,
          date: r.date ? String(r.date).slice(0, 10) : '',
          task: r.task,
        })),
      );
    }
    setIsEditing(false);
  };

  // ─── Loading / Error ────────────────────────────────────────────────────────
  if (loading && !isNew) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-3">
          <div className="animate-spin rounded-full h-10 w-10 border-[3px] border-blue-600 border-t-transparent" />
          <p className="text-sm text-gray-500">Loading project…</p>
        </div>
      </div>
    );
  }
  if (!isNew && (error || !project)) {
    return (
      <div className="p-6">
        <button onClick={() => navigate('/projects/list')} className="flex items-center gap-2 text-gray-600 dark:text-gray-400 mb-4 text-sm hover:text-gray-900">
          <FaArrowLeft /> Back to Projects
        </button>
        <div className="p-4 bg-red-50 dark:bg-red-900/20 rounded-lg text-red-700 dark:text-red-300">{error || 'Project not found'}</div>
      </div>
    );
  }

  // ─── Render ────────────────────────────────────────────────────────────────
  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      <ToastContainer position="top-right" autoClose={3500} />

      {/* ── Hero / Header ── */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="px-6 py-4">

          {/* Breadcrumb */}
          <div className="flex items-center gap-1.5 text-xs mb-3 text-gray-400 dark:text-gray-500">
            <button onClick={() => navigate('/projects')} className="hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
              {t('projects.moduleTitle', 'Project Management')}
            </button>
            <span>/</span>
            <button onClick={() => navigate('/projects/list')} className="hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
              Projects
            </button>
            <span>/</span>
            <span className="text-gray-600 dark:text-gray-300 font-medium">
              {isNew ? 'New Project' : (project?.project_name || projectName)}
            </span>
          </div>

          {/* Title row */}
          <div className="flex items-start justify-between gap-4 flex-nowrap overflow-x-auto">
            <div className="flex items-start gap-3 min-w-0">
              <button
                onClick={() => navigate('/projects/list')}
                className="mt-1 p-1.5 rounded-lg text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex-shrink-0"
              >
                <FaArrowLeft size={13} />
              </button>
              <div className="min-w-0">
                <div className="flex items-center gap-3 flex-wrap">
                  <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center flex-shrink-0 shadow-sm">
                    <FaFolderOpen className="text-white text-sm" />
                  </div>
                  <div>
                    <h1 className="text-xl font-bold text-gray-900 dark:text-white leading-tight">
                      {isNew ? 'New Project' : (project?.project_name || projectName)}
                    </h1>
                    {isNew && duplicateFrom && (
                      <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                        Duplicating from <span className="font-mono">{duplicateFrom}</span>{isDuplicating ? '…' : ''}
                      </p>
                    )}
                    {!isNew && <p className="text-xs text-gray-400 dark:text-gray-500 font-mono">{projectName}</p>}
                  </div>
                </div>

                {/* Status/priority badges + connection count chips */}
                {!isNew && (
                  <div className="flex items-center flex-wrap gap-2 mt-3 ml-12">
                    <span className={`px-2.5 py-1 rounded-lg text-xs font-semibold ${statusBadge(project?.status || '')}`}>
                      {project?.status || 'Open'}
                    </span>
                    <span className={`px-2.5 py-1 rounded-lg text-xs font-semibold ${priorityBadge(project?.priority || '')}`}>
                      {project?.priority || '—'}
                    </span>
                    {/* Company chip intentionally hidden (per UI request) */}

                    {/* Progress bar */}
                    <div className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
                      <div className="w-20 h-1.5 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden">
                        <div className="h-full bg-green-600 dark:bg-green-500 rounded-full transition-all" style={{ width: `${Math.min(project?.percent_complete ?? 0, 100)}%` }} />
                      </div>
                      <span className="font-semibold tabular-nums">{project?.percent_complete ?? 0}%</span>
                    </div>

                    {/* Connection count chips — purple (print-style) + green (export-style) */}
                    <StatChip
                      icon={<FaTasks size={10} />}
                      label="Tasks"
                      value={tasks.length}
                      loading={tasksLoading}
                      color="bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-700 text-purple-800 dark:text-purple-200"
                      onClick={() => navigate(`/projects/tasks?project=${projectName}`)}
                    />
                    <StatChip
                      icon={<FaClock size={10} />}
                      label="Timesheets"
                      value={timesheets.length}
                      loading={tsLoading}
                      color="bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-700 text-green-800 dark:text-green-200"
                      onClick={() => navigate(`/projects/timesheets?project=${encodeURIComponent(projectName!)}`)}
                    />
                  </div>
                )}
              </div>
            </div>

            {/* Action buttons */}
            <div className="flex gap-2 flex-shrink-0 flex-nowrap items-center whitespace-nowrap">
              {!isNew && (
                <>
                  <button
                    type="button"
                    onClick={() => navigate(`/projects/tasks/new?project=${encodeURIComponent(projectName || '')}`)}
                    className="flex items-center gap-1.5 px-3 py-2 bg-cyan-600 hover:bg-cyan-700 text-white rounded-lg text-xs font-medium shadow-sm transition-colors"
                  >
                    <FaPlus size={10} /><FaTasks size={10} /> Task
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      const params = new URLSearchParams();
                      params.set('project', projectName || '');
                      if (form.customer) params.set('customer', form.customer);
                      if (form.company)  params.set('company',  form.company);
                      navigate(`/projects/timesheets/new?${params.toString()}`);
                    }}
                    className="flex items-center gap-1.5 px-3 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-xs font-medium shadow-sm transition-colors"
                  >
                    <FaPlus size={10} /><FaClock size={10} /> Timesheet
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      const params = new URLSearchParams();
                      params.set('project', projectName || '');
                      if (form.customer) params.set('customer', form.customer);
                      if (form.company) params.set('company', form.company);
                      navigate(`/sales-orders/new?${params.toString()}`);
                    }}
                    className="flex items-center gap-1.5 px-3 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-xs font-medium shadow-sm transition-colors"
                  >
                    <FaPlus size={10} /><FaShoppingCart size={10} /> Sales Order
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      const params = new URLSearchParams();
                      params.set('project', projectName || '');
                      if (form.company) params.set('company', form.company);
                      navigate(`/material-requests/new?${params.toString()}`);
                    }}
                    className="flex items-center gap-1.5 px-3 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-lg text-xs font-medium shadow-sm transition-colors"
                  >
                    <FaPlus size={10} /><FaBoxes size={10} /> Material Request
                  </button>
                </>
              )}

              {!isEditing && !isNew && (
                <button
                  onClick={() => setIsEditing(true)}
                  className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-all shadow-lg hover:shadow-xl"
                >
                  <FaEdit size={12} /> Edit
                </button>
              )}
              {(isEditing || isNew) && (
                <>
                  <button
                    onClick={handleSave}
                    disabled={saving}
                    className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg disabled:opacity-50 text-sm font-medium transition-all shadow-lg hover:shadow-xl"
                  >
                    {saving ? <FaSpinner className="animate-spin" size={12} /> : <FaSave size={12} />}
                    {saving ? 'Saving…' : 'Save'}
                  </button>
                  {!isNew && (
                    <button
                      onClick={handleCancel}
                      className="flex items-center gap-1.5 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
                    >
                      <FaTimes size={12} /> Cancel
                    </button>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* ── Body ── */}
      <div className="px-6 py-6 space-y-3">

        {/* ── 1. Details (matches desk layout: name/status/type/active/method/complete | dates/priority/dept) ── */}
        <CollapsibleSection title="Details" defaultOpen={true}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5">
            <div>
              <FL required>Project Name</FL>
              {editable
                ? <input type="text" value={form.project_name || ''} onChange={e => set('project_name', e.target.value)} className={inputCls} placeholder="Enter project name" />
                : <RV>{form.project_name}</RV>}
            </div>
            <div>
              <FL>Expected Start Date</FL>
              {editable
                ? <input type="date" value={form.expected_start_date || ''} onChange={e => set('expected_start_date', e.target.value)} className={inputCls} />
                : <RV>{fmtDate(form.expected_start_date)}</RV>}
            </div>

            <div>
              <FL>Status</FL>
              {editable
                ? <select value={form.status || 'Open'} onChange={e => set('status', e.target.value)} className={selectCls}>
                    <option value="Open">Open</option>
                    <option value="Completed">Completed</option>
                    <option value="Cancelled">Cancelled</option>
                  </select>
                : <RV><span className={`px-2 py-0.5 rounded text-xs font-medium ${statusBadge(form.status || '')}`}>{form.status}</span></RV>}
            </div>
            <div>
              <FL>Expected End Date</FL>
              {editable
                ? <input type="date" value={form.expected_end_date || ''} onChange={e => set('expected_end_date', e.target.value)} className={inputCls} />
                : <RV>{fmtDate(form.expected_end_date)}</RV>}
            </div>

            <div>
              <FL>Project Type</FL>
              {editable
                ? <LinkField label="Project Type" hideLabel doctype="Project Type" value={form.project_type || ''} onChange={v => set('project_type', v)} placeholder="Select project type…" />
                : <RV>{form.project_type || '—'}</RV>}
            </div>
            <div>
              <FL>Priority</FL>
              {editable
                ? <select value={form.priority || 'Medium'} onChange={e => set('priority', e.target.value)} className={selectCls}>
                    <option value="Low">Low</option>
                    <option value="Medium">Medium</option>
                    <option value="High">High</option>
                    <option value="Urgent">Urgent</option>
                  </select>
                : <RV><span className={`px-2 py-0.5 rounded text-xs font-medium ${priorityBadge(form.priority || '')}`}>{form.priority}</span></RV>}
            </div>

            <div>
              <FL>Project Manager</FL>
              {editable
                ? (
                  <LinkField
                    label="Project Manager"
                    hideLabel
                    doctype="User"
                    value={form.custom_project_manager || ''}
                    onChange={v => set('custom_project_manager', v)}
                    placeholder="Select project manager…"
                  />
                )
                : <RV>{form.custom_project_manager || '—'}</RV>}
            </div>
            <div>
              <FL>Department</FL>
              {editable
                ? <LinkField label="Department" hideLabel doctype="Department" value={form.department || ''} onChange={v => set('department', v)} placeholder="Select department…" allowQuickCreate />
                : <RV>{form.department || '—'}</RV>}
            </div>

            <div>
              <FL>Is Active</FL>
              {editable
                ? <select value={form.is_active || 'Yes'} onChange={e => set('is_active', e.target.value)} className={selectCls}>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                  </select>
                : <RV>{form.is_active}</RV>}
            </div>
            <div>
              <FL>% Complete Method</FL>
              {editable
                ? <select value={form.percent_complete_method || 'Task Completion'} onChange={e => set('percent_complete_method', e.target.value)} className={selectCls}>
                    <option value="Manual">Manual</option>
                    <option value="Task Completion">Task Completion</option>
                    <option value="Task Progress">Task Progress</option>
                    <option value="Task Weight">Task Weight</option>
                  </select>
                : <RV>{form.percent_complete_method}</RV>}
            </div>

            <div>
              <FL>From Template</FL>
              {isNew
                ? <LinkField label="From Template" hideLabel doctype="Project Template" value={form.project_template || ''} onChange={v => set('project_template', v)} placeholder="Select template…" allowQuickCreate />
                : <RV>{form.project_template || '—'}</RV>}
            </div>
            <div>
              <FL>% Completed</FL>
              {editable && form.percent_complete_method === 'Manual'
                ? <input type="number" min={0} max={100} step={0.001} value={form.percent_complete ?? 0} onChange={e => set('percent_complete', parseFloat(e.target.value) || 0)} className={inputCls} />
                : <RV>
                    <div className="flex items-center gap-2 w-full min-w-0">
                      <div className="flex-1 h-2 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden min-w-0">
                        <div className="h-full bg-green-600 dark:bg-green-500 rounded-full transition-all" style={{ width: `${Math.min(form.percent_complete ?? 0, 100)}%` }} />
                      </div>
                      <span className="text-sm font-semibold min-w-[52px] text-right tabular-nums flex-shrink-0">
                        {(form.percent_complete ?? 0).toLocaleString('en-US', { minimumFractionDigits: 3, maximumFractionDigits: 3 })}%
                      </span>
                    </div>
                  </RV>}
            </div>
          </div>
        </CollapsibleSection>

        {/* ── Customer details (no Project Users table) ── */}
        <CollapsibleSection title="Customer Details" defaultOpen={true}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5">
            <div>
              <FL>Customer</FL>
              {editable
                ? <LinkField label="Customer" hideLabel doctype="Customer" value={form.customer || ''} onChange={v => set('customer', v)} placeholder="Select customer…" allowQuickCreate />
                : <RV>{form.customer || '—'}</RV>}
            </div>
            <div>
              <FL>Sales Order</FL>
              {!isNew && effectiveName ? (
                <RV>
                  {selectedSalesOrder
                    ? <button
                        type="button"
                        onClick={() => navigate(`/sales-orders/${encodeURIComponent(selectedSalesOrder)}`)}
                        className="text-blue-700 hover:underline font-medium"
                        title="Open sales order"
                      >
                        {selectedSalesOrder}
                      </button>
                    : (salesOrderCount != null && salesOrderCount > 0)
                      ? <button
                          type="button"
                          onClick={() => navigate(`/sales-orders?project=${encodeURIComponent(projectName!)}`)}
                          className="text-blue-700 hover:underline font-medium"
                          title="Open sales orders list"
                        >
                          {salesOrderCount} linked — open list
                        </button>
                      : <span className="text-gray-500 dark:text-gray-400">—</span>}
                </RV>
              ) : (
                <RV><span className="text-gray-400">—</span></RV>
              )}
            </div>
          </div>
        </CollapsibleSection>

        {/* ── 2. Notes ── */}
        <CollapsibleSection title="Notes" defaultOpen={true}>
          {editable
            ? <textarea rows={4} value={form.notes || ''} onChange={e => set('notes', e.target.value)}
                className="w-full px-3 py-2.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:outline-none resize-y"
                placeholder="Add notes…" />
            : <div className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap min-h-[40px] leading-relaxed">
                {formatProjectNotesForDisplay(form.notes) || <span className="text-gray-400 italic">No notes</span>}
              </div>}
        </CollapsibleSection>

        {/* ── Project updates: task-sourced (read-only) + project rows (editable) ── */}
        <CollapsibleSection
          title="Updates"
          icon={<FaBullhorn className="text-violet-500" size={13} />}
          defaultOpen={true}
          badge={
            !isNew && (mergedProgressDisplay.length > 0) ? (
              <span className="ml-2 text-[10px] font-mono bg-white/20 px-1.5 py-0.5 rounded">{mergedProgressDisplay.length}</span>
            ) : null
          }
        >
          <div className="rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
            <div
              className={`grid ${
                editable && !isNew ? 'grid-cols-[40px_1fr_8rem_1fr_36px]' : 'grid-cols-[40px_1fr_8rem_1fr]'
              } bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700`}
            >
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">No.</div>
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">Update</div>
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">Date</div>
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase">Task</div>
              {editable && !isNew && <div className="py-2 w-9" />}
            </div>
            {mergedProgressDisplay.length === 0 ? (
              <div className="py-8 text-center text-sm text-gray-400 italic">No updates yet.</div>
            ) : (
              <div className="divide-y divide-gray-100 dark:divide-gray-700">
                {mergedProgressDisplay.map((item, idx) => {
                  const { row, source, projectIndex } = item;
                  const canEditRow = editable && !isNew && source === 'project' && projectIndex !== undefined;
                  return (
                    <div
                      key={`${source}-${row.name || projectIndex}-${idx}`}
                      className={`grid ${
                        canEditRow ? 'grid-cols-[40px_1fr_8rem_1fr_36px]' : 'grid-cols-[40px_1fr_8rem_1fr]'
                      } items-center hover:bg-gray-50/80 dark:hover:bg-gray-800/40`}
                    >
                      <div className="px-3 py-2 text-xs text-gray-500 font-medium">{idx + 1}</div>
                      <div className="px-3 py-1.5 min-w-0">
                        {canEditRow ? (
                          <input
                            type="text"
                            value={row.update_ || ''}
                            onChange={e => {
                              const pi = projectIndex!;
                              setProjectOnlyUpdates(prev =>
                                prev.map((r, i) => (i === pi ? { ...r, update_: e.target.value } : r)),
                              );
                            }}
                            className={inputCls}
                            placeholder="Update…"
                          />
                        ) : (
                          <span className="text-sm text-gray-800 dark:text-gray-200">{row.update_ || '—'}</span>
                        )}
                      </div>
                      <div className="px-3 py-1.5">
                        {canEditRow ? (
                          <input
                            type="date"
                            value={row.date ? String(row.date).slice(0, 10) : ''}
                            onChange={e => {
                              const pi = projectIndex!;
                              setProjectOnlyUpdates(prev =>
                                prev.map((r, i) => (i === pi ? { ...r, date: e.target.value } : r)),
                              );
                            }}
                            className={inputCls}
                          />
                        ) : (
                          <span className="text-sm text-gray-700 dark:text-gray-300">
                            {row.date ? fmtDate(String(row.date).slice(0, 10)) : '—'}
                          </span>
                        )}
                      </div>
                      <div className="px-3 py-1.5 min-w-0">
                        {canEditRow ? (
                          <LinkField
                            label="Task"
                            hideLabel
                            doctype="Task"
                            value={row.task || ''}
                            onChange={v => {
                              const pi = projectIndex!;
                              setProjectOnlyUpdates(prev => prev.map((r, i) => (i === pi ? { ...r, task: v } : r)));
                            }}
                            placeholder="Task…"
                            filters={effectiveName ? { project: effectiveName } : undefined}
                            compact
                          />
                        ) : row.task ? (
                          <button
                            type="button"
                            onClick={() => navigate(`/projects/tasks/${encodeURIComponent(row.task!)}`)}
                            className="text-sm text-indigo-600 dark:text-indigo-400 hover:underline font-mono truncate max-w-full block text-left"
                          >
                            {row.task}
                          </button>
                        ) : (
                          <span className="text-sm text-gray-400">—</span>
                        )}
                      </div>
                      {canEditRow && (
                        <div className="flex justify-center">
                          <button
                            type="button"
                            onClick={() => {
                              const pi = projectIndex!;
                              setProjectOnlyUpdates(prev => prev.filter((_, i) => i !== pi));
                            }}
                            className="p-1.5 text-red-400 hover:text-red-600 rounded transition-colors"
                            title="Remove row"
                          >
                            <FaTrash size={11} />
                          </button>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
            {editable && !isNew && (
              <div className="border-t border-gray-200 dark:border-gray-700 px-3 py-2 bg-gray-50 dark:bg-gray-900/30">
                <button
                  type="button"
                  onClick={() => setProjectOnlyUpdates(prev => [...prev, {}])}
                  className="flex items-center gap-1.5 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 font-medium"
                >
                  <FaPlus size={10} /> Add Row
                </button>
              </div>
            )}
            {isNew && (
              <p className="text-[11px] text-gray-500 px-3 py-2 border-t border-gray-100 dark:border-gray-700">
                Save the project first to add updates and to load task-sourced rows.
              </p>
            )}
          </div>
        </CollapsibleSection>

        {/* ── Timesheet actuals (read-only; ERPNext maintains from submitted timesheets) ── */}
        {!isNew && project && (
          <CollapsibleSection title="Start and End Dates" icon={<FaClock className="text-sky-500" size={13} />} defaultOpen={true}>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5">
              <div>
                <FL>Actual Start Date (via Timesheet)</FL>
                <RV>{fmtDate((project as any).actual_start_date)}</RV>
              </div>
              <div>
                <FL>Actual End Date (via Timesheet)</FL>
                <RV>{fmtDate((project as any).actual_end_date)}</RV>
              </div>
              <div>
                <FL>Actual Time in Hours (via Timesheet)</FL>
                <RV>
                  {(project as any).actual_time != null && (project as any).actual_time !== ''
                    ? Number((project as any).actual_time).toLocaleString('en-US', { maximumFractionDigits: 2 })
                    : '—'}
                </RV>
              </div>
            </div>
          </CollapsibleSection>
        )}

        {/* ── 3. Costing and Billing (column order aligned with desk) ── */}
        <CollapsibleSection title="Costing and Billing" icon={<FaMoneyBillWave className="text-emerald-500" size={13} />} defaultOpen={true}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5">
            <div>
              <FL>Estimated Cost</FL>
              {editable
                ? <input
                    type="number"
                    min={0}
                    step="0.01"
                    value={form.estimated_costing === undefined || form.estimated_costing === null ? '' : form.estimated_costing}
                    onChange={e => {
                      const raw = e.target.value;
                      if (raw === '') {
                        set('estimated_costing', undefined);
                        return;
                      }
                      const n = parseFloat(raw);
                      set('estimated_costing', Number.isFinite(n) ? n : undefined);
                    }}
                    className={inputCls}
                  />
                : <RV>{fmtCurrency(project?.estimated_costing)}</RV>}
            </div>
            {!isNew ? (
              <div>
                <FL>Total Sales Amount (via Sales Order)</FL>
                <RV>{fmtCurrency(project?.total_sales_amount)}</RV>
              </div>
            ) : <div />}

            {!isNew ? (
              <div>
                <FL>Total Costing Amount (via Timesheet)</FL>
                <RV>{fmtCurrency(tsTotal.costing || project?.total_costing_amount)}</RV>
              </div>
            ) : <div />}
            {!isNew ? (
              <div>
                <FL>Total Billable Amount (via Timesheet)</FL>
                <RV>{fmtCurrency(tsTotal.billable || project?.total_billable_amount)}</RV>
              </div>
            ) : <div />}

            {!isNew ? (
              <div>
                <FL>Total Purchase Cost (via Purchase Invoice)</FL>
                <RV>{fmtCurrency(project?.total_purchase_cost)}</RV>
              </div>
            ) : <div />}
            {!isNew ? (
              <div>
                <FL>Total Billed Amount (via Sales Invoice)</FL>
                <RV>{fmtCurrency(project?.total_billed_amount)}</RV>
              </div>
            ) : <div />}

            <div>
              <FL required>Hospital</FL>
              {editable
                ? <LinkField label="Company" hideLabel doctype="Company" value={form.company || ''} onChange={v => set('company', v)} placeholder="Select company…" />
                : <RV>{form.company || '—'}</RV>}
            </div>
            {!isNew ? (
              <div>
                <FL>Total Consumed Material Cost (via Stock Entry)</FL>
                <RV>{fmtCurrency(project?.total_consumed_material_cost)}</RV>
              </div>
            ) : <div />}

            {isNew ? <div /> : <div className="hidden sm:block" aria-hidden />}
            {!isNew ? (
              <div>
                <FL>Default Cost Center</FL>
                <RV>{(project as any)?.cost_center || '—'}</RV>
              </div>
            ) : null}
          </div>
        </CollapsibleSection>

        {/* ── 4. Margin ── */}
        {!isNew && (
          <CollapsibleSection title="Margin" icon={<FaChartLine className="text-purple-500" size={13} />} defaultOpen={true}>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5">
              <div>
                <FL>Gross Margin</FL>
                <RV>{fmtCurrency(project?.gross_margin)}</RV>
              </div>
              <div>
                <FL>Gross Margin %</FL>
                <RV>
                  {(project?.per_gross_margin ?? 0).toLocaleString('en-US', { minimumFractionDigits: 3, maximumFractionDigits: 3 })}%
                </RV>
              </div>
            </div>
          </CollapsibleSection>
        )}

        {/* ── 5. Monitor Progress — hidden on saved projects unless collect progress is enabled (or user is editing) ── */}
        {showMonitorProgress && (
        <CollapsibleSection title="Monitor Progress" icon={<FaBell className="text-blue-500" size={13} />} defaultOpen={true}>
          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="collect_progress"
                checked={!!form.collect_progress}
                disabled={!editable}
                onChange={e => set('collect_progress', e.target.checked ? 1 : 0)}
                className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 cursor-pointer disabled:cursor-default"
              />
              <label htmlFor="collect_progress" className={`text-sm font-medium ${editable ? 'cursor-pointer' : 'cursor-default'} text-gray-700 dark:text-gray-300`}>
                Collect Progress
              </label>
            </div>
            {!!form.collect_progress && (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-5 pt-4 border-t border-gray-100 dark:border-gray-700">
                <div className="space-y-5">
                  <div>
                    <FL>Holiday List</FL>
                    {editable
                      ? <LinkField label="Holiday List" hideLabel doctype="Holiday List" value={(form as any).holiday_list || ''} onChange={v => set('holiday_list' as keyof Project, v)} placeholder="Select holiday list…" />
                      : <RV>{(form as any).holiday_list || '—'}</RV>}
                  </div>
                  <div>
                    <FL>Frequency To Collect Progress</FL>
                    {editable
                      ? <select value={form.frequency || 'Hourly'} onChange={e => set('frequency', e.target.value)} className={selectCls}>
                          <option value="Hourly">Hourly</option>
                          <option value="Twice Daily">Twice Daily</option>
                          <option value="Daily">Daily</option>
                          <option value="Weekly">Weekly</option>
                        </select>
                      : <RV>{form.frequency}</RV>}
                  </div>
                  {form.frequency === 'Hourly' && (
                    <>
                      <div>
                        <FL>From Time</FL>
                        {editable
                          ? <input type="time" value={fmtTime(form.from_time)} onChange={e => set('from_time', e.target.value)} className={inputCls} />
                          : <RV>{fmtTime(form.from_time) || '—'}</RV>}
                      </div>
                      <div>
                        <FL>To Time</FL>
                        {editable
                          ? <input type="time" value={fmtTime(form.to_time)} onChange={e => set('to_time', e.target.value)} className={inputCls} />
                          : <RV>{fmtTime(form.to_time) || '—'}</RV>}
                      </div>
                    </>
                  )}
                  {form.frequency === 'Twice Daily' && (
                    <>
                      <div>
                        <FL>First Email</FL>
                        {editable
                          ? <input type="time" value={fmtTime(form.first_email)} onChange={e => set('first_email', e.target.value)} className={inputCls} />
                          : <RV>{fmtTime(form.first_email) || '—'}</RV>}
                      </div>
                      <div>
                        <FL>Second Email</FL>
                        {editable
                          ? <input type="time" value={fmtTime(form.second_email)} onChange={e => set('second_email', e.target.value)} className={inputCls} />
                          : <RV>{fmtTime(form.second_email) || '—'}</RV>}
                      </div>
                    </>
                  )}
                  {form.frequency === 'Daily' && (
                    <div>
                      <FL>Daily Time to send</FL>
                      {editable
                        ? <input type="time" value={fmtTime(form.daily_time_to_send)} onChange={e => set('daily_time_to_send', e.target.value)} className={inputCls} />
                        : <RV>{fmtTime(form.daily_time_to_send) || '—'}</RV>}
                    </div>
                  )}
                  {form.frequency === 'Weekly' && (
                    <>
                      <div>
                        <FL>Day to Send</FL>
                        {editable
                          ? <select value={form.day_to_send || 'Monday'} onChange={e => set('day_to_send', e.target.value)} className={selectCls}>
                              {['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'].map(d => <option key={d} value={d}>{d}</option>)}
                            </select>
                          : <RV>{form.day_to_send}</RV>}
                      </div>
                      <div>
                        <FL>Weekly Time to send</FL>
                        {editable
                          ? <input type="time" value={fmtTime(form.weekly_time_to_send)} onChange={e => set('weekly_time_to_send', e.target.value)} className={inputCls} />
                          : <RV>{fmtTime(form.weekly_time_to_send) || '—'}</RV>}
                      </div>
                    </>
                  )}
                </div>
                <div className="space-y-5">
                  <div>
                    <FL required>Subject</FL>
                    {editable
                      ? <input type="text" value={(form as any).subject || ''} onChange={e => set('subject' as keyof Project, e.target.value)} className={inputCls} placeholder="Email subject…" />
                      : <RV>{(form as any).subject || '—'}</RV>}
                  </div>
                  <div>
                    <FL required>Message</FL>
                    {editable
                      ? <textarea rows={5} value={(form as any).message || ''} onChange={e => set('message' as keyof Project, e.target.value)} className={`${inputCls} resize-y`} placeholder="Message to project users…" />
                      : <div className="px-3 py-2.5 text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-900/30 rounded-lg min-h-[38px] border border-gray-100 dark:border-gray-700/50 whitespace-pre-wrap">{(form as any).message || '—'}</div>}
                    <p className="text-xs text-gray-500 dark:text-gray-400 mt-1.5">Message will be sent to the users to get their status on the Project</p>
                  </div>
                </div>
              </div>
            )}
          </div>
        </CollapsibleSection>
        )}

        {/* ── Activity Log ── */}
        {!isNew && (
          <ActivityLog
            doctype="Project"
            docname={projectName || ''}
            creationDate={project?.creation}
            createdBy={project?.owner}
            compact={false}
            initialVisible={5}
            collapsible
            startCollapsed
          />
        )}

      </div>
    </div>
  );
};

export default ProjectDetail;
