"use client";

import { ChangeEvent, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { apiGet, apiPost } from "@/lib/api";

type MailTone = "urgent" | "watch" | "good" | "info";
type MailCategory = "Money" | "Paperwork" | "Load update" | "Driver" | "Sales";
type ReplyMode = "clear" | "firm" | "friendly" | "short";
type ActionState = "review" | "draft_saved" | "mailbox_draft_ready" | "send_ready";
type WorkActionType = "load_note" | "task" | "billing_note" | "driver_update" | "detention_note" | "sales_lead";

type CoriMailPersistenceSummary = {
  providerAccounts: number;
  emailProviderAccounts: number;
  customSmtpAccounts: number;
  drafts: number;
  workActions: number;
  sendAuditRecords: number;
  pendingApprovalSends: number;
  approvedSends: number;
  queuedSends: number;
  sentSends: number;
  failedSends: number;
  needsAttentionSends: number;
  simpleStatus: string;
  nextStep: string;
};

type CoriMailApprovedSendReadiness = {
  status: "READY" | "SETUP_NEEDED" | "SEND_LOCKED";
  canSend: boolean;
  canApprove: boolean;
  connectedLabel: string | null;
  message: string;
  nextStep: string;
  settingsHref: string;
  checkedAt: string;
};

type CoriMailApprovedSendResult = {
  ok: boolean;
  status: "READY" | "SETUP_NEEDED" | "SEND_LOCKED" | "SENT" | "FAILED";
  message: string;
  auditRecordId?: string;
  providerMessageId?: string | null;
  settingsHref?: string;
};

type CoriMailSendReviewRecord = {
  id: string;
  subject: string;
  toEmail: string;
  ccEmail: string | null;
  status: "APPROVAL_REQUIRED" | "APPROVED" | "SEND_QUEUED" | "SENT" | "FAILED" | "CANCELED";
  statusLabel: string;
  statusTone: MailTone;
  simpleDetail: string;
  timingLabel: string;
  createdAt: string;
  approvedAt: string | null;
  sentAt: string | null;
  needsAttention: boolean;
};

type CoriMailMessage = {
  id: string;
  fromName: string;
  fromEmail: string;
  subject: string;
  receivedAt: string;
  category: MailCategory;
  tone: MailTone;
  linkedRecord: string;
  loadHref?: string;
  truckHref?: string;
  plainRead: string;
  whyItMatters: string;
  nextStep: string;
  userInstruction: string;
  suggestedReply: string;
  replyTo: string;
  cc?: string;
  workActions: WorkActionType[];
};

type MetricCardProps = {
  label: string;
  value: string;
  detail: string;
  tone?: MailTone;
};

type BriefingLaneProps = {
  label: string;
  detail: string;
  count: number;
  tone: MailTone;
};

type DraftMemory = {
  body: string;
  savedAt: string;
};

const DRAFT_STORAGE_KEY = "dispatchspot.coriMail.drafts.v366";

const EMAILS: CoriMailMessage[] = [
  {
    id: "msg-rateconf-1842",
    fromName: "Maya Brooks",
    fromEmail: "maya.brooks@atlanticfreight.example",
    subject: "Rate con missing signed copy for Load DS-1842",
    receivedAt: "Today 7:42 AM",
    category: "Paperwork",
    tone: "urgent",
    linkedRecord: "Load #DS-1842 · Truck #152 · Marcus James",
    loadHref: "/loads",
    truckHref: "/trucks",
    plainRead: "The broker is asking for the signed rate confirmation. This can slow pickup if it is not sent soon.",
    whyItMatters: "This touches load start, broker trust, and dispatch paperwork.",
    nextStep: "Send the signed rate con or ask the broker to resend the latest copy if the file is missing.",
    userInstruction: "Reply with a clear update and ask for confirmation once the broker receives the signed copy.",
    replyTo: "maya.brooks@atlanticfreight.example",
    workActions: ["load_note", "task"],
    suggestedReply:
      "Good morning Maya,\n\nThank you for the reminder. I am checking the signed rate confirmation for Load DS-1842 now. If the signed copy is already in our file, I will send it over shortly. If not, please resend the latest rate con so we can sign the correct version and keep pickup on track.\n\nI will follow up once it is handled.\n\nThank you,",
  },
  {
    id: "msg-payment-617",
    fromName: "Tanya Lewis",
    fromEmail: "ap@northstarlogistics.example",
    subject: "Payment status on invoice INV-617",
    receivedAt: "Today 8:16 AM",
    category: "Money",
    tone: "watch",
    linkedRecord: "Invoice INV-617 · Load #DS-1809 · $3,850 open",
    loadHref: "/billing",
    plainRead: "Accounts payable is asking for a payment status. The invoice still appears open.",
    whyItMatters: "This is a money follow-up. CORI should keep the tone firm but simple.",
    nextStep: "Ask for the planned payment date and confirm if any paperwork is still needed.",
    userInstruction: "Ask for a payment date and keep the relationship professional.",
    replyTo: "ap@northstarlogistics.example",
    workActions: ["billing_note", "task"],
    suggestedReply:
      "Good morning Tanya,\n\nI am checking on invoice INV-617 for Load DS-1809. Our side still shows an open balance of $3,850. Can you please confirm the planned payment date?\n\nIf anything is missing from our paperwork, please let me know and I will help get it corrected quickly.\n\nThank you,",
  },
  {
    id: "msg-driver-152",
    fromName: "Marcus James",
    fromEmail: "marcus.james@examplemail.test",
    subject: "Receiver says dock is backed up",
    receivedAt: "Today 8:31 AM",
    category: "Driver",
    tone: "urgent",
    linkedRecord: "Truck #152 · Load #DS-1842 · Receiver delay",
    loadHref: "/loads",
    truckHref: "/trucks",
    plainRead: "The driver says the receiver is delayed. This may create detention time.",
    whyItMatters: "CORI should protect the carrier by starting a clean delay record early.",
    nextStep: "Ask the driver for arrival time, dock time, and any receiver contact name.",
    userInstruction: "Reply to the driver and ask for the facts needed for detention.",
    replyTo: "marcus.james@examplemail.test",
    workActions: ["driver_update", "detention_note", "task"],
    suggestedReply:
      "Marcus,\n\nThanks for the update. Please send me your arrival time, the time they gave you a dock, and the name of anyone you spoke with at the receiver if you have it.\n\nStay checked in there. I am going to document the delay so we can protect detention if it applies.",
  },
  {
    id: "msg-broker-lane",
    fromName: "Derrick Stone",
    fromEmail: "derrick.stone@ridgewayloads.example",
    subject: "Any trucks near Jacksonville Friday?",
    receivedAt: "Yesterday 5:58 PM",
    category: "Sales",
    tone: "good",
    linkedRecord: "Sales follow-up · possible Friday lane",
    plainRead: "A broker is asking about future truck availability. This is a chance to create a load opportunity.",
    whyItMatters: "Fast, clear replies help Dispatch Spot win better load conversations.",
    nextStep: "Reply with availability and ask for lane, commodity, weight, rate, pickup time, and delivery time.",
    userInstruction: "Reply warmly and ask for the load details needed to quote.",
    replyTo: "derrick.stone@ridgewayloads.example",
    workActions: ["sales_lead", "task"],
    suggestedReply:
      "Hi Derrick,\n\nWe may have capacity near Jacksonville on Friday. Please send the pickup city, delivery city, commodity, weight, appointment times, and target rate.\n\nOnce I have those details, I can check fit quickly and let you know what works.\n\nThank you,",
  },
];




const QUICK_COMMANDS = [
  "Show only emails that need an answer today.",
  "Draft a firm but polite payment follow-up.",
  "Find emails linked to Truck #152.",
  "Turn this email into a task and load note.",
];

const WORK_ACTION_LABELS: Record<WorkActionType, string> = {
  load_note: "Load note",
  task: "Follow-up task",
  billing_note: "Billing note",
  driver_update: "Driver update",
  detention_note: "Detention note",
  sales_lead: "Sales lead",
};

function toneClasses(tone: MailTone = "info") {
  if (tone === "urgent") return "border-rose-200 bg-rose-50 text-rose-800";
  if (tone === "watch") return "border-amber-200 bg-amber-50 text-amber-800";
  if (tone === "good") return "border-emerald-200 bg-emerald-50 text-emerald-800";
  return "border-sky-200 bg-sky-50 text-sky-800";
}

function toneLabel(tone: MailTone) {
  if (tone === "urgent") return "Needs answer now";
  if (tone === "watch") return "Watch today";
  if (tone === "good") return "Good opportunity";
  return "Helpful info";
}

function categoryTone(category: MailCategory): MailTone {
  if (category === "Money") return "watch";
  if (category === "Paperwork") return "urgent";
  if (category === "Driver") return "urgent";
  if (category === "Sales") return "good";
  return "info";
}

function metricBorder(tone: MailTone = "info") {
  if (tone === "urgent") return "border-rose-200";
  if (tone === "watch") return "border-amber-200";
  if (tone === "good") return "border-emerald-200";
  return "border-slate-200";
}

function applyReplyMode(reply: string, message: CoriMailMessage, mode: ReplyMode) {
  if (mode === "short") {
    return `Hi ${message.fromName.split(" ")[0]},\n\nI received this and I am checking it now. I will follow up shortly with the next update.\n\nThank you,`;
  }

  if (mode === "firm") {
    return `${reply}\n\nPlease confirm receipt and the next expected step so we can keep this moving without delay.`;
  }

  if (mode === "friendly") {
    return reply.replace("Thank you,", "Thanks again,");
  }

  return reply;
}

function buildCoriCommandReply(command: string, message: CoriMailMessage) {
  const lower = command.toLowerCase();

  if (!command.trim()) return "Type a simple command. Example: Draft a short reply asking for the missing POD.";

  if (lower.includes("send")) {
    return "CORI prepared the action. Review the draft first. Sending stays locked until email is connected and approved.";
  }

  if (lower.includes("task") || lower.includes("note") || lower.includes("convert")) {
    return `CORI can turn this email into: ${message.workActions.map((action) => WORK_ACTION_LABELS[action]).join(", ")}. Review the work card before saving.`;
  }

  if (lower.includes("payment") || lower.includes("invoice") || lower.includes("money")) {
    return `Use a firm money reply for ${message.linkedRecord}. Ask for the payment date and ask if any paperwork is missing.`;
  }

  if (lower.includes("truck") || lower.includes("driver")) {
    return `Focus on ${message.linkedRecord}. Ask for time, location, contact name, and the next update time.`;
  }

  if (lower.includes("today") || lower.includes("urgent")) {
    return "Start with the messages marked Needs answer now. They can block pickup, delivery, detention, or payment.";
  }

  return `CORI is focused on ${message.subject}. Best next step: ${message.nextStep}`;
}

function buildWorkPreview(message: CoriMailMessage, action: WorkActionType) {
  if (action === "billing_note") return `Add billing note to ${message.linkedRecord}: payment follow-up sent; waiting for planned payment date or missing paperwork answer.`;
  if (action === "detention_note") return `Start detention note for ${message.linkedRecord}: driver reported receiver delay; collect arrival time, dock time, and receiver contact.`;
  if (action === "driver_update") return `Add driver update to ${message.linkedRecord}: driver says receiver is backed up; dispatcher requested clean delay facts.`;
  if (action === "sales_lead") return `Create sales lead from ${message.fromName}: possible Jacksonville capacity request; ask for lane, commodity, weight, times, and target rate.`;
  if (action === "task") return `Create follow-up task: ${message.nextStep}`;
  return `Add load note to ${message.linkedRecord}: ${message.plainRead}`;
}

function persistentWorkActionType(action: WorkActionType) {
  if (action === "load_note") return "LOAD_NOTE";
  if (action === "billing_note") return "BILLING_NOTE";
  if (action === "driver_update") return "DRIVER_UPDATE";
  if (action === "detention_note") return "DETENTION_NOTE";
  if (action === "sales_lead") return "SALES_LEAD";
  return "FOLLOW_UP_TASK";
}

function nowLabel() {
  return new Date().toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
}

function MetricCard({ label, value, detail, tone = "info" }: MetricCardProps) {
  return (
    <div className={`rounded-3xl border ${metricBorder(tone)} bg-white p-5 shadow-sm`}>
      <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">{label}</div>
      <div className="mt-3 text-3xl font-semibold tracking-tight text-slate-950">{value}</div>
      <p className="mt-2 text-sm leading-6 text-slate-600">{detail}</p>
    </div>
  );
}

function BriefingLane({ label, detail, count, tone }: BriefingLaneProps) {
  return (
    <div className={`rounded-2xl border p-4 ${toneClasses(tone)}`}>
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="text-sm font-semibold">{label}</div>
          <p className="mt-1 text-sm leading-5 opacity-90">{detail}</p>
        </div>
        <div className="rounded-full bg-white/70 px-3 py-1 text-sm font-semibold">{count}</div>
      </div>
    </div>
  );
}

function SendReviewStatusCard({ label, value, detail, tone = "info" }: MetricCardProps) {
  return (
    <div className={`rounded-2xl border ${metricBorder(tone)} bg-slate-50 p-4`}>
      <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">{label}</div>
      <div className="mt-2 text-2xl font-semibold text-slate-950">{value}</div>
      <p className="mt-1 text-sm leading-5 text-slate-600">{detail}</p>
    </div>
  );
}

function emptySendHistoryMessage(sendReady: boolean, providerConnected: boolean) {
  if (sendReady) return "No approved-send history yet. Review a reply, then approve it when the exact words are ready.";
  if (providerConnected) return "No send history yet. You can review and approve replies, but live sending is still locked.";
  return "No send history yet. Review replies here; a workspace admin can connect company email in Workspace Integrations.";
}

export default function CoriMailPage() {
  const [selectedId, setSelectedId] = useState(EMAILS[0]?.id ?? "");
  const [replyMode, setReplyMode] = useState<ReplyMode>("clear");
  const [command, setCommand] = useState("");
  const [commandReply, setCommandReply] = useState("CORI is ready. Pick an email or type a command in plain words.");
  const [actionState, setActionState] = useState<ActionState>("review");
  const [selectedWorkAction, setSelectedWorkAction] = useState<WorkActionType>(EMAILS[0]?.workActions[0] ?? "task");
  const [savedWorkAction, setSavedWorkAction] = useState("");
  const selectedMessage = useMemo(() => EMAILS.find((email) => email.id === selectedId) ?? EMAILS[0], [selectedId]);
  const [draftById, setDraftById] = useState<Record<string, DraftMemory>>(() =>
    Object.fromEntries(EMAILS.map((email) => [email.id, { body: email.suggestedReply, savedAt: "Not saved yet" }]))
  );
  const [persistenceSummary, setPersistenceSummary] = useState<CoriMailPersistenceSummary | null>(null);
  const [sendReadiness, setSendReadiness] = useState<CoriMailApprovedSendReadiness | null>(null);
  const [sendResult, setSendResult] = useState("");
  const [sendLoading, setSendLoading] = useState(false);
  const [sendHistory, setSendHistory] = useState<CoriMailSendReviewRecord[]>([]);

  useEffect(() => {
    try {
      const stored = window.localStorage.getItem(DRAFT_STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored) as Record<string, DraftMemory>;
        setDraftById((current) => ({ ...current, ...parsed }));
      }
    } catch {
      setCommandReply("CORI Mail opened. Browser draft memory is not available in this session.");
    }
  }, []);

  useEffect(() => {
    try {
      window.localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draftById));
    } catch {
      // Keep the interface usable even when browser storage is blocked.
    }
  }, [draftById]);


  async function refreshCoriMailMemory() {
    const [summaryData, historyData] = await Promise.all([
      apiGet<{ summary: CoriMailPersistenceSummary }>("/api/cori-mail/persistence"),
      apiGet<{ history: CoriMailSendReviewRecord[] }>("/api/cori-mail/send-history"),
    ]);
    setPersistenceSummary(summaryData.summary);
    setSendHistory(historyData.history);
  }

  useEffect(() => {
    refreshCoriMailMemory().catch(() => {
      setPersistenceSummary(null);
      setSendHistory([]);
    });

    apiGet<{ readiness: CoriMailApprovedSendReadiness }>("/api/cori-mail/approved-send")
      .then((data) => setSendReadiness(data.readiness))
      .catch(() => setSendReadiness(null));
  }, []);

  useEffect(() => {
    if (!selectedMessage.workActions.includes(selectedWorkAction)) {
      setSelectedWorkAction(selectedMessage.workActions[0] ?? "task");
    }
  }, [selectedMessage, selectedWorkAction]);

  const currentDraft = draftById[selectedMessage.id]?.body ?? selectedMessage.suggestedReply;
  const currentDraftSavedAt = draftById[selectedMessage.id]?.savedAt ?? "Not saved yet";
  const urgentCount = EMAILS.filter((email) => email.tone === "urgent").length;
  const moneyCount = EMAILS.filter((email) => email.category === "Money").length;
  const readyReplyCount = EMAILS.filter((email) => email.suggestedReply.trim()).length;
  const savedDraftCount = Object.values(draftById as Record<string, DraftMemory>).filter((draft) => draft.savedAt !== "Not saved yet").length;
  const providerConnected = Boolean(sendReadiness?.connectedLabel);
  const sendReady = Boolean(sendReadiness?.canSend);
  const sendButtonLabel = sendLoading ? "Sending..." : sendReady ? "Approve and send now" : providerConnected ? "Send locked" : "Connect email in settings";
  const sendStatusTone: MailTone = sendReady ? "good" : providerConnected ? "watch" : "info";
  const recentSendNeedsAttention = sendHistory.filter((record) => record.needsAttention).length;
  const recentSentCount = sendHistory.filter((record) => record.status === "SENT").length;
  const recentApprovedOrQueuedCount = sendHistory.filter((record) => record.status === "APPROVED" || record.status === "SEND_QUEUED").length;
  const sendReviewSummary = persistenceSummary
    ? `${persistenceSummary.sentSends} sent · ${persistenceSummary.approvedSends + (persistenceSummary.queuedSends ?? 0)} approved/waiting · ${persistenceSummary.failedSends} need attention`
    : "Loading send review history.";
  const categoryCounts = useMemo(() => {
    return EMAILS.reduce<Record<MailCategory, number>>((acc, email) => {
      acc[email.category] = (acc[email.category] ?? 0) + 1;
      return acc;
    }, { Money: 0, Paperwork: 0, "Load update": 0, Driver: 0, Sales: 0 });
  }, []);

  function selectMessage(message: CoriMailMessage) {
    setSelectedId(message.id);
    setReplyMode("clear");
    setActionState("review");
    setSavedWorkAction("");
    setSendResult("");
    setSelectedWorkAction(message.workActions[0] ?? "task");
    setCommandReply(`CORI selected ${message.subject}. Best next step: ${message.nextStep}`);
  }

  function updateDraft(event: ChangeEvent<HTMLTextAreaElement>) {
    setDraftById((current) => ({
      ...current,
      [selectedMessage.id]: { body: event.target.value, savedAt: current[selectedMessage.id]?.savedAt ?? "Not saved yet" },
    }));
    setActionState("review");
  }

  function changeReplyMode(mode: ReplyMode) {
    setReplyMode(mode);
    setDraftById((current) => ({
      ...current,
      [selectedMessage.id]: {
        body: applyReplyMode(selectedMessage.suggestedReply, selectedMessage, mode),
        savedAt: current[selectedMessage.id]?.savedAt ?? "Not saved yet",
      },
    }));
    setActionState("review");
  }

  function runCommand(value = command) {
    setCommand(value);
    setCommandReply(buildCoriCommandReply(value, selectedMessage));
  }

  function saveDraft() {
    const savedAt = nowLabel();
    setDraftById((current) => ({ ...current, [selectedMessage.id]: { body: currentDraft, savedAt } }));
    setActionState("draft_saved");
    apiPost<{ draft: { id: string } }>("/api/cori-mail/persistence", {
      action: "draft",
      sourceMessageId: selectedMessage.id,
      sourceFromName: selectedMessage.fromName,
      sourceFromEmail: selectedMessage.fromEmail,
      toEmail: selectedMessage.replyTo,
      ccEmail: selectedMessage.cc,
      subject: selectedMessage.subject,
      body: currentDraft,
      tone: replyMode,
      status: "LOCAL_DRAFT",
      userInstruction: selectedMessage.userInstruction,
      coriPlainRead: selectedMessage.plainRead,
    })
      .then(() => refreshCoriMailMemory())
      .catch(() => undefined);
    setCommandReply("Draft saved in CORI Mail. Draft saved. Live send still needs connected email and final approval.");
  }

  function prepareProviderDraft() {
    const savedAt = nowLabel();
    setDraftById((current) => ({ ...current, [selectedMessage.id]: { body: currentDraft, savedAt } }));
    setActionState("mailbox_draft_ready");
    setCommandReply(providerConnected ? "Draft is ready for connected email review." : "Draft is ready. Connect email in Workspace Settings before CORI can place it in the mailbox.");
  }

  function markReadyToSend() {
    setActionState("send_ready");
    setSendResult("");
    apiPost<{ auditRecord: { id: string } }>("/api/cori-mail/persistence", {
      action: "send_audit",
      sourceMessageId: selectedMessage.id,
      toEmail: selectedMessage.replyTo,
      ccEmail: selectedMessage.cc,
      subject: selectedMessage.subject,
      body: currentDraft,
      status: "APPROVAL_REQUIRED",
      approvalNote: "User opened final send review from CORI Mail.",
    })
      .then(() => refreshCoriMailMemory())
      .catch(() => undefined);
    setCommandReply(sendReady ? "Ready to send. CORI will send only after your final click." : providerConnected ? "Ready for approval, but live sending is still locked." : "Ready for review. Sending stays locked until email is connected in Workspace Settings and the user approves.");
  }

  async function approveAndSend() {
    if (!sendReady || sendLoading) return;

    setSendLoading(true);
    setSendResult("");
    setActionState("send_ready");

    try {
      const data = await apiPost<{ result: CoriMailApprovedSendResult }>("/api/cori-mail/approved-send", {
        sourceMessageId: selectedMessage.id,
        toEmail: selectedMessage.replyTo,
        ccEmail: selectedMessage.cc,
        subject: selectedMessage.subject,
        body: currentDraft,
        approvalNote: "User approved final CORI Mail send from the review panel.",
      });
      setSendResult(data.result.message);
      setCommandReply(data.result.message);
      const readinessData = await apiGet<{ readiness: CoriMailApprovedSendReadiness }>("/api/cori-mail/approved-send");
      setSendReadiness(readinessData.readiness);
      await refreshCoriMailMemory();
    } catch (error: any) {
      const message = String(error?.message ?? "Email could not be sent.");
      setSendResult(message);
      setCommandReply(message);
    } finally {
      setSendLoading(false);
    }
  }

  function saveWorkAction() {
    const preview = buildWorkPreview(selectedMessage, selectedWorkAction);
    setSavedWorkAction(preview);
    apiPost<{ workAction: { id: string } }>("/api/cori-mail/persistence", {
      action: "work_action",
      sourceMessageId: selectedMessage.id,
      actionType: persistentWorkActionType(selectedWorkAction),
      title: WORK_ACTION_LABELS[selectedWorkAction],
      plainInstruction: preview,
      previewJson: { linkedRecord: selectedMessage.linkedRecord, whyItMatters: selectedMessage.whyItMatters },
    })
      .then(() => refreshCoriMailMemory())
      .catch(() => undefined);
    setCommandReply(`Work card prepared: ${preview}`);
  }

        const workPreview = buildWorkPreview(selectedMessage, selectedWorkAction);

  return (
    <div className="space-y-6">
      <section className="rounded-3xl 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 className="max-w-3xl">
            <div className="inline-flex rounded-full bg-sky-50 px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-sky-700">Ask CORI</div>
            <h1 className="mt-4 text-3xl font-semibold tracking-tight text-slate-950">CORI Mail</h1>
            <p className="mt-3 text-base leading-7 text-slate-600">
              CORI reads the important email first, explains what it means, drafts a simple answer, and can turn the message into dispatch work. Sending stays locked until the user approves.
            </p>
          </div>
          <div className={`rounded-2xl border p-4 ${toneClasses(sendStatusTone)}`}>
            <div className="text-sm font-semibold">Email connection</div>
            <p className="mt-1 max-w-sm text-sm leading-6">
              {sendReady
                ? "Connected. CORI can send only after the user approves the final message."
                : providerConnected
                  ? "Company email is connected, but live sending is still locked."
                  : "Email is not connected yet. Ask a workspace admin to connect email in Workspace Settings before live inbox reading or sending is turned on."}
            </p>
          </div>
        </div>
      </section>

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <MetricCard label="Needs answer now" value={String(urgentCount)} detail="Pickup, driver, and paperwork emails CORI would place first." tone="urgent" />
        <MetricCard label="Money follow-up" value={String(moneyCount)} detail="Payment or invoice messages that need clean tracking." tone="watch" />
        <MetricCard label="Ready replies" value={String(readyReplyCount)} detail="Suggested answers the user can edit before sending." tone="good" />
        <MetricCard label="Saved drafts" value={String(savedDraftCount)} detail="Replies saved while the user reviews email." tone="info" />
      </section>

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <MetricCard label="Email accounts" value={String(persistenceSummary?.emailProviderAccounts ?? 0)} detail="Company email accounts saved in Workspace Settings." tone="info" />
        <MetricCard label="Saved replies" value={String(persistenceSummary?.drafts ?? 0)} detail="Replies the user can come back to." tone="good" />
        <MetricCard label="Work cards" value={String(persistenceSummary?.workActions ?? 0)} detail="Emails prepared as load notes, tasks, or money follow-ups." tone="watch" />
        <MetricCard label="Send review" value={String(persistenceSummary?.sendAuditRecords ?? 0)} detail={`${persistenceSummary?.sentSends ?? 0} sent, ${(persistenceSummary?.approvedSends ?? 0) + (persistenceSummary?.queuedSends ?? 0)} approved/waiting, ${persistenceSummary?.needsAttentionSends ?? 0} need attention.`} tone="info" />
      </section>

      <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Email connection</div>
            <h2 className="mt-2 text-xl font-semibold text-slate-950">CORI Mail stays focused on email work.</h2>
            <p className="mt-2 text-sm leading-6 text-slate-600">
              Email account setup stays in Workspace Settings. This page stays focused on important email, suggested replies, work cards, and review before send.
            </p>
          </div>
          <Link href="/company/integrations" className="rounded-2xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white">Open Email Settings</Link>
        </div>
      </section>

      <section className="grid gap-4 lg:grid-cols-4">
        <BriefingLane label="Paperwork" detail="Rate cons, PODs, BOLs, invoices, and missing documents." count={categoryCounts.Paperwork} tone={categoryTone("Paperwork")} />
        <BriefingLane label="Money" detail="Open invoices, payment dates, disputes, and missing billing files." count={categoryCounts.Money} tone={categoryTone("Money")} />
        <BriefingLane label="Driver" detail="Driver updates that can create delay, detention, or delivery risk." count={categoryCounts.Driver} tone={categoryTone("Driver")} />
        <BriefingLane label="Sales" detail="Broker and shipper emails that can turn into load opportunities." count={categoryCounts.Sales} tone={categoryTone("Sales")} />
      </section>

      <section className="grid gap-6 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.35fr)]">
        <div className="space-y-4">
          <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
            <div className="flex items-center justify-between gap-3">
              <div>
                <h2 className="text-lg font-semibold text-slate-950">CORI email briefing</h2>
                <p className="mt-1 text-sm text-slate-500">Most important messages first. No inbox clutter.</p>
              </div>
              <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{EMAILS.length} shown</span>
            </div>

            <div className="mt-4 space-y-3">
              {EMAILS.map((email) => {
                const active = email.id === selectedMessage.id;
                return (
                  <button
                    key={email.id}
                    type="button"
                    onClick={() => selectMessage(email)}
                    className={`w-full rounded-2xl border p-4 text-left transition ${active ? "border-slate-900 bg-slate-950 text-white" : "border-slate-200 bg-white hover:border-slate-300 hover:bg-slate-50"}`}
                  >
                    <div className="flex flex-wrap items-center gap-2">
                      <span className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold ${active ? "border-white/20 bg-white/10 text-white" : toneClasses(email.tone)}`}>{toneLabel(email.tone)}</span>
                      <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-slate-100 text-slate-600"}`}>{email.category}</span>
                      <span className={`text-xs ${active ? "text-slate-300" : "text-slate-500"}`}>{email.receivedAt}</span>
                    </div>
                    <div className="mt-3 text-sm font-semibold">{email.subject}</div>
                    <div className={`mt-1 text-xs ${active ? "text-slate-300" : "text-slate-500"}`}>From: {email.fromName}</div>
                    <p className={`mt-3 text-sm leading-6 ${active ? "text-slate-200" : "text-slate-600"}`}>{email.plainRead}</p>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
            <h2 className="text-lg font-semibold text-slate-950">Ask CORI Mail</h2>
            <p className="mt-1 text-sm leading-6 text-slate-500">Use plain words. CORI turns the email into a safe next step.</p>
            <div className="mt-4 space-y-2">
              {QUICK_COMMANDS.map((item) => (
                <button key={item} type="button" onClick={() => runCommand(item)} className="w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-left text-sm text-slate-700 hover:border-slate-300 hover:bg-white">
                  {item}
                </button>
              ))}
            </div>
            <div className="mt-4 flex flex-col gap-2 sm:flex-row">
              <input
                value={command}
                onChange={(event) => setCommand(event.target.value)}
                placeholder="Tell CORI what to do with this email..."
                className="min-h-11 flex-1 rounded-2xl border border-slate-200 px-4 text-sm outline-none focus:border-slate-400"
              />
              <button type="button" onClick={() => runCommand()} className="rounded-2xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white">Ask</button>
            </div>
            <div className="mt-4 rounded-2xl border border-sky-200 bg-sky-50 p-4 text-sm leading-6 text-sky-800">{commandReply}</div>
          </div>
        </div>

        <div className="space-y-4">
          <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
            <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <div className="flex flex-wrap items-center gap-2">
                  <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${toneClasses(selectedMessage.tone)}`}>{toneLabel(selectedMessage.tone)}</span>
                  <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{selectedMessage.category}</span>
                </div>
                <h2 className="mt-4 text-2xl font-semibold tracking-tight text-slate-950">{selectedMessage.subject}</h2>
                <p className="mt-2 text-sm text-slate-500">From {selectedMessage.fromName} · {selectedMessage.fromEmail} · {selectedMessage.receivedAt}</p>
              </div>
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-700">
                <div className="font-semibold text-slate-950">Linked work</div>
                <div className="mt-1 leading-6">{selectedMessage.linkedRecord}</div>
                <div className="mt-3 flex flex-wrap gap-2">
                  {selectedMessage.loadHref ? <Link href={selectedMessage.loadHref} className="rounded-full border border-slate-200 bg-white px-3 py-1 text-xs font-semibold text-slate-700">Open load</Link> : null}
                  {selectedMessage.truckHref ? <Link href={selectedMessage.truckHref} className="rounded-full border border-slate-200 bg-white px-3 py-1 text-xs font-semibold text-slate-700">Open truck</Link> : null}
                </div>
              </div>
            </div>

            <div className="mt-6 grid gap-4 lg:grid-cols-3">
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                <div className="text-sm font-semibold text-slate-950">What this means</div>
                <p className="mt-2 text-sm leading-6 text-slate-600">{selectedMessage.plainRead}</p>
              </div>
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                <div className="text-sm font-semibold text-slate-950">Why it matters</div>
                <p className="mt-2 text-sm leading-6 text-slate-600">{selectedMessage.whyItMatters}</p>
              </div>
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                <div className="text-sm font-semibold text-slate-950">Best next step</div>
                <p className="mt-2 text-sm leading-6 text-slate-600">{selectedMessage.nextStep}</p>
              </div>
            </div>
          </div>

          <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <h2 className="text-xl font-semibold text-slate-950">Suggested answer</h2>
                <p className="mt-1 text-sm text-slate-500">Edit the message. CORI keeps the words simple and the action clear.</p>
              </div>
              <div className="flex flex-wrap gap-2">
                {(["clear", "friendly", "firm", "short"] as ReplyMode[]).map((mode) => (
                  <button
                    key={mode}
                    type="button"
                    onClick={() => changeReplyMode(mode)}
                    className={`rounded-full px-3 py-1.5 text-xs font-semibold capitalize ${replyMode === mode ? "bg-slate-950 text-white" : "border border-slate-200 bg-white text-slate-700"}`}
                  >
                    {mode}
                  </button>
                ))}
              </div>
            </div>

            <div className="mt-4 grid gap-3 sm:grid-cols-2">
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3 text-sm text-slate-700"><span className="font-semibold text-slate-950">To:</span> {selectedMessage.replyTo}</div>
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3 text-sm text-slate-700"><span className="font-semibold text-slate-950">CC:</span> {selectedMessage.cc || "No CC suggested"}</div>
            </div>

            <textarea
              value={currentDraft}
              onChange={updateDraft}
              rows={12}
              className="mt-4 w-full rounded-3xl border border-slate-200 bg-white p-4 text-sm leading-6 text-slate-800 outline-none focus:border-slate-400"
            />

            <div className="mt-4 grid gap-3 lg:grid-cols-2">
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600">
                <span className="font-semibold text-slate-950">User instruction CORI followed:</span> {selectedMessage.userInstruction}
              </div>
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600">
                <span className="font-semibold text-slate-950">Draft memory:</span> {currentDraftSavedAt}
              </div>
            </div>

            <div className="mt-5 rounded-3xl border border-slate-200 bg-slate-50 p-4">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Final approval</div>
                  <p className="mt-1 text-sm leading-6 text-slate-600">
                    {sendReadiness?.message ?? "Checking company email readiness."} {sendReadiness?.nextStep ?? "Review the message before sending."}
                  </p>
                  <p className="mt-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">
                    {actionState === "draft_saved"
                      ? "Draft saved"
                      : actionState === "mailbox_draft_ready"
                        ? "Draft ready"
                        : actionState === "send_ready"
                          ? "Send reviewed"
                          : "Review first"}
                  </p>
                  {sendResult ? <p className="mt-2 text-sm font-semibold text-slate-800">{sendResult}</p> : null}
                </div>
                <div className="flex flex-wrap gap-2">
                  <button type="button" onClick={saveDraft} className="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700">Save draft</button>
                  <button type="button" onClick={prepareProviderDraft} className="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700">Prepare mailbox draft</button>
                  <button type="button" onClick={markReadyToSend} className="rounded-2xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white">Review send</button>
                  <button type="button" onClick={approveAndSend} disabled={!sendReady || sendLoading} className="rounded-2xl bg-sky-600 px-4 py-3 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300 disabled:text-slate-600">
                    {sendButtonLabel}
                  </button>
                </div>
              </div>
            </div>
          </div>


          <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Approved-send history</div>
                <h2 className="mt-2 text-xl font-semibold text-slate-950">Send review and audit</h2>
                <p className="mt-1 text-sm leading-6 text-slate-500">See what was reviewed, approved, sent, or needs attention. Technical mail logs and provider settings stay out of CORI Mail.</p>
              </div>
              <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${toneClasses(recentSendNeedsAttention > 0 ? "urgent" : recentApprovedOrQueuedCount > 0 ? "watch" : "good")}`}>
                {sendReviewSummary}
              </span>
            </div>

            <div className="mt-4 grid gap-3 md:grid-cols-3">
              <SendReviewStatusCard label="Needs attention" value={String(persistenceSummary?.needsAttentionSends ?? recentSendNeedsAttention)} detail="Reviews still waiting for final approval or sends that failed." tone={recentSendNeedsAttention > 0 ? "urgent" : "info"} />
              <SendReviewStatusCard label="Approved / waiting" value={String((persistenceSummary?.approvedSends ?? 0) + (persistenceSummary?.queuedSends ?? recentApprovedOrQueuedCount))} detail="Final approvals saved or messages being sent." tone="watch" />
              <SendReviewStatusCard label="Sent" value={String(persistenceSummary?.sentSends ?? recentSentCount)} detail="Approved emails sent from company email." tone="good" />
            </div>

            <div className="mt-5 space-y-3">
              {sendHistory.length ? sendHistory.map((record) => (
                <div key={record.id} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                    <div>
                      <div className="flex flex-wrap items-center gap-2">
                        <span className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold ${toneClasses(record.statusTone)}`}>{record.statusLabel}</span>
                        <span className="text-xs font-semibold text-slate-400">{record.timingLabel}</span>
                      </div>
                      <div className="mt-3 text-sm font-semibold text-slate-950">{record.subject}</div>
                      <div className="mt-1 text-xs text-slate-500">To: {record.toEmail}{record.ccEmail ? ` · CC: ${record.ccEmail}` : ""}</div>
                    </div>
                    <div className="rounded-full bg-white px-3 py-1 text-xs font-semibold text-slate-600">Review record</div>
                  </div>
                  <p className="mt-3 text-sm leading-6 text-slate-600">{record.simpleDetail}</p>
                </div>
              )) : (
                <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600">
                  {emptySendHistoryMessage(sendReady, providerConnected)}
                </div>
              )}
            </div>
          </div>

          <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <h2 className="text-xl font-semibold text-slate-950">Turn email into work</h2>
                <p className="mt-1 text-sm leading-6 text-slate-500">CORI can convert an email into the right Dispatch Spot record so the inbox does not become a second dispatch board.</p>
              </div>
              <span className="rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-800">Review first</span>
            </div>

            <div className="mt-4 flex flex-wrap gap-2">
              {selectedMessage.workActions.map((action) => (
                <button
                  key={action}
                  type="button"
                  onClick={() => setSelectedWorkAction(action)}
                  className={`rounded-full px-3 py-1.5 text-xs font-semibold ${selectedWorkAction === action ? "bg-slate-950 text-white" : "border border-slate-200 bg-white text-slate-700"}`}
                >
                  {WORK_ACTION_LABELS[action]}
                </button>
              ))}
            </div>

            <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-700">
              <div className="font-semibold text-slate-950">Work card preview</div>
              <p className="mt-2">{workPreview}</p>
            </div>

            {savedWorkAction ? (
              <div className="mt-3 rounded-2xl border border-emerald-200 bg-emerald-50 p-4 text-sm leading-6 text-emerald-800">
                Prepared for save: {savedWorkAction}
              </div>
            ) : null}

            <div className="mt-4 flex flex-wrap gap-2">
              <button type="button" onClick={saveWorkAction} className="rounded-2xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white">Prepare work card</button>
              <button type="button" disabled className="rounded-2xl bg-slate-200 px-4 py-3 text-sm font-semibold text-slate-500">Save after review</button>
            </div>
          </div>

          <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
            <h2 className="text-xl font-semibold text-slate-950">How CORI Mail keeps email safe</h2>
            <div className="mt-4 grid gap-3 md:grid-cols-2">
              {[
                ["Read with purpose", "CORI groups email by load, truck, driver, broker, money, and paperwork."],
                ["Draft first", "CORI prepares the answer and shows why it chose that answer."],
                ["User controls send", "No real email leaves the connected company email account until the user approves the final message."],
                ["Work memory", "Next steps can become load notes, follow-up tasks, billing notes, driver updates, or sales leads."],
                ["Settings stay clean", "Email connection stays in Workspace Settings so CORI Mail remains easy to use."],
              ].map(([label, body]) => (
                <div key={label} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="text-sm font-semibold text-slate-950">{label}</div>
                  <p className="mt-2 text-sm leading-6 text-slate-600">{body}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
