// [nexus] Assistant home-state greeting (Phase 9).
//
// Rendered as an assistant-turn message bubble when no conversation is
// active. Derives its body from `useAssistantHomeStatus` (or an injected
// status for unit testing) and presents a conversational "here's where
// you left off" summary instead of a dashboard grid.
import { ChatMarkdownMessage } from "../ChatMarkdownMessage";
import type { AssistantHomeStatus } from "../../hooks/useAssistantHomeStatus";
import { cn } from "@/lib/utils";

export interface AssistantHomeGreetingProps {
  status: AssistantHomeStatus;
  /**
   * Display name used in the greeting line. If omitted, the greeting drops
   * the personalised suffix.
   */
  userName?: string | null;
  /**
   * Exposed for deterministic tests. Defaults to `new Date()`.
   */
  now?: Date;
  className?: string;
}

function greetingForHour(hour: number, userName: string | null | undefined): string {
  let prefix: string;
  if (hour < 5 || hour >= 22) prefix = "Good evening";
  else if (hour < 12) prefix = "Good morning";
  else if (hour < 17) prefix = "Good afternoon";
  else prefix = "Good evening";
  const who = userName?.trim();
  return who ? `${prefix}, ${who}.` : `${prefix}.`;
}

/**
 * Build the markdown body of the greeting. Exposed for unit tests so they can
 * assert bullet content without poking into the rendered DOM.
 */
export function buildGreetingMarkdown(
  status: AssistantHomeStatus,
  userName: string | null | undefined,
  now: Date,
): string {
  const lines: string[] = [];
  lines.push(greetingForHour(now.getHours(), userName));
  lines.push("");

  const bullets: string[] = [];

  if (status.activeAgents > 0) {
    bullets.push(
      `${status.activeAgents} agent${status.activeAgents === 1 ? "" : "s"} currently working`,
    );
  }

  for (const gate of status.pendingGates) {
    const label = gate.projectName
      ? `${gate.projectName}: ${gate.gateName} awaiting approval`
      : `${gate.gateName} awaiting approval`;
    bullets.push(label);
  }

  for (const completion of status.recentCompletions) {
    const label = completion.projectName
      ? `${completion.projectName}: ${completion.summary} (${completion.when})`
      : `${completion.summary} (${completion.when})`;
    bullets.push(label);
  }

  for (const stale of status.staleProjects) {
    bullets.push(`${stale.name}: idle ${stale.lastActivity}`);
  }

  if (bullets.length > 0) {
    lines.push("Since we last talked:");
    for (const b of bullets) lines.push(` - ${b}`);
    lines.push("");
  } else if (!status.loading) {
    lines.push("Everything's quiet right now. Nothing waiting on you.");
    lines.push("");
  }

  lines.push("What do you want to do?");
  return lines.join("\n");
}

export function AssistantHomeGreeting({
  status,
  userName,
  now,
  className,
}: AssistantHomeGreetingProps) {
  if (status.loading) {
    return (
      <div
        data-testid="assistant-home-greeting-loading"
        className={cn("py-8 text-sm text-muted-foreground", className)}
      >
        Catching up…
      </div>
    );
  }

  const body = buildGreetingMarkdown(status, userName, now ?? new Date());

  return (
    <article
      data-testid="assistant-home-greeting"
      aria-label="Assistant home greeting"
      className={cn("flex gap-3 py-6", className)}
    >
      <div
        aria-hidden="true"
        className="mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-[4px] border border-border text-primary"
      >
        <span className="text-[11px] font-semibold uppercase tracking-[0.1em]">AI</span>
      </div>
      <div
        className={cn(
          "max-w-[620px] rounded-[8px] border border-border bg-card px-4 py-3",
          "text-sm leading-relaxed text-foreground",
          "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background",
        )}
      >
        <ChatMarkdownMessage content={body} />
      </div>
    </article>
  );
}
