"use client";

import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { apiDelete, apiGet, apiPatch, apiPost } from "@/lib/api";
import type { CRMActivity, CRMActivityType, CRMEntityType, User } from "@/types";

function typeLabel(type: CRMActivityType | string) {
  return type.replaceAll("_", " ").toLowerCase().replace(/^./, (c) => c.toUpperCase());
}

function dateLabel(value?: string | null) {
  return value ? new Date(value).toLocaleString() : "-";
}

function createdByLabel(activity: CRMActivity) {
  const name = [activity.createdByUser?.firstName, activity.createdByUser?.lastName].filter(Boolean).join(" ").trim();
  return name || activity.createdByUser?.email || "System";
}

function editorLabel(activity: CRMActivity) {
  const name = [activity.editedByUser?.firstName, activity.editedByUser?.lastName].filter(Boolean).join(" ").trim();
  return name || activity.editedByUser?.email || "System";
}

function getDueState(activity: CRMActivity) {
  if (!activity.dueAt || activity.completedAt) return "none" as const;

  const due = new Date(activity.dueAt);
  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const tomorrowStart = new Date(todayStart);
  tomorrowStart.setDate(todayStart.getDate() + 1);
  const nextWeek = new Date(todayStart);
  nextWeek.setDate(todayStart.getDate() + 7);

  if (due < now) return "overdue" as const;
  if (due >= todayStart && due < tomorrowStart) return "today" as const;
  if (due >= tomorrowStart && due < nextWeek) return "soon" as const;
  return "future" as const;
}

function sortActivities(activities: CRMActivity[]) {
  const priority = { overdue: 0, today: 1, soon: 2, future: 3, none: 4 } as const;

  return [...activities].sort((a, b) => {
    if (!!a.completedAt !== !!b.completedAt) return a.completedAt ? 1 : -1;

    const aState = getDueState(a);
    const bState = getDueState(b);
    if (priority[aState] !== priority[bState]) return priority[aState] - priority[bState];

    if (a.dueAt && b.dueAt) return new Date(a.dueAt).getTime() - new Date(b.dueAt).getTime();
    if (a.dueAt) return -1;
    if (b.dueAt) return 1;
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
  });
}

function metricCard(label: string, value: number, tone: "red" | "amber" | "blue" | "slate") {
  const tones = {
    red: "border-red-200 bg-red-50 text-red-800",
    amber: "border-amber-200 bg-amber-50 text-amber-800",
    blue: "border-blue-200 bg-blue-50 text-blue-800",
    slate: "border-slate-200 bg-slate-50 text-slate-800",
  } as const;

  return (
    <div className={`rounded-xl border px-4 py-3 ${tones[tone]}`}>
      <div className="text-xs font-semibold uppercase tracking-wide">{label}</div>
      <div className="mt-1 text-lg font-semibold">{value}</div>
    </div>
  );
}

function toLocalDateTimeInputValue(date: Date) {
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
  return local.toISOString().slice(0, 16);
}

function buildPresetDate(daysToAdd: number, hour: number, minute = 0) {
  const date = new Date();
  date.setSeconds(0, 0);
  date.setHours(hour, minute, 0, 0);
  date.setDate(date.getDate() + daysToAdd);
  return toLocalDateTimeInputValue(date);
}

function nextWeekdayDate(hour: number, minute = 0) {
  const date = new Date();
  date.setSeconds(0, 0);
  date.setHours(hour, minute, 0, 0);
  const day = date.getDay();
  const offset = day === 5 ? 3 : day === 6 ? 2 : 1;
  date.setDate(date.getDate() + offset);
  return toLocalDateTimeInputValue(date);
}

const QUICK_PRESETS: Array<{
  label: string;
  activityType: CRMActivityType;
  subject: string;
  content?: string;
  dueAt?: string;
}> = [
  { label: "Quick note", activityType: "NOTE", subject: "Relationship note", content: "" },
  { label: "Log call", activityType: "CALL", subject: "Outbound call", content: "Call outcome:\nNext step:" },
  { label: "Log email", activityType: "EMAIL", subject: "Email sent", content: "Email summary:\nRequested response by:" },
  { label: "Follow up today", activityType: "TASK", subject: "Follow up today", content: "Follow-up objective:", dueAt: buildPresetDate(0, 17, 0) },
  { label: "Follow up tomorrow", activityType: "TASK", subject: "Follow up tomorrow", content: "Follow-up objective:", dueAt: nextWeekdayDate(9, 0) },
  { label: "Schedule meeting", activityType: "MEETING", subject: "Relationship meeting", content: "Agenda:\nAttendees:", dueAt: buildPresetDate(7, 10, 0) },
];

type TimelineStatusFilter = "ALL" | "OPEN" | "COMPLETED" | "OVERDUE" | "DUE_TODAY" | "UPCOMING" | "NO_DUE_DATE";
type TimelineOperatorFilter = "ALL" | "MINE" | string;

const GOVERNED_TYPES = new Set(["NOTE", "CALL", "EMAIL", "MEETING", "TASK", "DOCUMENT", "OTHER"]);

function canEditActivity(activity: CRMActivity, viewer: User | null, canManage: boolean) {
  if (!canManage || !viewer) return false;
  if (viewer.role === "ORG_ADMIN") return true;
  return activity.createdByUser?.id === viewer.id && GOVERNED_TYPES.has(activity.activityType);
}

function canDeleteActivity(activity: CRMActivity, viewer: User | null, canManage: boolean) {
  if (!canManage || !viewer) return false;
  if (viewer.role === "ORG_ADMIN") return true;
  return activity.createdByUser?.id === viewer.id && GOVERNED_TYPES.has(activity.activityType);
}

function QuickPresetButton({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <button type="button" onClick={onClick} className="rounded-full border bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
      {label}
    </button>
  );
}



type IntelligenceLoggedMeta = {
  mode?: string;
  stage?: string;
  followUpDate?: string;
  entityName?: string;
  lane?: string;
  objective?: string;
  sequenceLabel?: string;
  currentSequenceStepLabel?: string;
};

const INTELLIGENCE_LOG_START = "[INTELLIGENCE_LOG]";
const INTELLIGENCE_LOG_END = "[/INTELLIGENCE_LOG]";

function buildIntelligenceLogMeta(summary: NonNullable<ReturnType<typeof getKickoffSummaryShape>>) {
  const entries = [
    ["mode", summary.mode],
    ["stage", summary.stage],
    ["followUpDate", summary.followUpDate],
    ["entityName", summary.entityName],
    ["lane", summary.lane],
    ["objective", summary.objective],
    ["sequenceLabel", summary.sequenceLabel],
    ["currentSequenceStepLabel", summary.currentSequenceStepLabel],
  ].filter((entry): entry is [string, string] => Boolean(entry[1]));
  return `${INTELLIGENCE_LOG_START}\n${entries.map(([key, value]) => `${key}: ${value}`).join("\\n")}\n${INTELLIGENCE_LOG_END}`;
}

function splitIntelligenceLog(content?: string | null) {
  const value = content || "";
  const start = value.indexOf(INTELLIGENCE_LOG_START);
  const end = value.indexOf(INTELLIGENCE_LOG_END);
  if (start === -1 || end === -1 || end < start) {
    return { visibleContent: value.trim(), meta: null as IntelligenceLoggedMeta | null };
  }
  const before = value.slice(0, start).trim();
  const raw = value.slice(start + INTELLIGENCE_LOG_START.length, end).trim();
  const meta: IntelligenceLoggedMeta = {};
  for (const line of raw.split(/\n+|\\n+/)) {
    const idx = line.indexOf(":");
    if (idx === -1) continue;
    const key = line.slice(0, idx).trim();
    const val = line.slice(idx + 1).trim();
    if (!val) continue;
    if (key in { mode: 1, stage: 1, followUpDate: 1, entityName: 1, lane: 1, objective: 1, sequenceLabel: 1, currentSequenceStepLabel: 1 }) {
      (meta as any)[key] = val;
    }
  }
  return { visibleContent: before, meta };
}

function getKickoffSummaryShape(searchParams: ReturnType<typeof useSearchParams>) {
  if (searchParams.get("activityKickoff") !== "intelligence") return null;
  const activityType = (searchParams.get("activityType") || "NOTE").trim().toUpperCase();
  const sequenceSteps = (searchParams.get("activitySequence") || "").split(" || ").map((step) => step.trim()).filter(Boolean);
  const rawStepIndex = Number(searchParams.get("activitySequenceStepIndex") || "0");
  const sequenceStepIndex = Number.isFinite(rawStepIndex) && rawStepIndex >= 0 ? rawStepIndex : 0;
  return {
    mode: searchParams.get("activityMode") || "market-search",
    lane: searchParams.get("activityLane") || "-",
    objective: searchParams.get("activityObjective") || "Confirm the next operational move.",
    contactHint: searchParams.get("activityContactHint") || "-",
    followUpDate: searchParams.get("activityFollowUpDate") || "-",
    stage: searchParams.get("activityStage") || "-",
    entityName: searchParams.get("activityEntityName") || "this record",
    subject: searchParams.get("activitySubject") || "",
    details: searchParams.get("activityContent") || "",
    dueAt: searchParams.get("activityDueAt") || "",
    activityType,
    sequenceLabel: searchParams.get("activitySequenceLabel") || "Recommended sequence",
    sequenceSteps,
    currentSequenceStepIndex: sequenceStepIndex,
    currentSequenceStepLabel: searchParams.get("activitySequenceStepLabel") || sequenceSteps[sequenceStepIndex] || "",
  };
}

function matchesStatusFilter(activity: CRMActivity, filter: TimelineStatusFilter) {
  const dueState = getDueState(activity);

  switch (filter) {
    case "OPEN":
      return !activity.completedAt;
    case "COMPLETED":
      return !!activity.completedAt;
    case "OVERDUE":
      return !activity.completedAt && dueState === "overdue";
    case "DUE_TODAY":
      return !activity.completedAt && dueState === "today";
    case "UPCOMING":
      return !activity.completedAt && (dueState === "soon" || dueState === "future");
    case "NO_DUE_DATE":
      return !activity.dueAt;
    default:
      return true;
  }
}

export function CRMActivityTimeline({ entityType, entityId, canManage = true }: { entityType: CRMEntityType; entityId: string; canManage?: boolean }) {
  const searchParams = useSearchParams();
  const [activities, setActivities] = useState<CRMActivity[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activityType, setActivityType] = useState<CRMActivityType>("NOTE");
  const [subject, setSubject] = useState("");
  const [content, setContent] = useState("");
  const [dueAt, setDueAt] = useState("");
  const [viewer, setViewer] = useState<User | null>(null);
  const [typeFilter, setTypeFilter] = useState<"ALL" | CRMActivityType>("ALL");
  const [statusFilter, setStatusFilter] = useState<TimelineStatusFilter>("ALL");
  const [operatorFilter, setOperatorFilter] = useState<TimelineOperatorFilter>("ALL");
  const [searchText, setSearchText] = useState("");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editSubject, setEditSubject] = useState("");
  const [editContent, setEditContent] = useState("");
  const [editDueAt, setEditDueAt] = useState("");
  const [editReason, setEditReason] = useState("");
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [deletionReason, setDeletionReason] = useState("");
  const [actionBusyId, setActionBusyId] = useState<string | null>(null);
  const kickoffKey = useMemo(() => {
    return [
      searchParams.get("activityKickoff") || "",
      searchParams.get("activityType") || "",
      searchParams.get("activitySubject") || "",
      searchParams.get("activityEntityType") || "",
      searchParams.get("activityEntityName") || "",
      searchParams.get("activityFollowUpDate") || "",
    ].join("|");
  }, [searchParams]);
  const [appliedKickoffKey, setAppliedKickoffKey] = useState("");
  const kickoffSummary = useMemo(() => getKickoffSummaryShape(searchParams), [searchParams]);

  async function loadActivities() {
    try {
      setLoading(true);
      setError(null);
      const data = await apiGet<{ activities: CRMActivity[] }>(`/api/crm-activities?entityType=${entityType}&entityId=${entityId}`);
      setActivities(data.activities ?? []);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load CRM activities");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadActivities();
  }, [entityType, entityId]);

  useEffect(() => {
    apiGet<{ user: User }>("/api/auth/me")
      .then((data) => setViewer(data.user))
      .catch(() => setViewer(null));
  }, []);

  useEffect(() => {
    const kickoff = searchParams.get("activityKickoff");
    if (kickoff !== "intelligence") return;
    const kickoffEntityType = (searchParams.get("activityEntityType") || "").trim().toUpperCase();
    if (kickoffEntityType && kickoffEntityType !== entityType) return;
    if (!kickoffKey || kickoffKey === appliedKickoffKey) return;

    const incomingType = (searchParams.get("activityType") || "NOTE").trim().toUpperCase();
    const allowedTypes = new Set(["NOTE", "CALL", "EMAIL", "MEETING", "TASK", "STATUS_CHANGE", "DOCUMENT", "OTHER"]);
    if (allowedTypes.has(incomingType)) setActivityType(incomingType as CRMActivityType);
    setSubject(searchParams.get("activitySubject") || "");
    setContent(searchParams.get("activityContent") || "");
    setDueAt(searchParams.get("activityDueAt") || "");
    setAppliedKickoffKey(kickoffKey);
  }, [appliedKickoffKey, entityType, kickoffKey, searchParams]);

  function applyKickoffSummary() {
    if (!kickoffSummary) return;
    const allowedTypes = new Set(["NOTE", "CALL", "EMAIL", "MEETING", "TASK", "STATUS_CHANGE", "DOCUMENT", "OTHER"]);
    if (allowedTypes.has(kickoffSummary.activityType)) setActivityType(kickoffSummary.activityType as CRMActivityType);
    setSubject(kickoffSummary.subject || "");
    setContent(kickoffSummary.details || "");
    setDueAt(kickoffSummary.dueAt || "");
  }

  function applyKickoffSequenceStep(stepIndex: number) {
    if (!kickoffSummary) return;
    const step = kickoffSummary.sequenceSteps[stepIndex];
    if (!step) return;
    const nextType = stepIndex === 0
      ? kickoffSummary.activityType
      : stepIndex === 1
        ? (kickoffSummary.activityType === "CALL" ? "EMAIL" : kickoffSummary.activityType === "EMAIL" ? "CALL" : "TASK")
        : "TASK";
    const allowedTypes = new Set(["NOTE", "CALL", "EMAIL", "MEETING", "TASK", "STATUS_CHANGE", "DOCUMENT", "OTHER"]);
    if (allowedTypes.has(nextType)) setActivityType(nextType as CRMActivityType);
    const baseSubject = `${kickoffSummary.entityName} · sequence step ${stepIndex + 1}`;
    setSubject(baseSubject);
    setContent([
      `Sequence plan: ${kickoffSummary.sequenceLabel}`,
      `Current step: ${step}`,
      `Objective: ${kickoffSummary.objective}`,
      kickoffSummary.lane && kickoffSummary.lane !== "-" ? `Lane / service: ${kickoffSummary.lane}` : "",
      kickoffSummary.contactHint && kickoffSummary.contactHint !== "-" ? `Contact hint: ${kickoffSummary.contactHint}` : "",
      kickoffSummary.followUpDate && kickoffSummary.followUpDate !== "-" ? `Target follow-up date: ${kickoffSummary.followUpDate}` : "",
    ].filter(Boolean).join("\n\n"));
    setDueAt(kickoffSummary.dueAt || "");
  }

  function applyPreset(preset: typeof QUICK_PRESETS[number]) {
    setActivityType(preset.activityType);
    setSubject(preset.subject);
    setContent(preset.content ?? "");
    setDueAt(preset.dueAt ?? "");
  }

  function clearComposer() {
    setSubject("");
    setContent("");
    setDueAt("");
    setActivityType("NOTE");
  }

  function resetFilters() {
    setTypeFilter("ALL");
    setStatusFilter("ALL");
    setOperatorFilter("ALL");
    setSearchText("");
  }

  function startEditing(activity: CRMActivity) {
    setEditingId(activity.id);
    setEditSubject(activity.subject ?? "");
    setEditContent(activity.content ?? "");
    setEditDueAt(activity.dueAt ? toLocalDateTimeInputValue(new Date(activity.dueAt)) : "");
    setEditReason("");
    setDeletingId(null);
    setDeletionReason("");
  }

  function cancelEditing() {
    setEditingId(null);
    setEditSubject("");
    setEditContent("");
    setEditDueAt("");
    setEditReason("");
  }

  function startDeleting(activity: CRMActivity) {
    setDeletingId(activity.id);
    setDeletionReason("");
    setEditingId(null);
  }

  function cancelDeleting() {
    setDeletingId(null);
    setDeletionReason("");
  }

  async function createActivity() {
    try {
      setSaving(true);
      setError(null);
      const contentWithContinuity = kickoffSummary
        ? [content || "", buildIntelligenceLogMeta(kickoffSummary)].filter(Boolean).join("\n\n")
        : content || undefined;
      await apiPost("/api/crm-activities", {
        entityType,
        entityId,
        activityType,
        subject: subject || undefined,
        content: contentWithContinuity,
        dueAt: dueAt || undefined,
      });
      clearComposer();
      await loadActivities();
    } catch (err: any) {
      setError(err?.message ?? "Failed to create CRM activity");
    } finally {
      setSaving(false);
    }
  }

  async function markComplete(id: string) {
    try {
      setActionBusyId(id);
      setError(null);
      await apiPost(`/api/crm-activities/${id}/complete`, {});
      await loadActivities();
    } catch (err: any) {
      setError(err?.message ?? "Failed to complete CRM activity");
    } finally {
      setActionBusyId(null);
    }
  }

  async function saveEdit(id: string) {
    try {
      setActionBusyId(id);
      setError(null);
      await apiPatch(`/api/crm-activities/${id}`, {
        subject: editSubject || undefined,
        content: editContent || undefined,
        dueAt: editDueAt || null,
        editReason: editReason || undefined,
      });
      cancelEditing();
      await loadActivities();
    } catch (err: any) {
      setError(err?.message ?? "Failed to update CRM activity");
    } finally {
      setActionBusyId(null);
    }
  }

  async function deleteActivity(id: string) {
    try {
      setActionBusyId(id);
      setError(null);
      await apiDelete(`/api/crm-activities/${id}`, {
        deletionReason: deletionReason || undefined,
      });
      cancelDeleting();
      await loadActivities();
    } catch (err: any) {
      setError(err?.message ?? "Failed to delete CRM activity");
    } finally {
      setActionBusyId(null);
    }
  }

  const sortedActivities = useMemo(() => sortActivities(activities), [activities]);

  const operatorOptions = useMemo(() => {
    const map = new Map<string, string>();
    for (const activity of activities) {
      if (activity.createdByUser?.id) {
        map.set(activity.createdByUser.id, createdByLabel(activity));
      }
    }
    return Array.from(map.entries()).map(([id, label]) => ({ id, label })).sort((a, b) => a.label.localeCompare(b.label));
  }, [activities]);

  const visibleActivities = useMemo(() => {
    const normalizedSearch = searchText.trim().toLowerCase();

    return sortedActivities.filter((activity) => {
      if (typeFilter !== "ALL" && activity.activityType !== typeFilter) return false;
      if (!matchesStatusFilter(activity, statusFilter)) return false;

      if (operatorFilter === "MINE") {
        if (!viewer?.id || activity.createdByUser?.id !== viewer.id) return false;
      } else if (operatorFilter !== "ALL") {
        if (activity.createdByUser?.id !== operatorFilter) return false;
      }

      if (!normalizedSearch) return true;
      const haystack = [activity.subject, activity.content, createdByLabel(activity), typeLabel(activity.activityType), activity.editReason].filter(Boolean).join(" ").toLowerCase();
      return haystack.includes(normalizedSearch);
    });
  }, [operatorFilter, searchText, sortedActivities, statusFilter, typeFilter, viewer?.id]);

  const stats = useMemo(() => {
    let overdue = 0;
    let dueToday = 0;
    let open = 0;

    for (const activity of activities) {
      if (activity.completedAt) continue;
      open += 1;
      const dueState = getDueState(activity);
      if (dueState === "overdue") overdue += 1;
      if (dueState === "today") dueToday += 1;
    }

    return { visible: visibleActivities.length, open, dueToday, overdue };
  }, [activities, visibleActivities.length]);

  const filterSummary = useMemo(() => {
    if (!activities.length) return "No CRM timeline entries yet.";
    if (visibleActivities.length === activities.length) return `Showing all ${activities.length} timeline entries.`;
    return `Showing ${visibleActivities.length} of ${activities.length} timeline entries.`;
  }, [activities.length, visibleActivities.length]);

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <h2 className="text-base font-semibold">CRM activity timeline</h2>
          <p className="mt-1 text-sm text-gray-500">Track follow-up ownership, relationship history, and governed timeline changes.</p>
        </div>
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
          {metricCard("Visible entries", stats.visible, "slate")}
          {metricCard("Open follow-ups", stats.open, "blue")}
          {metricCard("Due today", stats.dueToday, "amber")}
          {metricCard("Overdue", stats.overdue, "red")}
        </div>
      </div>

      <div className="mt-5 rounded-2xl border bg-gray-50 p-4">
        <div className="grid gap-3 lg:grid-cols-[minmax(0,180px)_minmax(0,180px)_minmax(0,220px)_minmax(0,1fr)_auto] lg:items-end">
          <label className="space-y-1 text-sm">
            <span className="font-medium text-gray-700">Activity type</span>
            <select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value as "ALL" | CRMActivityType)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm">
              <option value="ALL">All activity types</option>
              <option value="NOTE">Note</option>
              <option value="CALL">Call</option>
              <option value="EMAIL">Email</option>
              <option value="MEETING">Meeting</option>
              <option value="TASK">Task</option>
              <option value="STATUS_CHANGE">Status Change</option>
              <option value="DOCUMENT">Document</option>
              <option value="OTHER">Other</option>
            </select>
          </label>
          <label className="space-y-1 text-sm">
            <span className="font-medium text-gray-700">Status</span>
            <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value as TimelineStatusFilter)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm">
              <option value="ALL">All statuses</option>
              <option value="OPEN">Open only</option>
              <option value="COMPLETED">Completed only</option>
              <option value="OVERDUE">Overdue</option>
              <option value="DUE_TODAY">Due today</option>
              <option value="UPCOMING">Upcoming</option>
              <option value="NO_DUE_DATE">No due date</option>
            </select>
          </label>
          <label className="space-y-1 text-sm lg:min-w-52">
            <span className="font-medium text-gray-700">Operator</span>
            <select value={operatorFilter} onChange={(e) => setOperatorFilter(e.target.value as TimelineOperatorFilter)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm">
              <option value="ALL">All operators</option>
              {viewer?.id ? <option value="MINE">My activity only</option> : null}
              {operatorOptions.map((operator) => (
                <option key={operator.id} value={operator.id}>{operator.label}</option>
              ))}
            </select>
          </label>
          <label className="space-y-1 text-sm lg:flex-1">
            <span className="font-medium text-gray-700">Search timeline</span>
            <input value={searchText} onChange={(e) => setSearchText(e.target.value)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" placeholder="Search subject, details, type, or operator" />
          </label>
          <button type="button" onClick={resetFilters} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">Reset filters</button>
        </div>
        <div className="mt-3 text-xs text-gray-500">{filterSummary}</div>
      </div>

      {canManage ? (
        <div className="mt-5 space-y-3 rounded-2xl border bg-gray-50 p-4">
          {kickoffSummary ? (
            <div className="rounded-xl border border-blue-200 bg-blue-50 p-3 text-sm text-slate-700">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                <div>
                  <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-700">Lead follow-up</div>
                  <div className="mt-1 font-semibold text-slate-900">This activity was started from lead follow-up.</div>
                  <div className="mt-1">You can adjust the activity type, details, and due date before saving, or reapply the recommended draft if you want to reset the composer.</div>
                  <div className="mt-3 flex flex-wrap gap-2 text-xs">
                    <span className="rounded-full bg-white px-2.5 py-1 font-medium text-blue-900">Mode: {kickoffSummary.mode.replaceAll("-", " ")}</span>
                    <span className="rounded-full bg-white px-2.5 py-1 font-medium text-blue-900">Stage: {kickoffSummary.stage}</span>
                    <span className="rounded-full bg-white px-2.5 py-1 font-medium text-blue-900">Follow up by {kickoffSummary.followUpDate}</span>
                    <span className="rounded-full bg-white px-2.5 py-1 font-medium text-blue-900">Lead / record: {kickoffSummary.entityName}</span>
                    {kickoffSummary.currentSequenceStepLabel ? <span className="rounded-full bg-white px-2.5 py-1 font-medium text-blue-900">Current sequence step: {kickoffSummary.currentSequenceStepIndex + 1}</span> : null}
                  </div>
                  <div className="mt-3 grid gap-3 md:grid-cols-4">
                    <div className="rounded-xl border bg-white p-3">
                      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Lane / service</div>
                      <div className="mt-1 text-sm text-slate-800">{kickoffSummary.lane}</div>
                    </div>
                    <div className="rounded-xl border bg-white p-3">
                      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Contact hint</div>
                      <div className="mt-1 text-sm text-slate-800">{kickoffSummary.contactHint}</div>
                    </div>
                    <div className="rounded-xl border bg-white p-3">
                      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Objective</div>
                      <div className="mt-1 text-sm text-slate-800">{kickoffSummary.objective}</div>
                    </div>
                    <div className="rounded-xl border bg-white p-3">
                      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">{kickoffSummary.sequenceLabel}</div>
                      <ul className="mt-1 space-y-1 text-sm text-slate-800">
                        {kickoffSummary.sequenceSteps.length ? kickoffSummary.sequenceSteps.map((step, index) => <li key={step}><span className={index === kickoffSummary.currentSequenceStepIndex ? "font-semibold text-slate-900" : undefined}>• {step}</span></li>) : <li>Use the suggested first touch, then work the backup move if needed.</li>}
                      </ul>
                      {kickoffSummary.currentSequenceStepLabel ? <div className="mt-2 rounded-lg bg-blue-50 px-2 py-2 text-xs font-medium text-blue-900">Active step: {kickoffSummary.currentSequenceStepLabel}</div> : null}
                    </div>
                  </div>
                </div>
                <div className="flex flex-wrap gap-2">
                  <button type="button" onClick={applyKickoffSummary} className="rounded-xl border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-900 hover:bg-blue-100">Reapply kickoff draft</button>
                  {kickoffSummary.sequenceSteps.length ? kickoffSummary.sequenceSteps.map((step, index) => (
                    <button key={`apply-step-${index}`} type="button" onClick={() => applyKickoffSequenceStep(index)} className={`rounded-xl border px-3 py-2 text-sm font-medium ${index === kickoffSummary.currentSequenceStepIndex ? "border-blue-300 bg-blue-900 text-white" : "border-blue-200 bg-white text-blue-900 hover:bg-blue-100"}`}>
                      Apply step {index + 1}
                    </button>
                  )) : null}
                  <button type="button" onClick={clearComposer} className="rounded-xl border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-900 hover:bg-blue-100">Clear composer</button>
                </div>
              </div>
            </div>
          ) : null}
          <div>
            <div className="text-xs font-semibold uppercase tracking-wide text-gray-500">Quick add</div>
            <div className="mt-3 flex flex-wrap gap-2">
              {QUICK_PRESETS.map((preset) => (
                <div key={preset.label}><QuickPresetButton label={preset.label} onClick={() => applyPreset(preset)} /></div>
              ))}
              <button type="button" onClick={clearComposer} className="rounded-full border border-dashed bg-white px-3 py-2 text-sm font-medium text-gray-600 hover:bg-gray-50">Clear</button>
            </div>
          </div>

          <div className="grid gap-3 md:grid-cols-3">
            <label className="space-y-1 text-sm">
              <span className="font-medium text-gray-700">Activity type</span>
              <select value={activityType} onChange={(e) => setActivityType(e.target.value as CRMActivityType)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm">
                <option value="NOTE">Note</option>
                <option value="CALL">Call</option>
                <option value="EMAIL">Email</option>
                <option value="MEETING">Meeting</option>
                <option value="TASK">Task</option>
                <option value="STATUS_CHANGE">Status Change</option>
                <option value="DOCUMENT">Document</option>
                <option value="OTHER">Other</option>
              </select>
            </label>
            <label className="space-y-1 text-sm md:col-span-2">
              <span className="font-medium text-gray-700">Subject</span>
              <input value={subject} onChange={(e) => setSubject(e.target.value)} onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); if (!saving) void createActivity(); } }} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" placeholder="Short activity subject" />
            </label>
          </div>
          <label className="block space-y-1 text-sm">
            <span className="font-medium text-gray-700">Details</span>
            <textarea value={content} onChange={(e) => setContent(e.target.value)} onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); if (!saving) void createActivity(); } }} rows={3} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" placeholder="What happened, what was discussed, or what needs follow-up?" />
          </label>
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
            <div className="flex flex-col gap-2 sm:w-80">
              <label className="space-y-1 text-sm">
                <span className="font-medium text-gray-700">Due date</span>
                <input type="datetime-local" value={dueAt} onChange={(e) => setDueAt(e.target.value)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" />
              </label>
              <div className="flex flex-wrap gap-2">
                <button type="button" onClick={() => setDueAt(buildPresetDate(0, 17, 0))} className="rounded-lg border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">Today 5pm</button>
                <button type="button" onClick={() => setDueAt(nextWeekdayDate(9, 0))} className="rounded-lg border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">Next business day 9am</button>
                <button type="button" onClick={() => setDueAt(buildPresetDate(7, 10, 0))} className="rounded-lg border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">In 1 week</button>
              </div>
            </div>
            <div className="flex flex-col items-start gap-2 sm:items-end">
              <div className="text-xs text-gray-500">Press Ctrl/Cmd + Enter to save faster.</div>
              <button type="button" onClick={createActivity} disabled={saving} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:opacity-60">{saving ? "Saving..." : "Add activity"}</button>
            </div>
          </div>
        </div>
      ) : null}

      {error ? <div className="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div> : null}

      <div className="mt-5 space-y-3">
        {loading ? <div className="text-sm text-gray-500">Loading timeline...</div> : null}
        {!loading && !visibleActivities.length ? <div className="rounded-xl border border-dashed px-4 py-5 text-sm text-gray-500">No timeline entries match the current filters.</div> : null}
        {visibleActivities.map((activity) => {
          const dueState = getDueState(activity);
          const { visibleContent, meta: intelligenceLoggedMeta } = splitIntelligenceLog(activity.content);
          const cardTone = activity.completedAt
            ? "border-green-200 bg-green-50/40"
            : dueState === "overdue"
              ? "border-red-300 bg-red-50"
              : dueState === "today"
                ? "border-amber-300 bg-amber-50"
                : activity.activityType === "STATUS_CHANGE"
                  ? "border-violet-200 bg-violet-50/60"
                  : "border-gray-200 bg-white";
          const isEditing = editingId === activity.id;
          const isDeleting = deletingId === activity.id;
          const canEdit = canEditActivity(activity, viewer, canManage);
          const canDelete = canDeleteActivity(activity, viewer, canManage);

          return (
            <div key={activity.id} className={`rounded-xl border px-4 py-4 ${cardTone}`}>
              <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                <div className="flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    {activity.activityType === "STATUS_CHANGE" ? <span className="rounded-full bg-violet-100 px-2.5 py-1 text-xs font-semibold text-violet-700">{typeLabel(activity.activityType)}</span> : <span className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-semibold text-gray-700">{typeLabel(activity.activityType)}</span>}
                    {activity.completedAt ? <span className="rounded-full bg-green-100 px-2.5 py-1 text-xs font-semibold text-green-700">Completed</span> : null}
                    {dueState === "overdue" ? <span className="rounded-full bg-red-100 px-2.5 py-1 text-xs font-semibold text-red-700">Overdue</span> : null}
                    {dueState === "today" ? <span className="rounded-full bg-amber-100 px-2.5 py-1 text-xs font-semibold text-amber-700">Due today</span> : null}
                    {activity.dueAt && !activity.completedAt && dueState !== "overdue" && dueState !== "today" ? <span className="rounded-full bg-blue-100 px-2.5 py-1 text-xs font-semibold text-blue-700">Due {dateLabel(activity.dueAt)}</span> : null}
                    <span className="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-700">Operator: {createdByLabel(activity)}</span>
                    {activity.editedAt ? <span className="rounded-full bg-amber-100 px-2.5 py-1 text-xs font-medium text-amber-800">Edited</span> : null}
                    {intelligenceLoggedMeta ? <span className="rounded-full bg-blue-100 px-2.5 py-1 text-xs font-medium text-blue-800">Lead follow-up saved</span> : null}
                  </div>

                  {!isEditing ? (
                    <>
                      <div className="mt-2 text-sm font-medium text-gray-900">{activity.subject || "Untitled activity"}</div>
                      {intelligenceLoggedMeta ? (
                        <div className="mt-3 rounded-lg border border-blue-200 bg-blue-50 px-3 py-3 text-xs text-blue-900">
                          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-blue-700">Lead follow-up details</div>
                          <div className="mt-2 flex flex-wrap gap-2">
                            {intelligenceLoggedMeta.mode ? <span className="rounded-full bg-white px-2.5 py-1 font-medium">Mode: {intelligenceLoggedMeta.mode.replaceAll("-", " ")}</span> : null}
                            {intelligenceLoggedMeta.stage ? <span className="rounded-full bg-white px-2.5 py-1 font-medium">Stage: {intelligenceLoggedMeta.stage}</span> : null}
                            {intelligenceLoggedMeta.followUpDate ? <span className="rounded-full bg-white px-2.5 py-1 font-medium">Follow up by {intelligenceLoggedMeta.followUpDate}</span> : null}
                            {intelligenceLoggedMeta.currentSequenceStepLabel ? <span className="rounded-full bg-white px-2.5 py-1 font-medium">Step: {intelligenceLoggedMeta.currentSequenceStepLabel}</span> : null}
                          </div>
                          <div className="mt-2 grid gap-2 md:grid-cols-3">
                            {intelligenceLoggedMeta.entityName ? <div className="rounded-lg border bg-white px-3 py-2"><div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">Lead / record</div><div className="mt-1 text-xs text-slate-800">{intelligenceLoggedMeta.entityName}</div></div> : null}
                            {intelligenceLoggedMeta.lane ? <div className="rounded-lg border bg-white px-3 py-2"><div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">Lane / service</div><div className="mt-1 text-xs text-slate-800">{intelligenceLoggedMeta.lane}</div></div> : null}
                            {intelligenceLoggedMeta.objective ? <div className="rounded-lg border bg-white px-3 py-2"><div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">Objective</div><div className="mt-1 text-xs text-slate-800">{intelligenceLoggedMeta.objective}</div></div> : null}
                          </div>
                        </div>
                      ) : null}
                      {visibleContent ? <div className="mt-2 whitespace-pre-wrap text-sm text-gray-700">{visibleContent}</div> : null}
                      {activity.editedAt ? (
                        <div className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
                          Edited {dateLabel(activity.editedAt)} by {editorLabel(activity)}{activity.editReason ? ` — Reason: ${activity.editReason}` : ""}
                        </div>
                      ) : null}
                    </>
                  ) : (
                    <div className="mt-3 space-y-3 rounded-xl border border-amber-200 bg-amber-50/60 p-3">
                      <div className="text-xs font-semibold uppercase tracking-wide text-amber-700">Edit under timeline governance</div>
                      <label className="block space-y-1 text-sm">
                        <span className="font-medium text-gray-700">Subject</span>
                        <input value={editSubject} onChange={(e) => setEditSubject(e.target.value)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" />
                      </label>
                      <label className="block space-y-1 text-sm">
                        <span className="font-medium text-gray-700">Details</span>
                        <textarea value={editContent} onChange={(e) => setEditContent(e.target.value)} rows={3} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" />
                      </label>
                      <div className="grid gap-3 md:grid-cols-2">
                        <label className="space-y-1 text-sm">
                          <span className="font-medium text-gray-700">Due date</span>
                          <input type="datetime-local" value={editDueAt} onChange={(e) => setEditDueAt(e.target.value)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" />
                        </label>
                        <label className="space-y-1 text-sm">
                          <span className="font-medium text-gray-700">Reason for edit</span>
                          <input value={editReason} onChange={(e) => setEditReason(e.target.value)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" placeholder="Why is this being changed?" />
                        </label>
                      </div>
                      <div className="flex flex-wrap gap-2">
                        <button type="button" disabled={actionBusyId === activity.id} onClick={() => void saveEdit(activity.id)} className="rounded-lg bg-black px-3 py-2 text-xs font-semibold text-white disabled:opacity-60">{actionBusyId === activity.id ? "Saving..." : "Save edit"}</button>
                        <button type="button" onClick={cancelEditing} className="rounded-lg border bg-white px-3 py-2 text-xs font-medium text-gray-700 hover:bg-gray-50">Cancel</button>
                      </div>
                    </div>
                  )}

                  {isDeleting ? (
                    <div className="mt-3 space-y-3 rounded-xl border border-red-200 bg-red-50 p-3">
                      <div className="text-xs font-semibold uppercase tracking-wide text-red-700">Delete under timeline governance</div>
                      <p className="text-sm text-red-700">This removes the timeline entry from operator view. Governance rules allow deletion only for permitted activity types and roles.</p>
                      <label className="block space-y-1 text-sm">
                        <span className="font-medium text-gray-700">Reason for deletion</span>
                        <input value={deletionReason} onChange={(e) => setDeletionReason(e.target.value)} className="w-full rounded-xl border bg-white px-3 py-2 text-sm" placeholder="Optional deletion reason" />
                      </label>
                      <div className="flex flex-wrap gap-2">
                        <button type="button" disabled={actionBusyId === activity.id} onClick={() => void deleteActivity(activity.id)} className="rounded-lg bg-red-600 px-3 py-2 text-xs font-semibold text-white disabled:opacity-60">{actionBusyId === activity.id ? "Deleting..." : "Confirm delete"}</button>
                        <button type="button" onClick={cancelDeleting} className="rounded-lg border bg-white px-3 py-2 text-xs font-medium text-gray-700 hover:bg-gray-50">Cancel</button>
                      </div>
                    </div>
                  ) : null}
                </div>

                <div className="text-xs text-gray-500 sm:ml-4 sm:w-48 sm:text-right">
                  <div>Recorded {dateLabel(activity.createdAt)}</div>
                  {activity.updatedAt && activity.updatedAt !== activity.createdAt ? <div className="mt-1">Updated {dateLabel(activity.updatedAt)}</div> : null}
                  <div className="mt-3 flex flex-wrap gap-2 sm:justify-end">
                    {!activity.completedAt && canManage ? (
                      <button type="button" disabled={actionBusyId === activity.id} onClick={() => void markComplete(activity.id)} className="rounded-lg border px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-60">Mark complete</button>
                    ) : null}
                    {canEdit ? (
                      <button type="button" onClick={() => startEditing(activity)} className="rounded-lg border px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">Edit</button>
                    ) : null}
                    {canDelete ? (
                      <button type="button" onClick={() => startDeleting(activity)} className="rounded-lg border border-red-200 px-3 py-1.5 text-xs font-medium text-red-700 hover:bg-red-50">Delete</button>
                    ) : null}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}
