import Link from "next/link";

export type IntelligenceEntityType = "shipper" | "company" | "broker";

export type IntelligenceIntakePayload = {
  source: string;
  entityType: IntelligenceEntityType;
  name: string;
  lane?: string;
  location?: string;
  whyItFits?: string;
  nextMove?: string;
  crmFit?: string;
  contactHint?: string;
  query?: string;
  mode?: string;
};

function safe(value?: string | null) {
  return value?.trim() ?? "";
}

export function buildIntelligenceCreateHref(payload: IntelligenceIntakePayload) {
  const base = payload.entityType === "shipper" ? "/shippers/new" : payload.entityType === "broker" ? "/brokers/new" : "/companies/new";
  const params = new URLSearchParams();
  params.set("source", payload.source || "intelligence");
  params.set("intake", "intelligence");
  params.set("entityType", payload.entityType);
  params.set("name", payload.name);
  if (safe(payload.lane)) params.set("lane", safe(payload.lane));
  if (safe(payload.location)) params.set("location", safe(payload.location));
  if (safe(payload.whyItFits)) params.set("whyItFits", safe(payload.whyItFits));
  if (safe(payload.nextMove)) params.set("nextMove", safe(payload.nextMove));
  if (safe(payload.crmFit)) params.set("crmFit", safe(payload.crmFit));
  if (safe(payload.contactHint)) params.set("contactHint", safe(payload.contactHint));
  if (safe(payload.query)) params.set("query", safe(payload.query));
  if (safe(payload.mode)) params.set("mode", safe(payload.mode));
  return `${base}?${params.toString()}`;
}



export type IntelligenceIntakePrefillPlan = {
  recommendedStage: string;
  recommendedStageLabel: string;
  followUpDate: string;
  priorityLabel: string;
  summary: string;
};

function formatDateInput(date: Date) {
  return date.toISOString().slice(0, 10);
}

function addDays(days: number) {
  const next = new Date();
  next.setHours(0, 0, 0, 0);
  next.setDate(next.getDate() + days);
  return formatDateInput(next);
}

export function getIntelligencePrefillPlan(params: URLSearchParams, entityType?: IntelligenceEntityType): IntelligenceIntakePrefillPlan {
  const mode = (params.get("mode") || "market-search").trim();
  const name = (params.get("name") || "This lead").trim();
  const crmFit = (params.get("crmFit") || "").toLowerCase();
  const query = (params.get("query") || "broad research").trim();

  let recommendedStage = "LEAD";
  let recommendedStageLabel = "Lead";
  let followUpDate = addDays(3);
  let priorityLabel = "Standard intake";

  if (mode === "service-search") {
    recommendedStage = "CONTACTED";
    recommendedStageLabel = "Contacted";
    followUpDate = addDays(2);
    priorityLabel = "Service-fit follow-up";
  }

  if (mode === "outreach-planning") {
    recommendedStage = "WARM";
    recommendedStageLabel = "Warm";
    followUpDate = addDays(1);
    priorityLabel = "Outreach-ready";
  }

  if (crmFit.includes("warm")) {
    recommendedStage = "WARM";
    recommendedStageLabel = "Warm";
  }
  if (crmFit.includes("hot")) {
    recommendedStage = "HOT";
    recommendedStageLabel = "Hot";
    followUpDate = addDays(1);
    priorityLabel = "High-priority conversion";
  }
  if (crmFit.includes("premium")) {
    recommendedStage = "HOT";
    recommendedStageLabel = "Hot";
    followUpDate = addDays(1);
    priorityLabel = "Premium service review";
  }
  if (entityType === "broker" && recommendedStage === "LEAD") {
    recommendedStage = "CONTACTED";
    recommendedStageLabel = "Contacted";
  }

  return {
    recommendedStage,
    recommendedStageLabel,
    followUpDate,
    priorityLabel,
    summary: `${name} came from lead follow-up ${mode.replace(/-/g, " ")} for ${query}. Move it into CRM with a ${recommendedStageLabel.toLowerCase()} stage and follow up by ${followUpDate}.`,
  };
}

export function buildIntelligenceListHref(entityType: IntelligenceEntityType, payload?: Partial<IntelligenceIntakePayload>) {
  const base = entityType === "shipper" ? "/shippers" : entityType === "broker" ? "/brokers" : "/companies";
  const params = new URLSearchParams();
  params.set("report", "intelligence-intake");
  params.set("source", payload?.source || "intelligence");
  params.set("intake", "intelligence");
  params.set("entityType", entityType);
  if (safe(payload?.mode)) params.set("mode", safe(payload?.mode));
  if (safe(payload?.query)) params.set("query", safe(payload?.query));
  if (safe(payload?.name)) params.set("search", safe(payload?.name));
  return `${base}?${params.toString()}`;
}



function getModeLabel(mode?: string | null) {
  switch ((mode || "").trim()) {
    case "service-search":
      return "Service search";
    case "outreach-planning":
      return "Outreach planning";
    default:
      return "Market search";
  }
}

export function buildIntelligenceBackHref(params: URLSearchParams) {
  const next = new URLSearchParams();
  next.set("mode", params.get("mode") || "market-search");
  const query = params.get("query") || "";
  if (query.trim()) next.set("query", query.trim());
  return `/crm?${next.toString()}`;
}
export function buildIntelligenceNotes(params: URLSearchParams) {
  const parts = [
    params.get("crmFit") ? `CRM fit: ${params.get("crmFit")}` : "",
    params.get("lane") ? `Lane / service pattern: ${params.get("lane")}` : "",
    params.get("location") ? `Location: ${params.get("location")}` : "",
    params.get("whyItFits") ? `Why it fits: ${params.get("whyItFits")}` : "",
    params.get("nextMove") ? `Next move: ${params.get("nextMove")}` : "",
    params.get("contactHint") ? `Contact hint: ${params.get("contactHint")}` : "",
    params.get("query") ? `Search note: ${params.get("query")}` : "",
  ].filter(Boolean);
  return parts.join("\n\n");
}

export function IntelligenceIntakeBanner({
  title,
  subtitle,
  backHref,
}: {
  title: string;
  subtitle: string;
  backHref?: string;
}) {
  return (
    <div className="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-700">Lead follow-up</div>
          <div className="mt-1 text-base font-semibold text-slate-900">{title}</div>
          <div className="mt-1 text-sm text-slate-700">{subtitle}</div>
        </div>
        {backHref ? (
          <Link href={backHref} className="inline-flex items-center justify-center rounded-xl border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-900">
            Back to CRM
          </Link>
        ) : null}
      </div>
    </div>
  );
}


export function IntelligenceContextCard({
  params,
  entityType,
}: {
  params: URLSearchParams;
  entityType: IntelligenceEntityType;
}) {
  const plan = getIntelligencePrefillPlan(params, entityType);
  const cards = [
    ["Lead name", params.get("name") || "-"],
    ["Lane / service", params.get("lane") || "-"],
    ["Location", params.get("location") || "-"],
    ["Contact hint", params.get("contactHint") || "-"],
    ["Recommended stage", plan.recommendedStageLabel],
    ["Follow up by", plan.followUpDate],
  ] as const;

  return (
    <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Lead details</div>
          <div className="mt-1 text-base font-semibold text-slate-900">Move this lead into CRM</div>
          <div className="mt-1 text-sm text-slate-600">{plan.summary}</div>
        </div>
        <span className="rounded-full border bg-white px-3 py-1 text-xs font-medium text-slate-700">{plan.priorityLabel}</span>
      </div>
      <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
        {cards.map(([label, value]) => (
          <div key={label} className="rounded-xl border bg-white p-3">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">{label}</div>
            <div className="mt-1 text-sm text-slate-800">{value}</div>
          </div>
        ))}
      </div>
    </div>
  );
}


export function IntelligenceListHandoffBanner({
  params,
  entityType,
  filteredCount,
  createHref,
}: {
  params: URLSearchParams;
  entityType: IntelligenceEntityType;
  filteredCount: number;
  createHref: string;
}) {
  const plan = getIntelligencePrefillPlan(params, entityType);
  const leadName = params.get("name") || "this lead";
  const query = (params.get("query") || "").trim();
  const modeLabel = getModeLabel(params.get("mode"));
  const backHref = buildIntelligenceBackHref(params);
  const querySummary = query ? `Search note: ${query}` : "Search note: broad research";

  return (
    <section className="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="space-y-2">
          <div>
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-700">Lead match check</div>
            <div className="mt-1 text-base font-semibold text-slate-900">Review matching CRM records before creating a new one</div>
            <div className="mt-1 text-sm text-slate-700">
              {leadName} came from <span className="font-semibold">{modeLabel}</span>. {querySummary}
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-blue-900">Recommended stage: {plan.recommendedStageLabel}</span>
            <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-blue-900">Follow up by {plan.followUpDate}</span>
            <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-blue-900">Matches in view: {filteredCount}</span>
          </div>
          <div className="text-sm text-slate-700">
            {filteredCount > 0
              ? `Use the filtered list below to check whether ${leadName} already exists before creating a new CRM record.`
              : `No matching records are showing yet. You can clear the search, widen the filters, or create ${leadName} now.`}
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link href={backHref} className="rounded-xl border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-900 hover:bg-blue-100">
            Back to CRM
          </Link>
          <Link href={createHref} className="rounded-xl bg-blue-900 px-3 py-2 text-sm font-medium text-white hover:bg-blue-800">
            Create in CRM
          </Link>
        </div>
      </div>
    </section>
  );
}


export function getIntelligenceParamsFromHref(href?: string | null) {
  if (!href) return null;
  const queryIndex = href.indexOf("?");
  if (queryIndex === -1) return null;
  const params = new URLSearchParams(href.slice(queryIndex + 1));
  if (params.get("intake") !== "intelligence" || params.get("source") !== "intelligence") return null;
  return params;
}

function normalizeForComparison(value?: string | null) {
  return (value || "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
}


export type IntelligenceRecordDecision = {
  recommendation: string;
  recommendationLabel: string;
  reasoning: string;
  matchSignals: string[];
  riskLabel: string;
  riskTone: "good" | "watch" | "action";
};

function normalizedTokens(value?: string | null) {
  return normalizeForComparison(value).split(" ").filter(Boolean);
}

function unique<T>(items: T[]) {
  return Array.from(new Set(items));
}



export type IntelligenceFollowUpPlan = {
  primaryActivityType: "CALL" | "EMAIL" | "TASK";
  primaryLabel: string;
  secondaryActivityType: "CALL" | "EMAIL" | "TASK";
  secondaryLabel: string;
  objective: string;
  outreachAngle: string;
  sequenceLabel: string;
  sequenceSteps: string[];
};

export function getIntelligenceFollowUpPlan(params: URLSearchParams, entityType: IntelligenceEntityType): IntelligenceFollowUpPlan {
  const mode = (params.get("mode") || "market-search").trim();
  const lane = (params.get("lane") || "the active service lane").trim();
  const nextMove = (params.get("nextMove") || "confirm service fit and next-step ownership").trim();

  if (mode === "outreach-planning") {
    return {
      primaryActivityType: "EMAIL",
      primaryLabel: "Lead with outreach email",
      secondaryActivityType: "CALL",
      secondaryLabel: "Call if no reply",
      objective: `Open the conversation around ${lane} with crisp service language and a direct next step.`,
      outreachAngle: nextMove,
      sequenceLabel: "Email-first sequence",
      sequenceSteps: [
        `Send a short first-touch email focused on ${lane}.`,
        "If there is no reply, place a direct follow-up call.",
        "Set a task to revisit the account with a sharper offer or timing angle.",
      ],
    };
  }

  if (mode === "service-search") {
    return {
      primaryActivityType: "CALL",
      primaryLabel: entityType === "broker" ? "Call carrier sales first" : "Call for service-fit review",
      secondaryActivityType: "EMAIL",
      secondaryLabel: "Follow with recap email",
      objective: `Validate whether ${lane} rewards strong communication control, timing discipline, and repeat-fit service.`,
      outreachAngle: nextMove,
      sequenceLabel: "Call-first service-fit sequence",
      sequenceSteps: [
        "Open with a qualification call to confirm operating fit and urgency.",
        "Send a recap email that restates the service lane and next agreed step.",
        "Set a task to verify whether the opportunity should advance, pause, or be reworked.",
      ],
    };
  }

  return {
    primaryActivityType: "CALL",
    primaryLabel: "Call to qualify the lead",
    secondaryActivityType: "TASK",
    secondaryLabel: "Set research follow-up task",
    objective: `Qualify whether ${lane} looks like recurring freight worth moving deeper into CRM.`,
    outreachAngle: nextMove,
    sequenceLabel: "Qualification sequence",
    sequenceSteps: [
      "Place a first qualification call and confirm the freight pattern.",
      "Create a task to capture any missing research or contact gaps.",
      "Return with a sharper service offer once the lane and timing are clearer.",
    ],
  };
}

export function getIntelligenceRecordDecision(params: URLSearchParams, recordName: string, recordLocation?: string | null): IntelligenceRecordDecision {
  const leadName = params.get("name") || "";
  const leadLocation = params.get("location") || "";
  const exactNameMatch = normalizeForComparison(recordName) && normalizeForComparison(recordName) === normalizeForComparison(leadName);
  const recordTokens = normalizedTokens(recordName);
  const leadTokens = normalizedTokens(leadName);
  const sharedTokens = unique(leadTokens.filter((token) => recordTokens.includes(token)));
  const recordLocationTokens = normalizedTokens(recordLocation);
  const leadLocationTokens = normalizedTokens(leadLocation);
  const sharedLocationTokens = unique(leadLocationTokens.filter((token) => recordLocationTokens.includes(token)));
  const hasStrongNameOverlap = sharedTokens.length >= Math.min(2, Math.max(1, leadTokens.length));
  const hasLocationOverlap = sharedLocationTokens.length > 0;

  if (exactNameMatch && hasLocationOverlap) {
    return {
      recommendation: "USE_EXISTING",
      recommendationLabel: "Use existing record",
      reasoning: "The researched lead strongly matches this CRM record by name and location. Review the existing record first and continue follow-up there unless there is a verified structural difference.",
      matchSignals: ["Exact name match", "Location overlap", "Lower duplicate risk"],
      riskLabel: "Low duplicate risk",
      riskTone: "good",
    };
  }

  if (exactNameMatch || (hasStrongNameOverlap && hasLocationOverlap)) {
    return {
      recommendation: "REVIEW_CAREFULLY",
      recommendationLabel: "Review before creating",
      reasoning: "There are enough matching signals that this may already be the correct CRM record. Confirm the lane, contact path, and account structure before creating a separate record.",
      matchSignals: [exactNameMatch ? "Exact or near-exact name" : `Shared name terms: ${sharedTokens.join(", ")}`, hasLocationOverlap ? `Shared location terms: ${sharedLocationTokens.join(", ")}` : "Location still unclear", "Needs review"],
      riskLabel: "Moderate duplicate risk",
      riskTone: "watch",
    };
  }

  return {
    recommendation: "CREATE_SEPARATE",
    recommendationLabel: "Create separate record",
    reasoning: "The current CRM record does not strongly match the researched lead. Creating a separate record is reasonable if the service pattern and operating identity are truly different.",
    matchSignals: [sharedTokens.length ? `Limited name overlap: ${sharedTokens.join(", ")}` : "No strong name overlap", hasLocationOverlap ? `Some location overlap: ${sharedLocationTokens.join(", ")}` : "No meaningful location overlap", "Higher chance this is a separate lead"],
    riskLabel: "Lower match confidence",
    riskTone: "action",
  };
}
export function IntelligenceDetailReviewBanner({
  params,
  entityType,
  recordName,
  listHref,
  createHref,
}: {
  params: URLSearchParams;
  entityType: IntelligenceEntityType;
  recordName: string;
  listHref: string;
  createHref: string;
}) {
  const plan = getIntelligencePrefillPlan(params, entityType);
  const backHref = buildIntelligenceBackHref(params);
  const leadName = params.get("name") || "this lead";
  const lane = params.get("lane") || "-";
  const location = params.get("location") || "-";
  const query = (params.get("query") || "").trim();
  const modeLabel = getModeLabel(params.get("mode"));
  const exactNameMatch = normalizeForComparison(recordName) && normalizeForComparison(recordName) === normalizeForComparison(leadName);
  const decision = getIntelligenceRecordDecision(params, recordName, location);

  return (
    <section className="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="space-y-3">
          <div>
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-700">Lead review</div>
            <div className="mt-1 text-base font-semibold text-slate-900">Check this CRM record before creating a duplicate</div>
            <div className="mt-1 text-sm text-slate-700">
              You opened this record from <span className="font-semibold">{modeLabel}</span>{query ? ` for ${query}` : ""}. Review whether <span className="font-semibold">{recordName}</span> already covers the researched lead before creating a new CRM record.
            </div>
          </div>
          <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-xl border bg-white p-3">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Research lead</div>
              <div className="mt-1 text-sm text-slate-900">{leadName}</div>
            </div>
            <div className="rounded-xl border bg-white p-3">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Current record</div>
              <div className="mt-1 text-sm text-slate-900">{recordName}</div>
            </div>
            <div className="rounded-xl border bg-white p-3">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Lane / service</div>
              <div className="mt-1 text-sm text-slate-900">{lane}</div>
            </div>
            <div className="rounded-xl border bg-white p-3">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Location</div>
              <div className="mt-1 text-sm text-slate-900">{location}</div>
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-blue-900">Recommended stage: {plan.recommendedStageLabel}</span>
            <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-blue-900">Follow up by {plan.followUpDate}</span>
            <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${exactNameMatch ? "bg-emerald-100 text-emerald-800" : "bg-amber-100 text-amber-800"}`}>{exactNameMatch ? "Strong name match" : "Review for duplicate risk"}</span>
            <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${decision.riskTone === "good" ? "bg-emerald-100 text-emerald-800" : decision.riskTone === "watch" ? "bg-amber-100 text-amber-800" : "bg-slate-200 text-slate-800"}`}>{decision.riskLabel}</span>
          </div>
        </div>
        <div className="space-y-3 lg:max-w-sm">
          <div className="rounded-xl border bg-white p-3 text-sm text-slate-700">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Possible duplicate check</div>
            <div className="mt-1 font-semibold text-slate-900">{decision.recommendationLabel}</div>
            <div className="mt-1">{decision.reasoning}</div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href={listHref} className="rounded-xl border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-900 hover:bg-blue-100">
              Back to matching list
            </Link>
            <Link href={backHref} className="rounded-xl border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-900 hover:bg-blue-100">
              Back to CRM
            </Link>
            <Link href={createHref} className="rounded-xl bg-blue-900 px-3 py-2 text-sm font-medium text-white hover:bg-blue-800">
              Create separate record
            </Link>
          </div>
        </div>
      </div>
    </section>
  );
}



export function buildIntelligenceActivityKickoffHref(currentHref: string, payload: {
  entityType: IntelligenceEntityType;
  entityName: string;
  recommendedStageLabel?: string;
  followUpDate?: string;
  activityType: "CALL" | "EMAIL" | "TASK";
  contactHint?: string;
  nextMove?: string;
  lane?: string;
  objective?: string;
  mode?: string;
  sequenceLabel?: string;
  sequenceSteps?: string[];
  sequenceStepIndex?: number;
  sequenceStepLabel?: string;
}) {
  const [pathname, search = ""] = currentHref.split("?");
  const params = new URLSearchParams(search);
  params.set("activityKickoff", "intelligence");
  params.set("activityType", payload.activityType);
  params.set("activityEntityType", payload.entityType.toUpperCase());
  params.set("activityEntityName", payload.entityName);
  if (safe(payload.recommendedStageLabel)) params.set("activityStage", safe(payload.recommendedStageLabel));
  if (safe(payload.followUpDate)) params.set("activityFollowUpDate", safe(payload.followUpDate));
  if (safe(payload.contactHint)) params.set("activityContactHint", safe(payload.contactHint));
  if (safe(payload.nextMove)) params.set("activityNextMove", safe(payload.nextMove));
  if (safe(payload.lane)) params.set("activityLane", safe(payload.lane));
  if (safe(payload.objective)) params.set("activityObjective", safe(payload.objective));
  if (safe(payload.mode)) params.set("activityMode", safe(payload.mode));
  if (safe((payload as any).sequenceLabel)) params.set("activitySequenceLabel", safe((payload as any).sequenceLabel));
  if (Array.isArray((payload as any).sequenceSteps) && (payload as any).sequenceSteps.length) {
    params.set("activitySequence", (payload as any).sequenceSteps.filter(Boolean).join(" || "));
  }
  if (typeof (payload as any).sequenceStepIndex === "number") params.set("activitySequenceStepIndex", String((payload as any).sequenceStepIndex));
  if (safe((payload as any).sequenceStepLabel)) params.set("activitySequenceStepLabel", safe((payload as any).sequenceStepLabel));

  const subjectBase = payload.activityType === "CALL"
    ? `Lead follow-up call: ${payload.entityName}`
    : payload.activityType === "EMAIL"
      ? `Lead follow-up email: ${payload.entityName}`
      : `Lead follow-up task: ${payload.entityName}`;
  params.set("activitySubject", subjectBase);

  const details = [
    `Lead / record: ${payload.entityName}`,
    payload.recommendedStageLabel ? `Recommended stage: ${payload.recommendedStageLabel}` : "",
    payload.contactHint ? `Contact hint: ${payload.contactHint}` : "",
    payload.lane ? `Lane / service: ${payload.lane}` : "",
    payload.objective ? `Objective: ${payload.objective}` : "",
    payload.nextMove ? `Next move: ${payload.nextMove}` : "",
    payload.followUpDate ? `Target follow-up date: ${payload.followUpDate}` : "",
  ].filter(Boolean).join("\n\n");
  if (details) params.set("activityContent", details);

  if (payload.followUpDate) {
    const local = `${payload.followUpDate}T09:00`;
    params.set("activityDueAt", local);
  }

  return `${pathname}?${params.toString()}#crm-timeline`;
}

function getSequenceStepActivityType(plan: IntelligenceFollowUpPlan, stepIndex: number): "CALL" | "EMAIL" | "TASK" {
  if (stepIndex === 0) return plan.primaryActivityType;
  if (stepIndex === 1) return plan.secondaryActivityType;
  return "TASK";
}

export function IntelligenceDecisionSupportCard({
  params,
  entityType,
  recordName,
  recordLocation,
  useExistingHref,
  createHref,
}: {
  params: URLSearchParams;
  entityType: IntelligenceEntityType;
  recordName: string;
  recordLocation?: string | null;
  useExistingHref: string;
  createHref: string;
}) {
  const decision = getIntelligenceRecordDecision(params, recordName, recordLocation);
  const plan = getIntelligencePrefillPlan(params, entityType);
  const followUpPlan = getIntelligenceFollowUpPlan(params, entityType);
  const kickoffPayload = {
    entityType,
    entityName: recordName,
    recommendedStageLabel: plan.recommendedStageLabel,
    followUpDate: plan.followUpDate,
    contactHint: params.get("contactHint") || undefined,
    nextMove: params.get("nextMove") || undefined,
    lane: params.get("lane") || undefined,
    objective: followUpPlan.objective,
    mode: params.get("mode") || undefined,
    sequenceLabel: followUpPlan.sequenceLabel,
    sequenceSteps: followUpPlan.sequenceSteps,
  } as const;
  return (
    <section className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Lead follow-up help</div>
          <div className="mt-1 text-base font-semibold text-slate-900">{decision.recommendationLabel}</div>
          <div className="mt-1 text-sm text-slate-700">{decision.reasoning}</div>
        </div>
        <span className={`rounded-full px-3 py-1 text-xs font-medium ${decision.riskTone === "good" ? "bg-emerald-100 text-emerald-800" : decision.riskTone === "watch" ? "bg-amber-100 text-amber-800" : "bg-slate-200 text-slate-800"}`}>{decision.riskLabel}</span>
      </div>
      <div className="mt-4 rounded-xl border border-blue-200 bg-blue-50 p-4">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div className="space-y-3">
            <div>
              <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-700">Follow-up kickoff</div>
              <div className="mt-1 text-sm font-semibold text-slate-900">Start the first CRM activity</div>
              <div className="mt-1 text-sm text-slate-700">These actions prefill the CRM activity with the recommended follow-up date, record name, lane, and next step.</div>
            </div>
            <div className="grid gap-3 md:grid-cols-3">
              <div className="rounded-xl border bg-white p-3">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Suggested first touch</div>
                <div className="mt-1 text-sm font-semibold text-slate-900">{followUpPlan.primaryLabel}</div>
                <div className="mt-1 text-sm text-slate-700">{followUpPlan.objective}</div>
              </div>
              <div className="rounded-xl border bg-white p-3">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Backup move</div>
                <div className="mt-1 text-sm font-semibold text-slate-900">{followUpPlan.secondaryLabel}</div>
                <div className="mt-1 text-sm text-slate-700">{followUpPlan.outreachAngle}</div>
              </div>
              <div className="rounded-xl border bg-white p-3">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Suggested sequence</div>
                <div className="mt-1 text-sm font-semibold text-slate-900">{followUpPlan.sequenceLabel}</div>
                <ul className="mt-2 space-y-1 text-sm text-slate-700">
                  {followUpPlan.sequenceSteps.map((step) => (
                    <li key={step}>• {step}</li>
                  ))}
                </ul>
                <div className="mt-3 flex flex-wrap gap-2">
                  {followUpPlan.sequenceSteps.map((step, index) => (
                    <Link
                      key={`sequence-step-${index}`}
                      href={buildIntelligenceActivityKickoffHref(useExistingHref, {
                        ...kickoffPayload,
                        activityType: getSequenceStepActivityType(followUpPlan, index),
                        sequenceStepIndex: index,
                        sequenceStepLabel: step,
                      })}
                      className="rounded-xl border bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700 hover:bg-slate-100"
                    >
                      Prep step {index + 1}
                    </Link>
                  ))}
                </div>
              </div>
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href={buildIntelligenceActivityKickoffHref(useExistingHref, { ...kickoffPayload, activityType: "CALL" })} className={`rounded-xl border px-3 py-2 text-sm font-medium ${followUpPlan.primaryActivityType === "CALL" ? "border-blue-300 bg-blue-900 text-white" : "bg-white text-slate-700"}`}>Prep call</Link>
            <Link href={buildIntelligenceActivityKickoffHref(useExistingHref, { ...kickoffPayload, activityType: "EMAIL" })} className={`rounded-xl border px-3 py-2 text-sm font-medium ${followUpPlan.primaryActivityType === "EMAIL" ? "border-blue-300 bg-blue-900 text-white" : "bg-white text-slate-700"}`}>Prep email</Link>
            <Link href={buildIntelligenceActivityKickoffHref(useExistingHref, { ...kickoffPayload, activityType: "TASK" })} className={`rounded-xl border px-3 py-2 text-sm font-medium ${followUpPlan.primaryActivityType === "TASK" ? "border-blue-300 bg-blue-900 text-white" : "bg-white text-slate-700"}`}>Prep task</Link>
          </div>
        </div>
      </div>
      <div className="mt-4 grid gap-3 md:grid-cols-3">
        {decision.matchSignals.map((signal) => (
          <div key={signal} className="rounded-xl border bg-slate-50 p-3 text-sm text-slate-700">{signal}</div>
        ))}
      </div>
      <div className="mt-4 flex flex-wrap gap-2">
        <Link href={useExistingHref} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-slate-800">Work this record</Link>
        <Link href={createHref} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-slate-800">Create separate record</Link>
      </div>
    </section>
  );
}
