"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";
import type { Broker, Driver, Shipper } from "@/types";
import type { CallCopilotLaunchContext } from "@/components/cori/call-copilot-support";
import { buildMockSessionSummary, useCoriMockRuntime, useCoriSharedDtmfState } from "@/lib/cori-live-runtime";
import { buildProviderStartResult, type CoriBridgePhase, type CoriTransportMode } from "@/lib/cori-provider-transport";

type ContactRole = "BROKER" | "DRIVER" | "SHIPPER";
type CallPurpose =
  | "NEGOTIATE_RATE"
  | "CHECK_LOAD_DETAILS"
  | "CONFIRM_PICKUP"
  | "CONFIRM_DELIVERY"
  | "ETA_UPDATE"
  | "PROBLEM_RESOLUTION"
  | "CALLBACK"
  | "GENERAL";

type CallState = "READY" | "DIALING" | "CONNECTED" | "ENDED";
type QuickOutcome = "NONE" | "NO_ANSWER" | "CALLBACK" | "COUNTERED" | "BOOKED" | "PASS";

type ContactOption = {
  id: string;
  role: ContactRole;
  name: string;
  phone: string;
  companyLabel: string;
  searchText: string;
  truckLabel?: string;
};

type ParsedFacts = {
  pickup?: string;
  delivery?: string;
  miles?: number;
  offer?: number;
  weight?: number;
  callbackAt?: string;
  brokerSaid?: string;
  equipment?: string;
  pickupTime?: string;
  deliveryTime?: string;
  objection?: string;
  resultSignal?: "CALLBACK" | "BOOKED" | "PASS" | "COUNTERED";
};

type IntelligenceSnapshot = {
  hiddenSignals: string[];
  pricingReasons: string[];
  accessorialPrompts: string[];
  routeRiskLevel: "LOW" | "MED" | "HIGH";
};

function normalize(text: string) {
  return text.toLowerCase().replace(/\s+/g, " ").trim();
}

function roleLabel(role: ContactRole) {
  return role === "BROKER" ? "Broker" : role === "DRIVER" ? "Driver" : "Shipper";
}

function purposeLabel(purpose: CallPurpose) {
  return (

    {
      NEGOTIATE_RATE: "Negotiate rate",
      CHECK_LOAD_DETAILS: "Check load details",
      CONFIRM_PICKUP: "Confirm pickup",
      CONFIRM_DELIVERY: "Confirm delivery",
      ETA_UPDATE: "ETA update",
      PROBLEM_RESOLUTION: "Problem resolution",
      CALLBACK: "Callback",
      GENERAL: "General call",
    } as const
  )[purpose];
}

function purposeFromString(value?: string | null): CallPurpose {
  const normalized = normalize(value ?? "").replace(/\s+/g, "_").toUpperCase();
  const allowed: CallPurpose[] = ["NEGOTIATE_RATE", "CHECK_LOAD_DETAILS", "CONFIRM_PICKUP", "CONFIRM_DELIVERY", "ETA_UPDATE", "PROBLEM_RESOLUTION", "CALLBACK", "GENERAL"];
  return allowed.includes(normalized as CallPurpose) ? (normalized as CallPurpose) : "NEGOTIATE_RATE";
}

function compactMoney(value?: string | number | null, withPennies = false) {
  const parsed = typeof value === "number" ? value : Number(value ?? "");
  if (!Number.isFinite(parsed)) return "—";
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: withPennies ? 2 : 0,
    maximumFractionDigits: withPennies ? 2 : 0,
  }).format(parsed);
}

function formatNumber(value?: number | null) {
  if (!Number.isFinite(value ?? NaN)) return "—";
  return new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(value as number);
}

function parseMoney(value?: string | null) {
  const parsed = Number(value ?? "");
  return Number.isFinite(parsed) ? parsed : undefined;
}

function parseLane(lane?: string | null) {
  if (!lane) return {} as ParsedFacts;
  const parts = lane.split(/→|->| to /i).map((part) => part.trim()).filter(Boolean);
  return {
    pickup: parts[0],
    delivery: parts[1],
  };
}

function parseFactsFromNote(note: string, lane?: string | null): ParsedFacts {
  const text = note.trim();
  const base = parseLane(lane);
  if (!text) return base;

  const moneyMatches = [...text.matchAll(/\$\s*([\d,.]+)/g)].map((match) => Number(match[1].replace(/,/g, ""))).filter(Number.isFinite);
  const milesMatch = text.match(/(\d{2,5})\s*(?:loaded\s*)?(?:mi|miles)/i);
  const weightMatch = text.match(/(\d{4,6})\s*(?:lb|lbs|pounds)/i);
  const callbackMatch = text.match(/(?:call\s*me\s*back|callback|circle\s*back|check\s*back)\s*(?:at|for|around|after)?\s*([0-9]{1,2}(?::[0-9]{2})?\s*(?:am|pm)?)/i);
  const pickupMatch = text.match(/(?:pick\s*up|pickup|pu)[:\-]?\s*([A-Za-z .'-]+?,\s*[A-Za-z]{2})/i);
  const deliveryMatch = text.match(/(?:drop|delivery|del)[:\-]?\s*([A-Za-z .'-]+?,\s*[A-Za-z]{2})/i);
  const pickupTimeMatch = text.match(/(?:pickup time|pu time|pick up at|pickup at)[:\-]?\s*([A-Za-z0-9: ]+(?:am|pm)?)/i);
  const deliveryTimeMatch = text.match(/(?:delivery time|del time|deliver at|delivery at)[:\-]?\s*([A-Za-z0-9: ]+(?:am|pm)?)/i);
  const equipmentMatch = text.match(/(?:van|reefer|flatbed|step deck|stepdeck|hotshot|power only|conestoga)/i);

  const objection = /(too high|customer won't pay|can'?t do that|too much|not enough|best we can do|that won'?t work)/i.test(text)
    ? text
    : undefined;

  let resultSignal: ParsedFacts["resultSignal"];
  if (/(send (?:the )?rate con|send rate confirmation|we got it|book it|you'?re covered|covered it|booked)/i.test(text)) {
    resultSignal = "BOOKED";
  } else if (/(call me back|callback|circle back|check back|let me check|let me talk to my customer)/i.test(text)) {
    resultSignal = "CALLBACK";
  } else if (/(pass|not interested|we're out|can'?t use it|won't work|no thanks)/i.test(text)) {
    resultSignal = "PASS";
  } else if (/(we can maybe do|we can do|come up to|counter|best we can do is|i can move to)/i.test(text) && moneyMatches.length) {
    resultSignal = "COUNTERED";
  }

  return {
    ...base,
    pickup: pickupMatch?.[1]?.trim() || base.pickup,
    delivery: deliveryMatch?.[1]?.trim() || base.delivery,
    miles: milesMatch ? Number(milesMatch[1]) : undefined,
    offer: moneyMatches.length ? moneyMatches[moneyMatches.length - 1] : undefined,
    weight: weightMatch ? Number(weightMatch[1]) : undefined,
    callbackAt: callbackMatch?.[1]?.trim(),
    equipment: equipmentMatch?.[0]?.trim(),
    pickupTime: pickupTimeMatch?.[1]?.trim(),
    deliveryTime: deliveryTimeMatch?.[1]?.trim(),
    objection,
    resultSignal,
    brokerSaid: text || undefined,
  };
}

function buildBrokerOptions(brokers: Broker[]): ContactOption[] {
  return brokers
    .filter((broker) => broker.phone)
    .map((broker) => ({
      id: broker.id,
      role: "BROKER" as const,
      name: broker.contactName?.trim() || broker.name,
      phone: broker.phone ?? "",
      companyLabel: broker.name,
      searchText: normalize(`${broker.name} ${broker.contactName ?? ""} ${broker.phone ?? ""}`),
    }));
}

function buildDriverOptions(drivers: Driver[]): ContactOption[] {
  return drivers
    .filter((driver) => driver.phone)
    .map((driver) => {
      const name = `${driver.firstName} ${driver.lastName ?? ""}`.trim();
      return {
        id: driver.id,
        role: "DRIVER" as const,
        name,
        phone: driver.phone ?? "",
        companyLabel: driver.companyName ?? "Assigned driver",
        truckLabel: driver.truck?.truckNumber ? `Truck ${driver.truck.truckNumber}` : undefined,
        searchText: normalize(`${name} ${driver.companyName ?? ""} ${driver.phone ?? ""} ${driver.truck?.truckNumber ?? ""}`),
      };
    });
}

function buildShipperOptions(shippers: Shipper[]): ContactOption[] {
  return shippers
    .filter((shipper) => shipper.phone)
    .map((shipper) => ({
      id: shipper.id,
      role: "SHIPPER" as const,
      name: shipper.contactName?.trim() || shipper.companyName,
      phone: shipper.phone ?? "",
      companyLabel: shipper.companyName,
      searchText: normalize(`${shipper.companyName} ${shipper.contactName ?? ""} ${shipper.phone ?? ""}`),
    }));
}

function buildIntelligenceSnapshot(selectedContact: ContactOption | null, purpose: CallPurpose, context: CallCopilotLaunchContext, parsedFacts: ParsedFacts, outcome: QuickOutcome): IntelligenceSnapshot {
  const laneText = normalize(`${context.laneLabel ?? ""} ${parsedFacts.pickup ?? ""} ${parsedFacts.delivery ?? ""} ${parsedFacts.brokerSaid ?? ""}`);
  const ask = parseMoney(context.targetRate);
  const floor = parseMoney(context.floorRate);
  const hiddenSignals: string[] = [];
  const pricingReasons: string[] = [];
  const accessorialPrompts: string[] = [];
  let riskScore = 0;

  const mountainRoute = /(denver|salt lake|asheville|boise|montana|wyoming|colorado|mountain|pass|appalachian|rockies)/i.test(laneText);
  const weatherRisk = /(blizzard|snow|ice|storm|closed road|closure|flood|wind|weather)/i.test(laneText);
  const delayRisk = /(construction|maintenance|road work|lane closure|traffic|accident|backup|congestion)/i.test(laneText);
  const heavyLoad = Boolean(parsedFacts.weight && parsedFacts.weight >= 43000);
  const permitRisk = Boolean(parsedFacts.weight && parsedFacts.weight >= 47000);
  const afterHours = /(8|9|10|11)\s*pm|12\s*am|after hours|overnight/i.test(parsedFacts.brokerSaid ?? "");
  const weekendTiming = /(sat|saturday|sun|sunday|weekend)/i.test(parsedFacts.brokerSaid ?? "");

  if (mountainRoute) {
    hiddenSignals.push("Mountain route");
    pricingReasons.push("mountain terrain");
    riskScore += 2;
  }
  if (weatherRisk) {
    hiddenSignals.push("Weather risk");
    pricingReasons.push("weather exposure");
    riskScore += 2;
  }
  if (delayRisk) {
    hiddenSignals.push("Delay risk");
    pricingReasons.push("traffic / road work");
    riskScore += 1;
  }
  if (heavyLoad) {
    hiddenSignals.push("Heavy load");
    pricingReasons.push("heavy weight");
    riskScore += 1;
  }
  if (permitRisk) {
    hiddenSignals.push("Permit risk");
    accessorialPrompts.push("Ask permit coverage");
    riskScore += 1;
  }
  if (afterHours) {
    hiddenSignals.push("After-hours risk");
    accessorialPrompts.push("Ask after-hours pay");
    riskScore += 1;
  }
  if (weekendTiming) {
    hiddenSignals.push("Weekend timing");
    accessorialPrompts.push("Ask layover");
    riskScore += 1;
  }

  if (selectedContact?.role === "BROKER" && purpose === "NEGOTIATE_RATE") {
    accessorialPrompts.push("Ask detention");
    if (heavyLoad) accessorialPrompts.push("Ask heavy-load pay");
  }

  if (parsedFacts.offer && floor && parsedFacts.offer < floor) {
    hiddenSignals.push("Below floor");
    pricingReasons.push("offer below truck floor");
  } else if (parsedFacts.offer && ask && parsedFacts.offer < ask) {
    hiddenSignals.push("Below ask");
    pricingReasons.push("offer below target");
  }

  const effectiveOutcome = parsedFacts.resultSignal === "BOOKED" ? "BOOKED" : parsedFacts.resultSignal === "PASS" ? "PASS" : parsedFacts.resultSignal === "CALLBACK" ? "CALLBACK" : outcome;

  if (effectiveOutcome === "CALLBACK") hiddenSignals.push(parsedFacts.callbackAt ? `Callback ${parsedFacts.callbackAt}` : "Hold callback time");
  if (effectiveOutcome === "PASS") hiddenSignals.push("Work backup option");
  if (parsedFacts.objection) hiddenSignals.push("Broker pushback");

  const routeRiskLevel = riskScore >= 4 ? "HIGH" : riskScore >= 2 ? "MED" : "LOW";
  return {
    hiddenSignals: hiddenSignals.slice(0, 6),
    pricingReasons: pricingReasons.slice(0, 3),
    accessorialPrompts: [...new Set(accessorialPrompts)].slice(0, 3),
    routeRiskLevel,
  };
}

function buildHiddenReality(selectedContact: ContactOption | null, purpose: CallPurpose, context: CallCopilotLaunchContext, parsedFacts: ParsedFacts, outcome: QuickOutcome) {
  if (!selectedContact) {
    return ["Pick a contact", "CORI will load short risk checks here", "Call stays idle until you press Call"];
  }

  const snapshot = buildIntelligenceSnapshot(selectedContact, purpose, context, parsedFacts, outcome);
  const tags = [...snapshot.hiddenSignals, ...snapshot.accessorialPrompts];
  if (snapshot.routeRiskLevel !== "LOW") {
    tags.unshift(`Route risk: ${snapshot.routeRiskLevel}`);
  }
  return tags.length ? tags.slice(0, 6) : ["No extra route risk yet", "Keep the call short", "Only ask what changes the decision"];
}

function buildAdvice(selectedContact: ContactOption | null, purpose: CallPurpose, context: CallCopilotLaunchContext, parsedFacts: ParsedFacts, outcome: QuickOutcome) {
  const ask = parseMoney(context.targetRate);
  const floor = parseMoney(context.floorRate);
  const miles = parsedFacts.miles;
  const offer = parsedFacts.offer;
  const rpm = offer && miles ? offer / miles : undefined;
  const effectiveOutcome = parsedFacts.resultSignal === "BOOKED"
    ? "BOOKED"
    : parsedFacts.resultSignal === "PASS"
      ? "PASS"
      : parsedFacts.resultSignal === "CALLBACK"
        ? "CALLBACK"
        : parsedFacts.resultSignal === "COUNTERED"
          ? "COUNTERED"
          : outcome;
  const snapshot = buildIntelligenceSnapshot(selectedContact, purpose, context, parsedFacts, effectiveOutcome === "NONE" ? "NONE" : effectiveOutcome);
  const reasonSuffix = snapshot.pricingReasons.length ? ` Reason: ${snapshot.pricingReasons.join(" + ")}.` : "";

  if (!selectedContact) {
    return {
      headline: "Pick who to call",
      body: "Search broker, driver, or shipper. The dialer will fill the number and wait for your call.",
      speakLine: "Say: Hi, I’m calling about this move.",
      metrics: [
        { label: "Purpose", value: purposeLabel(purpose) },
        { label: "Ask", value: compactMoney(ask) },
        { label: "Floor", value: compactMoney(floor) },
      ],
    };
  }

  if (outcome === "NO_ANSWER") {
    return {
      headline: "No answer",
      body: "Log it fast and move to callback or the next broker.",
      speakLine: "Say: Left voicemail. Call back later.",
      metrics: [
        { label: "Next move", value: "Callback" },
        { label: "Lane", value: context.laneLabel || "—" },
        { label: "Truck", value: context.truckLabel || selectedContact.truckLabel || "—" },
      ],
    };
  }

  if (effectiveOutcome === "BOOKED") {
    return {
      headline: "Booked",
      body: `Get the rate con, pickup details, and any special requirements before you move on.${reasonSuffix}`,
      speakLine: "Say: Great, send the rate con and full pickup details now.",
      metrics: [
        { label: "Booked", value: compactMoney(offer ?? ask) },
        { label: "Miles", value: miles ? formatNumber(miles) : "—" },
        { label: "Risk", value: snapshot.routeRiskLevel },
      ],
    };
  }

  if (selectedContact.role === "BROKER" && purpose === "NEGOTIATE_RATE") {
    if (effectiveOutcome === "PASS") {
      return {
        headline: "Pass and move on",
        body: `The lane is not workable at the current terms. Protect the truck by moving to the next option.${reasonSuffix}`,
        speakLine: "Say: Understood. We’ll pass on this one.",
        metrics: [
          { label: "Offer", value: compactMoney(offer) },
          { label: "Floor", value: compactMoney(floor) },
          { label: "Risk", value: snapshot.routeRiskLevel },
        ],
      };
    }

    if (effectiveOutcome === "COUNTERED" && offer) {
      return {
        headline: "Counter in play",
        body: `The broker moved. Hold the floor and close only if the rate clears the truck.${reasonSuffix}`,
        speakLine: `Say: We still need ${compactMoney(floor ?? ask ?? offer)} on this one.`,
        metrics: [
          { label: "Offer", value: compactMoney(offer) },
          { label: "RPM", value: rpm ? compactMoney(rpm, true) : "—" },
          { label: "Risk", value: snapshot.routeRiskLevel },
        ],
      };
    }

    if (offer && floor && offer < floor) {
      return {
        headline: "Too low",
        body: `The offer does not clear the truck floor. Counter higher or pass.${reasonSuffix}`,
        speakLine: `Say: Too low for this truck. We can do ${compactMoney(floor)} minimum.`,
        metrics: [
          { label: "Offer", value: compactMoney(offer) },
          { label: "RPM", value: rpm ? compactMoney(rpm, true) : "—" },
          { label: "Reason", value: snapshot.pricingReasons[0] || "Below floor" },
        ],
      };
    }

    if (offer && ask && offer < ask) {
      return {
        headline: "Counter higher",
        body: `The offer may work only if the broker comes up. Hold your ask and be ready to settle above the floor.${reasonSuffix}`,
        speakLine: `Say: We need ${compactMoney(ask)} on this one.`,
        metrics: [
          { label: "Offer", value: compactMoney(offer) },
          { label: "RPM", value: rpm ? compactMoney(rpm, true) : "—" },
          { label: "Risk", value: snapshot.routeRiskLevel },
        ],
      };
    }

    if (offer && ask && offer >= ask) {
      return {
        headline: "Work to close it",
        body: `The offer is in range. Confirm the details that can still hurt the truck.${reasonSuffix}`,
        speakLine: snapshot.accessorialPrompts[0]
          ? `Say: Good. Confirm details and ${snapshot.accessorialPrompts[0].replace(/^Ask /i, "ask ")}.`
          : "Say: Good. Confirm pickup time, delivery time, and detention terms.",
        metrics: [
          { label: "Offer", value: compactMoney(offer) },
          { label: "RPM", value: rpm ? compactMoney(rpm, true) : "—" },
          { label: "Risk", value: snapshot.routeRiskLevel },
        ],
      };
    }

    return {
      headline: "Get lane, miles, and offer first",
      body: `Keep it short. Confirm pickup, drop, miles, and the broker’s best offer before you counter.${reasonSuffix}`,
      speakLine: "Say: What are pickup, delivery, loaded miles, and your best rate on this one?",
      metrics: [
        { label: "Ask", value: compactMoney(ask) },
        { label: "Floor", value: compactMoney(floor) },
        { label: "Risk", value: snapshot.routeRiskLevel },
      ],
    };
  }

  if (selectedContact.role === "DRIVER") {
    return {
      headline: "Get location and next risk quickly",
      body: `Confirm where the driver is, what changed, and whether pickup or delivery timing is at risk.${reasonSuffix}`,
      speakLine: "Say: Where are you now, what changed, and what do you need from me next?",
      metrics: [
        { label: "Purpose", value: purposeLabel(purpose) },
        { label: "Truck", value: context.truckLabel || selectedContact.truckLabel || "—" },
        { label: "Risk", value: snapshot.routeRiskLevel },
      ],
    };
  }

  return {
    headline: "Confirm what changes service",
    body: `Keep the call focused on timing, truck status, and the one thing that changes the load decision.${reasonSuffix}`,
    speakLine: "Say: I’m calling with a quick update on this move.",
    metrics: [
      { label: "Purpose", value: purposeLabel(purpose) },
      { label: "Truck", value: context.truckLabel || selectedContact.truckLabel || "—" },
      { label: "Risk", value: snapshot.routeRiskLevel },
    ],
  };
}

function buildLiveFacts(selectedContact: ContactOption | null, purpose: CallPurpose, callState: CallState, context: CallCopilotLaunchContext, parsedFacts: ParsedFacts) {
  const laneFacts = parseLane(context.laneLabel);
  const pickup = parsedFacts.pickup || laneFacts.pickup;
  const delivery = parsedFacts.delivery || laneFacts.delivery;

  return [
    { label: "Contact", value: selectedContact ? `${selectedContact.name} · ${roleLabel(selectedContact.role)}` : "Not selected" },
    { label: "Phone", value: selectedContact?.phone || context.phone || "—" },
    { label: "Purpose", value: purposeLabel(purpose) },
    { label: "Pick up", value: pickup || "—" },
    { label: "Drop", value: delivery || "—" },
    { label: "Miles", value: parsedFacts.miles ? formatNumber(parsedFacts.miles) : "—" },
    { label: "Offer", value: parsedFacts.offer ? compactMoney(parsedFacts.offer) : "—" },
    { label: "Weight", value: parsedFacts.weight ? `${formatNumber(parsedFacts.weight)} lb` : "—" },
    { label: "Equip", value: parsedFacts.equipment || "—" },
    { label: "PU time", value: parsedFacts.pickupTime || "—" },
    { label: "DEL time", value: parsedFacts.deliveryTime || "—" },
    { label: "Callback", value: parsedFacts.callbackAt || "—" },
    { label: "Signal", value: parsedFacts.resultSignal || "—" },
    { label: "Call state", value: callState === "CONNECTED" ? "Listening live" : callState === "DIALING" ? "Dialing" : callState === "ENDED" ? "Call ended" : "Ready" },
  ];
}

function ReviewStat({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white px-3 py-3">
      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">{label}</div>
      <div className="mt-1 text-sm font-semibold text-slate-900">{value}</div>
    </div>
  );
}

function RuntimeReviewRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-start justify-between gap-3 rounded-2xl border border-slate-200 bg-white px-3 py-3">
      <div className="text-sm font-medium text-slate-700">{label}</div>
      <div className="max-w-[65%] text-right text-sm text-slate-900">{value}</div>
    </div>
  );
}

function FactRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-3 border-b border-slate-100 py-1.5 last:border-b-0">
      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">{label}</div>
      <div className="text-right text-sm font-medium text-slate-800">{value}</div>
    </div>
  );
}

function HelpDot({ label }: { label: string }) {
  return (
    <span className="group relative inline-flex align-middle">
      <button
        type="button"
        aria-label={label}
        className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-sky-200 bg-sky-50 text-sm font-bold text-sky-700 shadow-sm transition hover:border-sky-300 hover:bg-white focus:outline-none focus:ring-2 focus:ring-sky-300"
      >
        ?
      </button>
      <span className="pointer-events-none absolute left-1/2 top-full z-50 mt-2 hidden w-72 -translate-x-1/2 rounded-2xl border border-slate-200 bg-white px-4 py-3 text-left text-sm font-medium leading-6 text-slate-700 shadow-xl group-hover:block group-focus-within:block">
        {label}
      </span>
    </span>
  );
}

function KeypadButton({ label, sublabel, onClick }: { label: string; sublabel?: string; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="flex h-14 flex-col items-center justify-center rounded-2xl border border-slate-200 bg-white text-slate-900 shadow-sm transition hover:border-sky-300 hover:bg-sky-50"
    >
      <span className="text-base font-semibold">{label}</span>
      {sublabel ? <span className="mt-0.5 text-[10px] uppercase tracking-[0.16em] text-slate-400">{sublabel}</span> : <span className="mt-0.5 text-[10px] text-transparent">•</span>}
    </button>
  );
}

export function CallCopilotShell({ variant, launchContext, onClose }: { variant: "page" | "popup"; launchContext?: CallCopilotLaunchContext; onClose?: () => void }) {
  const [brokers, setBrokers] = useState<Broker[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [shippers, setShippers] = useState<Shipper[]>([]);
  const [search, setSearch] = useState(launchContext?.contactName ?? "");
  const [selectedContact, setSelectedContact] = useState<ContactOption | null>(null);
  const [purpose, setPurpose] = useState<CallPurpose>(purposeFromString(launchContext?.purpose));
  const [callState, setCallState] = useState<CallState>("READY");
  const [callNote, setCallNote] = useState("");
  const [quickOutcome, setQuickOutcome] = useState<QuickOutcome>("NONE");
  const [error, setError] = useState<string | null>(null);
  const [transportMode, setTransportMode] = useState<CoriTransportMode>("MOCK");
  const [bridgePhase, setBridgePhase] = useState<CoriBridgePhase>("NOT_READY");
  const [startLabel, setStartLabel] = useState("Waiting for call start");
  const [fallbackLabel, setFallbackLabel] = useState("No fallback used");
  const [transcriptMode, setTranscriptMode] = useState("Call notes are ready when the call starts");
  const [eventFlowSummary, setEventFlowSummary] = useState("Call helper is ready when the session starts.");
  const [searchOpen, setSearchOpen] = useState(false);
  const [keypadOpen, setKeypadOpen] = useState(false);
  const [keypadDigits, setKeypadDigits] = useState("");
  const [keypadStatus, setKeypadStatus] = useState("Use the keypad only when the phone asks for a number or extension.");
  const [keypadDelivery, setKeypadDelivery] = useState("Digits stay in the dialer until the call can send them.");
  const [keypadLastTone, setKeypadLastTone] = useState<string | null>(null);
  const [keypadDeliveryMode, setKeypadDeliveryMode] = useState<"IDLE" | "QUEUED" | "SENT" | "BLOCKED">("IDLE");
  const [toneQueue, setToneQueue] = useState<string[]>([]);
  const [toneSendBusy, setToneSendBusy] = useState(false);
  const [rapidBlockedCount, setRapidBlockedCount] = useState(0);
  const [lastBlockedReason, setLastBlockedReason] = useState<string | null>(null);
  const [pendingRetryDigit, setPendingRetryDigit] = useState<string | null>(null);
  const [retryHint, setRetryHint] = useState("Wait for the call to connect, then CORI can send queued keypad digits.");
  const [sendRepeatBlocked, setSendRepeatBlocked] = useState(0);
  const lastToneAttemptRef = useRef<{ digit: string; at: number } | null>(null);
  const wrapperRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let cancelled = false;
    async function loadContacts() {
      try {
        const [brokerResponse, driverResponse, shipperResponse] = await Promise.all([
          apiGet<Broker[] | { brokers?: Broker[] }>("/api/brokers"),
          apiGet<Driver[] | { drivers?: Driver[] }>("/api/drivers"),
          apiGet<Shipper[] | { shippers?: Shipper[] }>("/api/shippers"),
        ]);
        const brokerList = Array.isArray(brokerResponse) ? brokerResponse : brokerResponse?.brokers ?? [];
        const driverList = Array.isArray(driverResponse) ? driverResponse : driverResponse?.drivers ?? [];
        const shipperList = Array.isArray(shipperResponse) ? shipperResponse : shipperResponse?.shippers ?? [];
        if (!cancelled) {
          setBrokers(brokerList);
          setDrivers(driverList);
          setShippers(shipperList);
        }
      } catch (caught) {
        if (!cancelled) {
          setError(caught instanceof Error ? caught.message : "Could not load phone book.");
        }
      }
    }
    void loadContacts();
    return () => {
      cancelled = true;
    };
  }, []);

  const options = useMemo(() => [...buildBrokerOptions(brokers), ...buildDriverOptions(drivers), ...buildShipperOptions(shippers)], [brokers, drivers, shippers]);

  useEffect(() => {
    if (!launchContext?.contactType || !launchContext?.phone) return;
    const role: ContactRole = normalize(launchContext.contactType).includes("driver")
      ? "DRIVER"
      : normalize(launchContext.contactType).includes("shipper")
        ? "SHIPPER"
        : "BROKER";
    setSelectedContact((current) => current ?? {
      id: launchContext.contactId ?? `context-${role}-${launchContext.phone}`,
      role,
      name: launchContext.contactName ?? "Selected contact",
      phone: launchContext.phone ?? "",
      companyLabel: launchContext.companyLabel ?? "",
      searchText: normalize(`${launchContext.contactName ?? ""} ${launchContext.phone ?? ""}`),
      truckLabel: launchContext.truckLabel,
    });
  }, [launchContext]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (!wrapperRef.current || wrapperRef.current.contains(event.target as Node)) return;
      setSearchOpen(false);
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const filteredOptions = useMemo(() => {
    const query = normalize(search);
    if (!query) return options.slice(0, 8);
    return options.filter((option) => option.searchText.includes(query)).slice(0, 8);
  }, [options, search]);

  const parsedFacts = useMemo(() => parseFactsFromNote(callNote, launchContext?.laneLabel), [callNote, launchContext]);
  const liveFacts = useMemo(() => buildLiveFacts(selectedContact, purpose, callState, launchContext ?? {}, parsedFacts), [selectedContact, purpose, callState, launchContext, parsedFacts]);
  const hiddenReality = useMemo(() => buildHiddenReality(selectedContact, purpose, launchContext ?? {}, parsedFacts, quickOutcome), [selectedContact, purpose, launchContext, parsedFacts, quickOutcome]);
  const advice = useMemo(() => buildAdvice(selectedContact, purpose, launchContext ?? {}, parsedFacts, quickOutcome), [selectedContact, purpose, launchContext, parsedFacts, quickOutcome]);

  const listeningPlanCards = useMemo(() => ([
    {
      title: "Event flow",
      text: "Policy check → notice check → call connects → listening starts → facts update → advice refreshes → save only what is ready.",
    },
    {
      title: "Fact life",
      text: "Facts can be heard, become stronger, get replaced, or be dropped. CORI should show the best current value, not every raw fragment.",
    },
    {
      title: "UI use",
      text: "The page and popup should read one listening truth. Operators should mainly see posture, best facts, advice change, and save readiness.",
    },
    {
      title: "Privacy gate",
      text: "Live listening must stay blocked unless workspace policy, notice rules, and session readiness all say yes.",
    },
  ]), []);

  const resultSignal = parsedFacts.resultSignal ?? (quickOutcome === "CALLBACK" ? "CALLBACK" : quickOutcome === "BOOKED" ? "BOOKED" : quickOutcome === "PASS" ? "PASS" : quickOutcome === "COUNTERED" ? "COUNTERED" : null);

  const runtimeSnapshot = useCoriMockRuntime({
    callState,
    selectedContactName: selectedContact?.name,
    selectedPhone: selectedContact?.phone || launchContext?.phone,
    laneLabel: launchContext?.laneLabel,
    targetRate: launchContext?.targetRate,
    parsedOffer: parsedFacts.offer ?? parseMoney(launchContext?.targetRate),
    callbackAt: parsedFacts.callbackAt,
    resultSignal,
    objection: parsedFacts.objection,
    quickOutcome,
    transportMode,
    bridgePhase,
    startLabel,
    fallbackLabel,
    transcriptMode,
    eventFlowSummary,
    noteText: callNote,
  }, variant);

  const runtimeContract = runtimeSnapshot.contract;
  const runtimeSummary = useMemo(() => buildMockSessionSummary(runtimeSnapshot), [runtimeSnapshot]);
  const sharedDtmfState = useCoriSharedDtmfState({
    digits: keypadDigits,
    status: keypadStatus,
    delivery: keypadDelivery,
    lastTone: keypadLastTone,
    deliveryMode: keypadDeliveryMode,
    queuedCount: toneQueue.length,
    rapidBlocked: rapidBlockedCount,
    lastBlockedReason,
    nextAction: retryHint,
    retryAvailable: Boolean(pendingRetryDigit),
    pendingRetryDigit,
  }, variant);

  function handleSelect(option: ContactOption) {
    setSelectedContact(option);
    setSearch(option.name);
    setSearchOpen(false);
    setCallState("READY");
    setQuickOutcome("NONE");
    setTransportMode("MOCK");
    setBridgePhase("NOT_READY");
    setStartLabel("Waiting for call start");
    setFallbackLabel("No fallback used");
    setTranscriptMode("Call notes are ready when the call starts");
    setEventFlowSummary("Call helper is ready when the session starts.");
  }

  async function handleCallPress() {
    if (!selectedContact) return;
    if (callState === "CONNECTED") {
      setBridgePhase(transportMode === "PROVIDER" ? "PROVIDER_CLOSING" : bridgePhase);
      setCallState("ENDED");
      window.setTimeout(() => setBridgePhase(transportMode === "PROVIDER" ? "PROVIDER_CLOSED" : "MOCK_FALLBACK"), 300);
      return;
    }

    setBridgePhase("GUARDED_START");
    setCallState("DIALING");

    try {
      const body = {
        targetPhone: selectedContact.phone,
        dialerStage: "READY",
        consentCaptured: true,
      };
      const liveSession = await apiPost<any>("/api/voice/twilio/live-session", body);
      const providerConnect = await apiPost<any>("/api/voice/twilio/provider-connect", body);
      const start = buildProviderStartResult({ liveSession, providerConnect });
      setTransportMode(start.mode);
      setBridgePhase(start.bridgePhase);
      setStartLabel(start.startLabel);
      setFallbackLabel(start.fallbackLabel);
      setTranscriptMode(start.transcriptMode);
      setEventFlowSummary(start.eventFlowSummary);

      window.setTimeout(() => {
        setBridgePhase(start.mode === "PROVIDER" ? "PROVIDER_DIALING" : "MOCK_FALLBACK");
        setCallState("CONNECTED");
        window.setTimeout(() => setBridgePhase(start.mode === "PROVIDER" ? "PROVIDER_LIVE" : "MOCK_FALLBACK"), 350);
      }, 450);
    } catch (caught) {
      const start = buildProviderStartResult({ error: caught instanceof Error ? caught.message : "Provider connect blocked" });
      setTransportMode(start.mode);
      setBridgePhase(start.bridgePhase);
      setStartLabel(start.startLabel);
      setFallbackLabel(start.fallbackLabel);
      setTranscriptMode(start.transcriptMode);
      setEventFlowSummary(start.eventFlowSummary);
      window.setTimeout(() => setCallState("CONNECTED"), 450);
    }
  }

  const panelClass = "rounded-2xl border border-slate-200 bg-white p-4 shadow-sm";
  const callButtonLabel = callState === "CONNECTED" ? "End call" : callState === "DIALING" ? "Dialing..." : callState === "ENDED" ? "Retry call" : "Call";
  const keypadEnabled = callState === "CONNECTED" || callState === "DIALING";
  const keypadDisplay = sharedDtmfState.digits || "No digits entered yet";
  const toneDeliveryTone = sharedDtmfState.lastTone ? `Last tone ${sharedDtmfState.lastTone}` : "No keypad digit sent yet";

  useEffect(() => {
    if (!keypadEnabled) {
      setKeypadOpen(false);
      if (callState === "ENDED") {
        setKeypadStatus("The call ended. Reopen the keypad after you retry the call.");
        setKeypadDelivery("Keypad sending is paused until the next active call.");
        setKeypadDeliveryMode("IDLE");
        setRetryHint("Retry the call or save the result before using the keypad again.");
      } else if (callState === "READY") {
        setKeypadStatus("Use the keypad only when the phone asks for a number or extension.");
        setKeypadDelivery("Digits stay in the dialer until the call can send them.");
        setKeypadDeliveryMode("IDLE");
        setRetryHint("Pick a contact and start the call before using the keypad.");
      }
    }
  }, [keypadEnabled, callState]);



  useEffect(() => {
    if (callState === "CONNECTED" && toneQueue.length > 0 && !toneSendBusy) {
      setKeypadDeliveryMode("QUEUED");
      setRetryHint("Wait while CORI sends the queued keypad digits.");
      setKeypadDelivery(`Queued ${toneQueue.length} ${toneQueue.length === 1 ? "tone" : "tones"}. CORI is sending them now that the call is connected.`);
    }
  }, [callState, toneQueue.length, toneSendBusy]);

  async function sendLiveDtmfTone(value: string, retryAttempt = false) {
    if (transportMode !== "PROVIDER") {
      setPendingRetryDigit(value);
      setKeypadDeliveryMode("BLOCKED");
      setLastBlockedReason("DTMF_PROVIDER_PATH_REQUIRED");
      setRetryHint("Wait for the live phone connection or keep the keypad digits here for reference.");
      setKeypadDelivery(`Stored ${value} locally. Keypad sending stays off until the live phone connection is active.`);
      return;
    }

    try {
      const result = await apiPost<{
        dtmfSendReady?: boolean;
        sendStatus?: string;
        providerToneStatus?: string;
        message?: string;
        queuedForConnect?: boolean;
        sentNow?: boolean;
        blockedReason?: string;
        retryAllowed?: boolean;
        nextAction?: string;
      }>("/api/voice/twilio/dtmf", {
        digit: value,
        targetPhone: selectedContact?.phone,
        dialerStage: callState,
        consentCaptured: true,
        transportMode,
        retryAttempt,
      });

      if (result?.dtmfSendReady) {
        setPendingRetryDigit(null);
        setLastBlockedReason(null);
        if (result?.queuedForConnect) {
          setKeypadDeliveryMode("QUEUED");
          setRetryHint("Wait for the call to connect, then CORI will send the queued keypad digits.");
          setKeypadDelivery(`Queued ${value}. ${result.message || result.providerToneStatus || "Tone will send when the call finishes connecting."}`);
        } else {
          setKeypadDeliveryMode("SENT");
          setRetryHint("Press another keypad digit, or clear the entry when you are done.");
          setKeypadDelivery(`Sent ${value}. ${result?.message || result?.providerToneStatus || "Keypad digit is being sent."}`);
        }
        setKeypadLastTone(value);
        return;
      }

      setPendingRetryDigit(value);
      setKeypadDeliveryMode("BLOCKED");
      setLastBlockedReason(result?.blockedReason || result?.sendStatus || "DTMF_BLOCKED");
      setRetryHint(result?.queuedForConnect ? "Wait for connect, then retry the blocked keypad digit if it still matters." : "Retry the last keypad digit or clear the queue if the phone menu moved on.");
      setKeypadDelivery(`Could not send ${value}. ${result?.message || result?.sendStatus || "Keypad sending stayed blocked."}`);
    } catch (caught) {
      const message = caught instanceof Error ? caught.message : "Keypad sending stayed blocked.";
      setPendingRetryDigit(value);
      setKeypadDeliveryMode("BLOCKED");
      setLastBlockedReason("DTMF_REQUEST_FAILED");
      setRetryHint("Retry the last keypad digit when the line is stable, or clear the queue if the menu changed.");
      setKeypadDelivery(`Could not send ${value}. ${message}`);
    }
  }

  useEffect(() => {
    if (!keypadEnabled || toneSendBusy || toneQueue.length === 0) return;
    if (callState === "DIALING") return;
    let cancelled = false;
    const nextDigit = toneQueue[0];
    setToneSendBusy(true);
    void sendLiveDtmfTone(nextDigit, false).finally(() => {
      if (cancelled) return;
      setToneQueue((current) => current[0] === nextDigit ? current.slice(1) : current);
      setToneSendBusy(false);
    });
    return () => {
      cancelled = true;
    };
  }, [keypadEnabled, toneQueue, toneSendBusy, callState]);

  function appendKeypadDigit(value: string) {
    if (!keypadEnabled) return;
    setKeypadOpen(true);
    setKeypadDigits((current) => `${current}${value}`.slice(-24));
    setKeypadStatus(`Captured ${value} for menu or extension entry.`);
    const now = Date.now();
    if (lastToneAttemptRef.current && lastToneAttemptRef.current.digit === value && now - lastToneAttemptRef.current.at < 450) {
      setSendRepeatBlocked((current) => current + 1);
      setKeypadDeliveryMode("BLOCKED");
      setLastBlockedReason("DTMF_REPEAT_GUARD");
      setRetryHint("Wait a beat before sending the same keypad digit again, or use Retry if the menu still needs it.");
      setKeypadDelivery(`Held ${value} locally. CORI blocked a repeated tone that arrived too fast.`);
      return;
    }
    lastToneAttemptRef.current = { digit: value, at: now };
    if (toneQueue.length >= 6) {
      setRapidBlockedCount((current) => current + 1);
      setPendingRetryDigit(value);
      setKeypadDeliveryMode("BLOCKED");
      setLastBlockedReason("DTMF_RAPID_KEYPRESS_BLOCKED");
      setRetryHint("Wait for the keypad queue to clear, then retry the held digit if it still matters.");
      setKeypadDelivery(`Held ${value} locally. Too many keypad presses were entered too fast. Wait for the queue to clear.`);
      return;
    }
    setPendingRetryDigit(null);
    setToneQueue((current) => [...current, value]);
    setKeypadDeliveryMode("QUEUED");
    if (callState === "DIALING") {
      setRetryHint("Wait for the call to connect. CORI will drain the keypad queue in order.");
      setKeypadDelivery(`Queued ${value}. CORI will send tones in order once the call connects.`);
    } else if (toneSendBusy || toneQueue.length > 0) {
      setRetryHint("Wait while CORI sends the queued keypad digits in order.");
      setKeypadDelivery(`Queued ${value}. CORI will send tones in order while the call stays active.`);
    } else {
      setRetryHint("Wait while CORI sends the keypad digit. Retry only if the phone menu did not react.");
      setKeypadDelivery(`Sending ${value} through the dialer now.`);
    }
  }

  function handleKeypadBackspace() {
    setKeypadDigits((current) => current.slice(0, -1));
    setKeypadStatus("Removed the last keypad digit.");
    setKeypadDelivery("The last keypad record stays until a new digit is sent.");
  }

  function handleKeypadClear() {
    setKeypadDigits("");
    setToneQueue([]);
    setPendingRetryDigit(null);
    setKeypadStatus("Cleared keypad digits.");
    setKeypadDeliveryMode("IDLE");
    setLastBlockedReason(null);
    setRetryHint("Keypad entry cleared. Add a new digit only if the phone menu still needs it.");
    setKeypadDelivery("Digit history cleared in the dialer.");
    setKeypadLastTone(null);
  }

  function handleRetryTone() {
    if (!pendingRetryDigit || !keypadEnabled) return;
    if (toneQueue.length >= 6) {
      setRetryHint("Wait for the queued keypad digits to clear before retrying the blocked tone.");
      return;
    }
    if (callState === "CONNECTED") {
      setToneSendBusy(true);
      void sendLiveDtmfTone(pendingRetryDigit, true).finally(() => {
        setToneSendBusy(false);
      });
      setKeypadStatus(`Retrying ${pendingRetryDigit} for menu or extension entry.`);
      setKeypadDeliveryMode("QUEUED");
      setKeypadDelivery(`Retrying ${pendingRetryDigit}. CORI is sending it again through the dialer.`);
      setLastBlockedReason(null);
      setPendingRetryDigit(null);
      setRetryHint("Wait for the phone menu to react before retrying the same digit again.");
      return;
    }
    setToneQueue((current) => [pendingRetryDigit, ...current]);
    setKeypadDeliveryMode("QUEUED");
    setKeypadStatus(`Queued ${pendingRetryDigit} again for menu or extension entry.`);
    setKeypadDelivery(`Retrying ${pendingRetryDigit}. CORI will send it when the dialer is ready.`);
    setLastBlockedReason(null);
    setPendingRetryDigit(null);
    setRetryHint(callState === "DIALING" ? "Wait for connect so CORI can drain the keypad retry queue." : "Wait while CORI retries the blocked keypad digit.");
  }

  return (
    <div className={`${variant === "page" ? "space-y-4" : "space-y-3"}`}>
      <div className="rounded-3xl border border-slate-200 bg-white p-4 shadow-sm">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">
              <span>Call</span>
              <HelpDot label="Pick a contact, press Call, write short notes, and use CORI's next line when you need help." />
            </div>
            <div className="mt-1 text-xl font-semibold text-slate-900">{selectedContact ? `${selectedContact.name} · ${roleLabel(selectedContact.role)}` : "Pick who you want to call"}</div>
            <div className="mt-1 text-sm text-slate-500">Call the contact, keep the facts, and move the load forward.</div>
          </div>
          <div className="grid gap-2 text-sm sm:grid-cols-2 lg:min-w-[320px]">
            <div className="rounded-2xl border border-slate-200 bg-slate-50 px-3 py-2">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Truck</div>
              <div className="mt-1 font-medium text-slate-800">{launchContext?.truckLabel || selectedContact?.truckLabel || "No truck linked yet"}</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 px-3 py-2">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Lane</div>
              <div className="mt-1 font-medium text-slate-800">{launchContext?.laneLabel || "Add lane context from truck or load"}</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 px-3 py-2">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Ask</div>
              <div className="mt-1 font-medium text-slate-800">{compactMoney(launchContext?.targetRate)}</div>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 px-3 py-2">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Floor</div>
              <div className="mt-1 font-medium text-slate-800">{compactMoney(launchContext?.floorRate)}</div>
            </div>
          </div>
        </div>
      </div>

      <div className={panelClass} ref={wrapperRef}>
        <div className="flex flex-col gap-3 lg:flex-row lg:items-end">
          <div className="min-w-0 flex-1">
            <label className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Phone book</label>
            <div className="relative mt-1">
              <input
                value={search}
                onChange={(event) => {
                  setSearch(event.target.value);
                  setSearchOpen(true);
                }}
                onFocus={() => setSearchOpen(true)}
                placeholder="Search broker, driver, or shipper"
                className="w-full rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-800 outline-none ring-0 placeholder:text-slate-400 focus:border-sky-300"
              />
              {searchOpen ? (
                <div className="absolute z-20 mt-2 max-h-72 w-full overflow-y-auto rounded-2xl border border-slate-200 bg-white shadow-xl">
                  {filteredOptions.length ? filteredOptions.map((option) => (
                    <button
                      key={`${option.role}-${option.id}`}
                      type="button"
                      onClick={() => handleSelect(option)}
                      className="flex w-full flex-col items-start gap-1 border-b border-slate-100 px-4 py-3 text-left last:border-b-0 hover:bg-sky-50"
                    >
                      <div className="text-sm font-medium text-slate-900">{option.companyLabel} — {option.name}</div>
                      <div className="text-xs text-slate-500">{roleLabel(option.role)} · {option.phone}{option.truckLabel ? ` · ${option.truckLabel}` : ""}</div>
                    </button>
                  )) : <div className="px-4 py-3 text-sm text-slate-500">No matches yet.</div>}
                </div>
              ) : null}
            </div>
          </div>
          <div className="w-full lg:w-72">
            <label className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Reason for call</label>
            <select value={purpose} onChange={(event) => setPurpose(event.target.value as CallPurpose)} className="mt-1 w-full rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-800 outline-none focus:border-sky-300">
              <option value="NEGOTIATE_RATE">Negotiate rate</option>
              <option value="CHECK_LOAD_DETAILS">Check load details</option>
              <option value="CONFIRM_PICKUP">Confirm pickup</option>
              <option value="CONFIRM_DELIVERY">Confirm delivery</option>
              <option value="ETA_UPDATE">ETA update</option>
              <option value="PROBLEM_RESOLUTION">Problem resolution</option>
              <option value="CALLBACK">Callback</option>
              <option value="GENERAL">General call</option>
            </select>
          </div>
        </div>
        {error ? <div className="mt-3 text-sm text-rose-600">{error}</div> : null}
      </div>

      <section className="rounded-3xl border border-sky-100 bg-sky-50 p-4 shadow-sm">
        <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <div className="text-sm font-semibold text-sky-950">Need help during the call?</div>
            <div className="mt-1 text-sm leading-6 text-sky-900">Type short notes or a question for CORI. CORI will keep the useful facts and suggest what to say next.</div>
          </div>
          <HelpDot label="Ask CORI in plain words. Short notes work best: offer 2400, pickup 8am, driver wants callback, broker said rate con is coming." />
        </div>
      </section>

      <div className="grid gap-4 xl:grid-cols-[1.05fr_0.95fr_1.05fr]">
        <section className={panelClass}>
          <div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400"><span>Call facts</span><HelpDot label="These are the facts CORI can use while you work the call." /></div>
          <div className="mt-3 grid gap-0.5">
            {liveFacts.map((fact) => <FactRow key={fact.label} label={fact.label} value={fact.value} />)}
          </div>
        </section>
        <section className={panelClass}>
          <div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400"><span>Watch for</span><HelpDot label="CORI only shows route, money, weather, or timing items that can change the decision." /></div>
          <div className="mt-3 flex flex-wrap gap-2">
            {hiddenReality.map((item) => (
              <div key={item} className="rounded-full border border-amber-200 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-700">{item}</div>
            ))}
          </div>
          <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 px-3 py-3 text-xs text-slate-600">
Only the facts that change the decision or the rate appear here.
          </div>
        </section>
        <section className={panelClass}>
          <div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400"><span>What to say</span><HelpDot label="Use this when you want CORI to keep the call short and focused." /></div>
          <div className="mt-3 text-lg font-semibold text-slate-900">{advice.headline}</div>
          <div className="mt-2 text-sm leading-6 text-slate-600">{advice.body}</div>
          <div className="mt-4 rounded-2xl border border-sky-200 bg-sky-50 px-3 py-3">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-700">Say next</div>
            <div className="mt-1 text-sm font-medium text-sky-900">{advice.speakLine}</div>
          </div>
          <div className="mt-4 grid gap-2 sm:grid-cols-3">
            {advice.metrics.map((metric) => (
              <div key={metric.label} className="rounded-2xl border border-slate-200 bg-white px-3 py-3">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">{metric.label}</div>
                <div className="mt-1 text-sm font-semibold text-slate-800">{metric.value}</div>
              </div>
            ))}
          </div>
          <div className="mt-4 rounded-2xl border border-sky-200 bg-sky-100 px-3 py-3 shadow-sm">
            <label className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-800"><span>Ask CORI</span><HelpDot label="Type a short question or note for CORI. CORI will pull out rate, lane, time, callback, and result signals." /></label>
            <input
              value={callNote}
              onChange={(event) => setCallNote(event.target.value)}
              placeholder="Ask CORI or type a short note..."
              className="mt-2 w-full rounded-xl border border-sky-200 bg-white px-3 py-2 text-sm text-slate-900 outline-none placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-100"
            />
          </div>
          <div className="mt-4">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Result</div>
            <div className="mt-2 flex flex-wrap gap-2">
              {[
                ["NO_ANSWER", "No answer"],
                ["CALLBACK", "Callback"],
                ["COUNTERED", "Countered"],
                ["BOOKED", "Booked"],
                ["PASS", "Pass"],
              ].map(([value, label]) => (
                <button
                  key={value}
                  type="button"
                  onClick={() => setQuickOutcome(value as QuickOutcome)}
                  className={`rounded-full border px-3 py-1.5 text-xs font-medium ${quickOutcome === value ? "border-sky-300 bg-sky-50 text-sky-700" : "border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>
        </section>
      </div>

      <div className="rounded-3xl border border-slate-200 bg-slate-950 px-4 py-4 text-white shadow-xl">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <div className="min-w-0">
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Phone</div>
            <div className="mt-1 text-xl font-semibold">{selectedContact?.phone || launchContext?.phone || "Select a number first"}</div>
            <div className="mt-1 text-sm text-slate-300">{selectedContact ? `${selectedContact.companyLabel} · ${selectedContact.name}` : "The dialer waits until you press Call."}</div>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <div className="rounded-full border border-slate-700 px-3 py-2 text-xs font-medium text-slate-300">{callState === "CONNECTED" ? "Connected" : callState === "DIALING" ? "Dialing" : callState === "ENDED" ? "Ended" : "Ready"}</div>
            <button
              type="button"
              onClick={() => setKeypadOpen((current) => !current)}
              disabled={!keypadEnabled}
              className="rounded-full border border-slate-700 px-4 py-2 text-sm font-medium text-slate-100 hover:bg-slate-900 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {keypadOpen ? "Hide keypad" : "Keypad"}
            </button>
            <button type="button" onClick={handleCallPress} disabled={!selectedContact || callState === "DIALING"} className={`rounded-full px-5 py-2.5 text-sm font-semibold ${callState === "CONNECTED" ? "bg-rose-500 text-white hover:bg-rose-600" : "bg-emerald-500 text-white hover:bg-emerald-600"} disabled:cursor-not-allowed disabled:opacity-50`}>
              {callButtonLabel}
            </button>
            {variant === "popup" && onClose ? <button type="button" onClick={onClose} className="rounded-full border border-slate-700 px-4 py-2 text-sm font-medium text-slate-200 hover:bg-slate-900">Close</button> : null}
          </div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_auto] lg:items-center">
          <div className="rounded-2xl border border-slate-800 bg-slate-900/70 px-3 py-3 text-sm text-slate-200">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Keypad</div>
                <div className="mt-1 font-medium text-white">{keypadDisplay}</div>
                <div className="mt-1 text-xs text-slate-400">Use this only when the phone asks for an option or extension.</div>
              </div>
              <div className={`rounded-full px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] ${sharedDtmfState.deliveryMode === "SENT" ? "bg-emerald-500/15 text-emerald-300" : sharedDtmfState.deliveryMode === "QUEUED" ? "bg-amber-500/15 text-amber-200" : sharedDtmfState.deliveryMode === "BLOCKED" ? "bg-rose-500/15 text-rose-200" : "bg-slate-800 text-slate-300"}`}>
                {sharedDtmfState.deliveryMode === "IDLE" ? "Local only" : sharedDtmfState.deliveryMode}
              </div>
            </div>
            <div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-slate-300">
              <span className="rounded-full border border-slate-800 bg-slate-950/50 px-3 py-1.5">Use keypad only when needed</span>
              {sharedDtmfState.retryAvailable ? <button type="button" onClick={handleRetryTone} className="rounded-full border border-slate-700 px-3 py-1.5 text-xs font-medium text-slate-100 hover:bg-slate-900">Retry tone</button> : null}
              {sharedDtmfState.queuedCount ? <button type="button" onClick={handleKeypadClear} className="rounded-full border border-slate-700 px-3 py-1.5 text-xs font-medium text-slate-200 hover:bg-slate-900">Clear queue</button> : null}
            </div>
          </div>
          <div className="text-xs text-slate-400 lg:text-right">Open the keypad during a live call when a phone menu or extension asks for digits.</div>
        </div>
      </div>

      {keypadOpen ? (
        <div className={`fixed inset-x-4 bottom-4 z-40 ${variant === "popup" ? "sm:inset-x-6" : "sm:left-auto sm:right-6 sm:w-[24rem]"}`}>
          <div className="rounded-[28px] border border-slate-200 bg-white p-4 shadow-2xl">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Dial pad</div>
                <div className="mt-1 text-lg font-semibold text-slate-900">{keypadDisplay}</div>
                <div className="mt-1 text-sm text-slate-600">Use this when the phone asks you to press a number or enter an extension.</div>
              </div>
              <button type="button" onClick={() => setKeypadOpen(false)} className="rounded-full border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50">Close</button>
            </div>
            <div className="mt-4 grid grid-cols-3 gap-3">
              <KeypadButton label="1" onClick={() => appendKeypadDigit("1")} />
              <KeypadButton label="2" sublabel="ABC" onClick={() => appendKeypadDigit("2")} />
              <KeypadButton label="3" sublabel="DEF" onClick={() => appendKeypadDigit("3")} />
              <KeypadButton label="4" sublabel="GHI" onClick={() => appendKeypadDigit("4")} />
              <KeypadButton label="5" sublabel="JKL" onClick={() => appendKeypadDigit("5")} />
              <KeypadButton label="6" sublabel="MNO" onClick={() => appendKeypadDigit("6")} />
              <KeypadButton label="7" sublabel="PQRS" onClick={() => appendKeypadDigit("7")} />
              <KeypadButton label="8" sublabel="TUV" onClick={() => appendKeypadDigit("8")} />
              <KeypadButton label="9" sublabel="WXYZ" onClick={() => appendKeypadDigit("9")} />
              <KeypadButton label="*" onClick={() => appendKeypadDigit("*")} />
              <KeypadButton label="0" onClick={() => appendKeypadDigit("0")} />
              <KeypadButton label="#" onClick={() => appendKeypadDigit("#")} />
            </div>
            <div className="mt-4 flex flex-wrap gap-2">
              <button type="button" onClick={handleKeypadBackspace} disabled={!keypadDigits} className="rounded-full border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50">Backspace</button>
              <button type="button" onClick={handleKeypadClear} disabled={!keypadDigits && !toneQueue.length} className="rounded-full border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50">Clear</button>
              <button type="button" onClick={handleRetryTone} disabled={!sharedDtmfState.retryAvailable} className="rounded-full border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50">Retry tone</button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}