"use client";

import { FormEvent, ReactNode, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { apiGet, apiPatch, apiPost } from "@/lib/api";
import type { DashboardSummary, Load, Truck, WorkAssignmentQueueItem, WorkAssignmentQueueSummary } from "@/types";

type BriefingMessage = {
  id: string;
  role: "assistant" | "user";
  content: string;
  createdAt: string;
};

type BriefingSnapshot = {
  key: string;
  label: string;
  generatedAt: string;
  sections: BriefingSection[];
};

type BriefingSection = {
  key: string;
  title: string;
  body: string;
  bullets: string[];
  href?: string;
  actionLabel?: string;
};

type BriefingAction = {
  label: string;
  detail: string;
  href: string;
  priority: "High" | "Medium" | "Normal";
};

type CoriBriefingConversationSummary = {
  id: string;
  briefingDayKey: string;
  title: string;
  isCurrentDay: boolean;
  updatedAt: string;
  messageCount: number;
};

type CoriBriefingConversation = CoriBriefingConversationSummary & {
  generatedAt: string;
  snapshot: BriefingSnapshot | null;
  messages: BriefingMessage[];
};

type CoriBriefingState = {
  preference: {
    businessDayStartTime: string;
  };
  currentDayKey: string;
  conversations: CoriBriefingConversationSummary[];
  selectedConversation: CoriBriefingConversation;
};

const DEFAULT_START_TIME = "06:00";

function formatDateTime(value?: string | null) {
  if (!value) return "No time saved";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "No time saved";
  return date.toLocaleString(undefined, { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" });
}

function formatDayLabel(key: string) {
  const date = new Date(`${key}T12:00:00`);
  if (Number.isNaN(date.getTime())) return key || "Current briefing";
  return date.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric", year: "numeric" });
}

function formatStatus(value?: string | null) {
  if (!value) return "No status saved";
  return value
    .toLowerCase()
    .split("_")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
}

function money(value?: string | number | null) {
  if (value == null || value === "") return "No amount saved";
  const numberValue = Number(value);
  if (!Number.isFinite(numberValue)) return String(value);
  return numberValue.toLocaleString(undefined, { style: "currency", currency: "USD" });
}

function driverName(driver?: { firstName?: string | null; lastName?: string | null } | null) {
  const parts = [driver?.firstName, driver?.lastName].filter(Boolean);
  return parts.length ? parts.join(" ") : "No driver saved";
}

function truckName(truck?: { truckNumber?: string | null } | null) {
  return truck?.truckNumber ? `Truck #${truck.truckNumber}` : "No truck saved";
}

function loadNumber(load: Load) {
  return load.referenceNumber ? `Load #${load.referenceNumber}` : `Load record ${load.id.slice(0, 8)}`;
}

function routeLabel(load: Pick<Load, "pickupLocation" | "deliveryLocation">) {
  const origin = load.pickupLocation || "origin not saved";
  const destination = load.deliveryLocation || "destination not saved";
  return `${origin} to ${destination}`;
}

function truckCompany(truck: Truck) {
  return truck.ownerContactName || truck.factoringCompany || "this workspace";
}

function truckReferenceFromTruck(truck: Truck) {
  const drivers = truck.drivers?.length ? truck.drivers.map((driver) => driverName(driver)).join(", ") : "no driver saved";
  const company = truckCompany(truck);
  return company === "this workspace" ? `${truckName(truck)} with ${drivers}` : `${truckName(truck)} from ${company}`;
}

function truckReferenceFromLoad(load: Load) {
  const base = truckName(load.truck);
  const driver = driverName(load.driver);
  return driver === "No driver saved" ? base : `${base} with ${driver}`;
}

function truckDetail(truck: Truck) {
  const equipment = [truck.year, truck.make, truck.model].filter(Boolean).join(" ") || truck.equipmentType || "equipment type not saved";
  const trailer = [truck.trailerLength ? `${truck.trailerLength} ft` : null, truck.trailerType].filter(Boolean).join(" ");
  const drivers = truck.drivers?.length ? truck.drivers.map((driver) => driverName(driver)).join(", ") : "No active driver linked";
  const company = truckCompany(truck);
  const ownership = company === "this workspace" ? "listed in this workspace" : `from ${company}`;
  return `${truckName(truck)} is a ${equipment}${trailer ? ` with ${trailer}` : ""}, ${ownership}. Driver: ${drivers}. Current status: ${truck.status || "active"}.`;
}

function loadDetail(load: Load, read: string, nextAction: string) {
  const broker = load.broker?.name || "broker/customer not saved";
  return [
    `${loadNumber(load)} from ${broker} is moving from ${routeLabel(load)} with ${truckReferenceFromLoad(load)}.`,
    `  • Status: ${formatStatus(load.status)}`,
    `  • Pickup time: ${formatDateTime(load.pickupDate)}`,
    `  • Delivery time: ${formatDateTime(load.deliveryDate)}`,
    `  • Current read: ${read}`,
    `  • Next action: ${nextAction}`,
  ].join("\n");
}

function loadReference(load: Load, nextAction?: string) {
  const broker = load.broker?.name || "broker/customer not saved";
  const reference = `${loadNumber(load)} from ${broker} to ${load.deliveryLocation || "destination not saved"} on ${truckReferenceFromLoad(load)}`;
  return nextAction ? `${reference}. ${nextAction}` : reference;
}

function assignmentDetail(item: WorkAssignmentQueueItem) {
  return [
    `${item.targetLabel}.`,
    `  • Context: ${item.targetContext || "No extra context saved"}`,
    `  • Instructions: ${item.instructions || "No instructions saved"}`,
    `  • Due: ${formatDateTime(item.dueAt)}`,
    `  • Priority: ${formatStatus(item.priority)}`,
  ].join("\n");
}

function recentChangeDetail(item: DashboardSummary["recentActivity"][number]) {
  return [
    `${item.headline || `${item.referenceNumber ?? "A load"} moved to ${formatStatus(item.toStatus)}`}.`,
    `  • Load: ${item.referenceNumber ? `Load #${item.referenceNumber}` : item.loadId}`,
    `  • Previous status: ${formatStatus(item.fromStatus)}`,
    `  • New status: ${formatStatus(item.toStatus)}`,
    `  • Changed: ${formatDateTime(item.changedAt)}`,
    `  • Context: ${item.contextLine || item.referenceLine || "No extra status context saved"}`,
  ].join("\n");
}

function SectionCard({ title, subtitle, children }: { title: string; subtitle: string; children: ReactNode }) {
  return (
    <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="mb-4">
        <h2 className="text-lg font-semibold text-slate-950">{title}</h2>
        <p className="mt-1 text-sm leading-6 text-slate-600">{subtitle}</p>
      </div>
      {children}
    </section>
  );
}

function BriefingBubble({ sections, generatedAt }: { sections: BriefingSection[]; generatedAt: string }) {
  return (
    <article className="rounded-[2rem] border border-sky-100 bg-sky-50/80 p-5 shadow-sm sm:p-6">
      <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.22em] text-sky-700">CORI briefing</p>
          <h2 className="mt-1 text-2xl font-semibold text-slate-950">Your detailed business briefing is ready.</h2>
        </div>
        <span className="rounded-full border border-sky-200 bg-white px-3 py-1 text-xs font-semibold text-sky-700">
          Updated {generatedAt}
        </span>
      </div>

      <div className="space-y-5">
        {sections.map((section) => (
          <section key={section.key} className="rounded-3xl border border-white/80 bg-white/85 p-4">
            <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
              <div>
                <h3 className="text-base font-semibold text-slate-950">{section.title}</h3>
                <p className="mt-1 text-sm leading-6 text-slate-700">{section.body}</p>
              </div>
              {section.href ? (
                <Link href={section.href} className="inline-flex shrink-0 items-center justify-center rounded-full bg-slate-950 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-800">
                  {section.actionLabel ?? "Open"}
                </Link>
              ) : null}
            </div>
            {section.bullets.length ? (
              <ul className="mt-3 space-y-3 text-sm leading-6 text-slate-700">
                {section.bullets.map((bullet) => (
                  <li key={bullet} className="flex gap-2">
                    <span className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-sky-500" />
                    <span className="whitespace-pre-line">{bullet}</span>
                  </li>
                ))}
              </ul>
            ) : null}
          </section>
        ))}
      </div>
    </article>
  );
}

function ChatMessageCard({ message }: { message: BriefingMessage }) {
  const isUser = message.role === "user";
  return (
    <div className={`flex ${isUser ? "justify-end" : "justify-start"}`}>
      <div className={`max-w-3xl rounded-3xl px-5 py-4 text-sm leading-6 shadow-sm ${isUser ? "bg-slate-950 text-white" : "border border-sky-100 bg-sky-50 text-slate-800"}`}>
        <div className={`mb-1 text-xs font-semibold ${isUser ? "text-slate-300" : "text-sky-700"}`}>{isUser ? "You" : "CORI"}</div>
        <p className="whitespace-pre-line">{message.content}</p>
      </div>
    </div>
  );
}

function buildBriefingSections(
  summary: DashboardSummary | null,
  trucks: Truck[],
  inTransitLoads: Load[],
  assignments: WorkAssignmentQueueItem[],
  assignmentSummary: WorkAssignmentQueueSummary,
): BriefingSection[] {
  const activeTruckCount = trucks.length;
  const needsNextLoad = summary?.needsAssignment.length ?? 0;
  const alerts = summary?.alerts ?? [];
  const readyForInvoice = summary?.readyForInvoice ?? [];
  const overdueOrToday = assignmentSummary.overdue + assignmentSummary.dueToday;
  const inTransitCount = inTransitLoads.length || summary?.loadStateReport.find((item) => item.key === "IN_TRANSIT")?.count || 0;
  const collectionsCount = summary?.dispatcherFollowUpReport.find((item) => item.key === "collections")?.count ?? 0;
  const needsAttentionCount = Number(summary?.queueHealth.find((item) => item.key === "blockers")?.value ?? 0);
  const recentActivity = summary?.recentActivity ?? [];

  const activeTruckDetails = trucks.slice(0, 12).map(truckDetail);
  const activeTruckReferences = trucks.slice(0, 12).map(truckReferenceFromTruck);
  const nextLoadDetails = summary?.needsAssignment.slice(0, 8).map((load) => loadDetail(load, "This truck or load needs attention before the truck finishes without a next move.", "Open the load or truck, confirm availability, and choose the next dispatch move.")) ?? [];
  const nextLoadReferences = summary?.needsAssignment.slice(0, 8).map((load) => loadReference(load, "Confirm availability and choose the next dispatch move.")) ?? [];
  const inTransitDetails = inTransitLoads.slice(0, 10).map((load) => loadDetail(load, "Picked up or underway based on current in-transit status. Progress is expected unless a dispatch risk is listed in this briefing.", "Confirm the next check call, arrival window, or receiver update on the Dispatch Board."));
  const inTransitReferences = inTransitLoads.slice(0, 10).map((load) => loadReference(load, "Confirm the next check call or arrival window."));
  const topAlerts = alerts.slice(0, 6).map((alert) => [
    alert.headline || alert.message,
    `  • Context: ${alert.contextLine || "No extra context saved"}`,
    `  • Reference: ${alert.referenceLine || alert.loadId || "No load reference saved"}`,
    `  • Support: ${alert.supportLine || "Open Dispatch to review the exact load and next action."}`,
  ].join("\n"));
  const topFollowUps = assignments.slice(0, 8).map(assignmentDetail);
  const readyForInvoiceDetails = readyForInvoice.slice(0, 8).map((load) => loadDetail(load, `Delivered or invoice-ready work is present. Amount showing: ${money(load.financialSummary?.grossRevenue ?? load.invoiceAmount)}.`, "Open Documents or Billing, confirm required paperwork, and move the load toward invoice/payment."));
  const readyForInvoiceReferences = readyForInvoice.slice(0, 8).map((load) => loadReference(load, `Amount showing: ${money(load.financialSummary?.grossRevenue ?? load.invoiceAmount)}. Confirm paperwork and move it toward invoice/payment.`));
  const recentChanges = recentActivity.slice(0, 8).map(recentChangeDetail);

  return [
    {
      key: "executive-summary",
      title: "Today’s Business Read",
      body: summary?.daySummary.detail || summary?.daySummary.headline || "CORI reviewed the workspace and prepared the current operating picture for today.",
      bullets: [
        `${activeTruckCount} active truck${activeTruckCount === 1 ? " is" : "s are"} visible in this workspace:${activeTruckDetails.length ? `\n  • ${activeTruckDetails.join("\n  • ")}` : "\n  • No active trucks are currently listed."}`,
        `${inTransitCount} load${inTransitCount === 1 ? " appears" : "s appear"} to be moving right now:${inTransitDetails.length ? `\n  • ${inTransitDetails.join("\n  • ")}` : "\n  • No exact in-transit load records were returned to the briefing feed yet."}`,
        `${needsNextLoad} truck or load item${needsNextLoad === 1 ? " needs" : "s need"} next-load attention:${nextLoadDetails.length ? `\n  • ${nextLoadDetails.join("\n  • ")}` : "\n  • No truck is showing as needing a next load right now."}`,
        `${overdueOrToday} follow-up${overdueOrToday === 1 ? " is" : "s are"} due now or today:${topFollowUps.length ? `\n  • ${topFollowUps.join("\n  • ")}` : "\n  • No urgent follow-up record is showing right now."}`,
      ],
      href: "/dispatch",
      actionLabel: "Open Dispatch",
    },
    {
      key: "what-changed",
      title: "What Changed Since Your Last Check-In",
      body: recentChanges.length ? "These exact movements changed the operating picture." : "No major recent load-status changes are showing in the current dashboard feed.",
      bullets: recentChanges.length ? recentChanges : ["CORI will continue tracking load movements, status changes, and follow-up pressure throughout the day."],
      href: "/loads",
      actionLabel: "Review Loads",
    },
    {
      key: "dispatch-operations",
      title: "Dispatch Operations",
      body: alerts.length || overdueOrToday ? "Dispatch has active work that should be handled before it becomes expensive or disruptive." : "Dispatch appears calm right now, but CORI will keep watching for load risks and missed follow-ups.",
      bullets: [
        `${alerts.length} live dispatch risk${alerts.length === 1 ? " is" : "s are"} showing:${topAlerts.length ? `\n  • ${topAlerts.join("\n  • ")}` : "\n  • No high-risk live load alert is showing right now."}`,
        `${overdueOrToday} follow-up${overdueOrToday === 1 ? " is" : "s are"} due now or today:${topFollowUps.length ? `\n  • ${topFollowUps.join("\n  • ")}` : "\n  • No due follow-up record is showing right now."}`,
      ],
      href: "/dispatch",
      actionLabel: "Work Board",
    },
    {
      key: "trucks-drivers",
      title: "Trucks and Drivers",
      body: needsNextLoad ? "The most important truck work is making sure trucks do not finish without a next move." : "Trucks look covered from the current briefing view.",
      bullets: [
        `${activeTruckCount} active truck${activeTruckCount === 1 ? " is" : "s are"} were introduced in the executive summary. For the rest of this briefing, CORI will refer to them by truck number and company:${activeTruckReferences.length ? `\n  • ${activeTruckReferences.join("\n  • ")}` : "\n  • No active trucks are currently listed."}`,
        nextLoadReferences.length ? `Next-load items to watch now:\n  • ${nextLoadReferences.join("\n  • ")}` : "No truck is currently showing as needing a next load from the dashboard feed.",
      ],
      href: "/trucks",
      actionLabel: "Open Trucks",
    },
    {
      key: "loads-in-motion",
      title: "Loads in Motion",
      body: "CORI is watching active loads for follow-up timing, risk signals, and missing movement steps.",
      bullets: [
        `${inTransitCount} moving load${inTransitCount === 1 ? " is" : "s are"} were detailed in the executive summary. Current movement watch list:${inTransitReferences.length ? `\n  • ${inTransitReferences.join("\n  • ")}` : "\n  • No exact in-transit load list was returned to CORI yet."}`,
        `${needsAttentionCount} item${needsAttentionCount === 1 ? " needs" : "s need"} attention on the Dispatch Board. ${needsAttentionCount ? "Open Dispatch and handle the named issue before it affects service." : "No specific issue is showing right now."}`,
      ],
      href: "/dispatch",
      actionLabel: "Open Board",
    },
    {
      key: "routes-weather",
      title: "Routes and Weather Risks",
      body: "Route and weather review should stay connected to exact loads, trucks, and drivers so the dispatcher can make one clear movement decision.",
      bullets: [
        inTransitReferences.length ? `Start route/weather review with these moving loads first:\n  • ${inTransitReferences.slice(0, 5).join("\n  • ")}` : "No moving load is currently available for route/weather review in this briefing feed.",
        "CORI should explain detours, weather pressure, timing risk, and price impact in plain language before a dispatcher calls the broker, carrier, or driver.",
        "When needed, ask CORI to draft a broker or driver update using the route issue and load details.",
      ],
      href: "/routes",
      actionLabel: "Plan Routes",
    },
    {
      key: "documents-compliance",
      title: "Paperwork",
      body: readyForInvoice.length ? "Completed work still needs paperwork or invoice attention." : "No delivered load is currently showing as ready for invoice follow-up.",
      bullets: readyForInvoiceDetails.length ? readyForInvoiceDetails : ["CORI will continue watching PODs, rate confirmations, invoices, and missing paperwork. No exact paperwork issue is listed right now."],
      href: "/documents",
      actionLabel: "Check Paperwork",
    },
    {
      key: "billing-cash-flow",
      title: "Billing and Cash Flow",
      body: collectionsCount || readyForInvoice.length ? "Cash-flow work is present. Focus on invoice-ready loads first, then collections follow-up." : "Billing pressure looks manageable from the current dashboard feed.",
      bullets: [
        `${readyForInvoice.length} delivered load${readyForInvoice.length === 1 ? " may" : "s may"} need invoice or paperwork attention:${readyForInvoiceReferences.length ? `\n  • ${readyForInvoiceReferences.join("\n  • ")}` : "\n  • No invoice-ready load record is listed right now."}`,
        `${collectionsCount} collection follow-up item${collectionsCount === 1 ? " is" : "s are"} showing. ${collectionsCount ? "Open Billing and work each unpaid load by broker/customer, amount, and payment status." : "No collection follow-up detail is currently listed."}`,
        "Use Billing Records for unpaid customer money. Keep app account setup in Workspace Settings.",
      ],
      href: "/billing",
      actionLabel: "Open Billing",
    },
    {
      key: "customers-carriers",
      title: "Broker, Customer, and Carrier Follow-Up",
      body: topFollowUps.length ? "These exact follow-ups may affect freight movement, payment, or relationship quality today." : "No urgent broker, customer, or carrier follow-up is showing from the current queue.",
      bullets: topFollowUps.length ? topFollowUps : ["CORI will keep watching follow-up tasks, customer requests, and carrier service needs."],
      href: "/crm",
      actionLabel: "Open CRM",
    },
    {
      key: "messages-email",
      title: "Email Follow-Up",
      body: "Use CORI Mail when email needs attention. This daily briefing stays focused on dispatch, paperwork, money, and follow-up work.",
      bullets: [
        "Open CORI Mail to review important messages, suggested replies, and email-to-work cards.",
        "Review every drafted reply before anything is sent.",
        "Ask CORI to turn important emails into load notes, follow-up tasks, billing notes, driver updates, or sales leads.",
      ],
      href: "/cori/mail",
      actionLabel: "Open CORI Mail",
    },
    {
      key: "priorities",
      title: "CORI Recommended Order of Work",
      body: "CORI recommends working the business in the order that protects movement, paperwork, money, and relationships.",
      bullets: [
        nextLoadReferences.length ? `First: protect trucks that need a next load.\n  • ${nextLoadReferences.slice(0, 3).join("\n  • ")}` : "First: keep monitoring active loads and next-load coverage. No exact next-load issue is showing right now.",
        topAlerts.length ? `Second: clear live load risks before they become service failures.\n  • ${topAlerts.slice(0, 3).join("\n  • ")}` : "Second: keep dispatch steady and confirm movement updates as they happen.",
        readyForInvoiceReferences.length ? `Third: clear paperwork or invoice issues so money can move.\n  • ${readyForInvoiceReferences.slice(0, 3).join("\n  • ")}` : "Third: keep billing clean and prevent paperwork backlog.",
        topFollowUps.length ? `Fourth: finish due follow-ups so nobody is waiting on your team.\n  • ${topFollowUps.slice(0, 3).join("\n  • ")}` : "Fourth: use CORI for route, call, quote, and planning support as new work appears.",
      ],
      href: "/dispatch",
      actionLabel: "Start Work",
    },
    {
      key: "cori-actions",
      title: "Actions CORI Can Help With Now",
      body: "You can continue this briefing and ask CORI to explain, draft, summarize, or guide supported actions without leaving the daily business context.",
      bullets: [
        "Ask CORI to explain why a specific load is risky by load number, broker/customer, truck, driver, route, and timing.",
        "Ask CORI to draft a broker or carrier message for your review using the exact load, price, route, and delay context from this briefing.",
        "Ask CORI to summarize today’s unresolved dispatch, paperwork, or billing issues with named records only.",
        "Ask CORI to compare today’s briefing with a previous day by date and approximate time.",
      ],
    },
  ];
}

function buildActions(sections: BriefingSection[]): BriefingAction[] {
  return sections
    .filter((section) => section.href)
    .slice(0, 6)
    .map((section, index) => ({
      label: section.actionLabel ?? "Open",
      detail: section.title,
      href: section.href ?? "/dashboard",
      priority: index < 2 ? "High" : index < 4 ? "Medium" : "Normal",
    }));
}

export default function DashboardPage() {
  const [summary, setSummary] = useState<DashboardSummary | null>(null);
  const [trucks, setTrucks] = useState<Truck[]>([]);
  const [inTransitLoads, setInTransitLoads] = useState<Load[]>([]);
  const [assignments, setAssignments] = useState<WorkAssignmentQueueItem[]>([]);
  const [assignmentSummary, setAssignmentSummary] = useState<WorkAssignmentQueueSummary>({ total: 0, overdue: 0, dueToday: 0, dueSoon: 0, urgent: 0, escalated: 0 });
  const [error, setError] = useState<string | null>(null);
  const [businessStartTime, setBusinessStartTime] = useState(DEFAULT_START_TIME);
  const [currentDayKey, setCurrentDayKey] = useState("");
  const [selectedDayKey, setSelectedDayKey] = useState("");
  const [briefingIndex, setBriefingIndex] = useState<CoriBriefingConversationSummary[]>([]);
  const [selectedConversation, setSelectedConversation] = useState<CoriBriefingConversation | null>(null);
  const [messages, setMessages] = useState<BriefingMessage[]>([]);
  const [draft, setDraft] = useState("");

  function applyBriefingState(data: CoriBriefingState) {
    setBusinessStartTime(data.preference.businessDayStartTime || DEFAULT_START_TIME);
    setCurrentDayKey(data.currentDayKey);
    setSelectedDayKey(data.selectedConversation.briefingDayKey);
    setBriefingIndex(data.conversations ?? []);
    setSelectedConversation(data.selectedConversation);
    setMessages(data.selectedConversation.messages ?? []);
  }

  function loadBriefingState(dayKey?: string) {
    const path = dayKey ? `/api/cori-briefing?dayKey=${encodeURIComponent(dayKey)}` : "/api/cori-briefing";
    apiGet<CoriBriefingState>(path)
      .then((data) => {
        applyBriefingState(data);
        setError(null);
      })
      .catch((err: any) => setError(err?.message ?? "Failed to load CORI Briefing"));
  }

  useEffect(() => {
    loadBriefingState();

    apiGet<{ summary: DashboardSummary }>("/api/dashboard/summary")
      .then((data) => {
        setSummary(data.summary);
        setError(null);
      })
      .catch((err: any) => setError(err?.message ?? "Failed to load CORI Briefing"));

    apiGet<{ items: WorkAssignmentQueueItem[]; summary: WorkAssignmentQueueSummary }>("/api/assignments/queue?scope=MINE")
      .then((data) => {
        setAssignments(data.items ?? []);
        setAssignmentSummary(data.summary);
      })
      .catch(() => {});

    apiGet<{ trucks: Truck[] }>("/api/trucks")
      .then((data) => setTrucks((data.trucks ?? []).filter((truck) => truck.isActive !== false)))
      .catch(() => {});

    apiGet<{ loads: Load[] }>("/api/loads?status=IN_TRANSIT")
      .then((data) => setInTransitLoads(data.loads ?? []))
      .catch(() => {});
  }, []);

  const generatedAt = useMemo(() => new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }), [summary, trucks, inTransitLoads, assignments]);
  const liveSections = useMemo(() => buildBriefingSections(summary, trucks, inTransitLoads, assignments, assignmentSummary), [assignmentSummary, assignments, inTransitLoads, summary, trucks]);
  const liveSnapshot = useMemo<BriefingSnapshot>(() => ({ key: currentDayKey, label: formatDayLabel(currentDayKey), generatedAt, sections: liveSections }), [currentDayKey, generatedAt, liveSections]);
  const isCurrentDay = selectedDayKey === currentDayKey;
  const selectedSnapshot = useMemo(() => {
    if (!selectedDayKey || isCurrentDay) return liveSnapshot;
    return selectedConversation?.snapshot ?? {
      key: selectedDayKey,
      label: formatDayLabel(selectedDayKey),
      generatedAt: selectedConversation?.generatedAt ? formatDateTime(selectedConversation.generatedAt) : "Saved briefing",
      sections: [
        {
          key: "past-placeholder",
          title: "Past briefing record",
          body: "This earlier briefing is read-only. The stored briefing snapshot will appear here after that day has been saved by the CORI Briefing persistence service.",
          bullets: ["Open today’s briefing to continue the current business conversation. Past days can be referenced by date and approximate time, but not continued."],
        },
      ],
    };
  }, [isCurrentDay, liveSnapshot, selectedConversation, selectedDayKey]);
  const currentActions = useMemo(() => buildActions(liveSections), [liveSections]);

  useEffect(() => {
    if (!currentDayKey || !isCurrentDay || !liveSections.length) return;
    const snapshot = liveSnapshot;
    const timer = window.setTimeout(() => {
      apiPatch<CoriBriefingState>("/api/cori-briefing", { briefingDayKey: currentDayKey, snapshot }).catch(() => {});
    }, 600);
    return () => window.clearTimeout(timer);
  }, [currentDayKey, isCurrentDay, liveSections.length, liveSnapshot]);

  function handleStartTimeChange(value: string) {
    setBusinessStartTime(value);
    apiPatch<CoriBriefingState>("/api/cori-briefing", { businessDayStartTime: value })
      .then((data) => applyBriefingState(data))
      .catch((err: any) => setError(err?.message ?? "Failed to update briefing day start time"));
  }

  function selectDay(key: string) {
    loadBriefingState(key);
  }

  function handleAskCori(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const question = draft.trim();
    if (!question || !isCurrentDay || !currentDayKey) return;
    apiPost<{ conversation: CoriBriefingConversation }>("/api/cori-briefing", { dayKey: currentDayKey, content: question })
      .then((data) => {
        if (data.conversation) {
          setSelectedConversation(data.conversation);
          setMessages(data.conversation.messages ?? []);
        }
        setDraft("");
      })
      .catch((err: any) => setError(err?.message ?? "Failed to save briefing message"));
  }

  return (
    <div className="space-y-6">
      <div className="rounded-[2rem] border border-slate-200 bg-white p-6 shadow-sm">
        <div className="flex flex-col gap-5 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-sm font-semibold uppercase tracking-[0.24em] text-sky-700">Daily executive assistant</p>
            <h1 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">CORI Briefing</h1>
            <p className="mt-3 max-w-3xl text-sm leading-6 text-slate-600">
              This is the detailed daily business briefing conversation. Ask CORI general questions on the Ask CORI page, but use this page to review today’s operation, check progress, and continue the current day’s executive briefing.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href="/cori" className="inline-flex items-center rounded-full border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 shadow-sm hover:bg-slate-50">
              Ask CORI
            </Link>
            <Link href="/dispatch" className="inline-flex items-center rounded-full bg-slate-950 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-slate-800">
              Open Dispatch
            </Link>
          </div>
        </div>
      </div>

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

      <div className="grid gap-6 xl:grid-cols-[280px_1fr]">
        <aside className="space-y-4">
          <SectionCard title="Briefing day" subtitle="Choose when a new business day starts.">
            <label className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" htmlFor="business-start-time">New day starts</label>
            <input
              id="business-start-time"
              type="time"
              value={businessStartTime}
              onChange={(event) => handleStartTimeChange(event.target.value)}
              className="mt-2 w-full rounded-2xl border border-slate-300 bg-white px-4 py-3 text-sm font-semibold text-slate-900 shadow-sm focus:border-sky-400 focus:outline-none focus:ring-4 focus:ring-sky-100"
            />
            <p className="mt-3 text-sm leading-6 text-slate-600">
              Current briefing day: <span className="font-semibold text-slate-900">{formatDayLabel(currentDayKey)}</span>
            </p>
          </SectionCard>

          <SectionCard title="Past briefings" subtitle="Past days are read-only. Use today to continue the conversation.">
            <div className="space-y-2">
              {briefingIndex.map((conversation) => {
                const active = conversation.briefingDayKey === selectedDayKey;
                const current = conversation.briefingDayKey === currentDayKey;
                return (
                  <button
                    key={conversation.id}
                    type="button"
                    onClick={() => selectDay(conversation.briefingDayKey)}
                    className={`w-full rounded-2xl border px-4 py-3 text-left text-sm transition ${active ? "border-sky-300 bg-sky-50 text-sky-900" : "border-slate-200 bg-slate-50 text-slate-700 hover:bg-white"}`}
                  >
                    <span className="block font-semibold">{formatDayLabel(conversation.briefingDayKey)}</span>
                    <span className="mt-1 block text-xs text-slate-500">{current ? "Current day · active" : "Read-only"} · {conversation.messageCount} saved messages</span>
                  </button>
                );
              })}
            </div>
          </SectionCard>

          <SectionCard title="Next links" subtitle="Direct paths from today’s briefing.">
            <div className="space-y-2">
              {currentActions.map((action) => (
                <Link key={`${action.href}-${action.detail}`} href={action.href} className="block rounded-2xl border bg-slate-50 px-4 py-3 text-sm hover:bg-white hover:shadow-sm">
                  <span className="font-semibold text-slate-900">{action.label}</span>
                  <span className="mt-1 block text-slate-600">{action.detail}</span>
                </Link>
              ))}
            </div>
          </SectionCard>
        </aside>

        <main className="space-y-5">
          <BriefingBubble sections={selectedSnapshot.sections} generatedAt={selectedSnapshot.generatedAt} />

          <SectionCard title={isCurrentDay ? "Continue today’s briefing" : "Past briefing conversation"} subtitle={isCurrentDay ? "Ask clarifying questions or ask CORI to prepare a supported action from this briefing." : "Past briefing days are read-only. Reference this day from today’s briefing if needed."}>
            <div className="space-y-4">
              {messages.length ? messages.map((message) => <ChatMessageCard key={message.id} message={message} />) : (
                <div className="rounded-3xl border border-dashed bg-slate-50 px-5 py-6 text-sm leading-6 text-slate-600">
                  {isCurrentDay ? "No follow-up questions have been added to today’s briefing yet." : "No saved follow-up messages are stored for this past briefing day yet."}
                </div>
              )}
            </div>

            <form onSubmit={handleAskCori} className="mt-5 rounded-[1.75rem] border border-sky-100 bg-sky-50 p-3">
              <label htmlFor="ask-cori-briefing" className="mb-2 block px-2 text-sm font-semibold text-sky-900">Ask CORI</label>
              <div className="flex flex-col gap-3 md:flex-row">
                <textarea
                  id="ask-cori-briefing"
                  value={draft}
                  onChange={(event) => setDraft(event.target.value)}
                  disabled={!isCurrentDay}
                  rows={3}
                  placeholder={isCurrentDay ? "Ask a question, request an explanation, or tell CORI what action you want prepared…" : "Past briefing days are read-only."}
                  className="min-h-24 flex-1 resize-none rounded-3xl border border-sky-200 bg-white px-4 py-3 text-sm leading-6 text-slate-900 shadow-sm focus:border-sky-400 focus:outline-none focus:ring-4 focus:ring-sky-100 disabled:bg-slate-100 disabled:text-slate-500"
                />
                <button
                  type="submit"
                  disabled={!isCurrentDay || !draft.trim()}
                  className="inline-flex items-center justify-center rounded-full bg-slate-950 px-6 py-3 text-sm font-semibold text-white shadow-sm hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-300"
                >
                  Send
                </button>
              </div>
              <p className="mt-3 px-2 text-xs leading-5 text-slate-600">
                This briefing conversation is separate from the general Ask CORI page. Today stays active; earlier days can be reviewed and referenced, but not continued.
              </p>
            </form>
          </SectionCard>
        </main>
      </div>
    </div>
  );
}
