"use client";

// ---------------------------------------------------------------------------
// KratosMessages — renders flow-level messages (ui.messages) as banners
// ---------------------------------------------------------------------------
// Node-level (per-field) messages are rendered inline by KratosFlowForm.
// This component surfaces the flow-wide messages: "An email containing a
// recovery code has been sent", "The recovery code is invalid or has already
// been used", etc.
// ---------------------------------------------------------------------------

import { CheckCircle2, CircleAlert, Info } from "lucide-react";
import type { KratosFlow, KratosMessage } from "@/lib/kratos";

function variantClasses(type: string): string {
  switch (type) {
    case "error":
      return "bg-destructive/10 text-destructive";
    case "success":
      return "bg-green-500/10 text-green-700 dark:text-green-400";
    default:
      return "bg-primary/10 text-primary";
  }
}

function Icon({ type }: { type: string }) {
  if (type === "error") return <CircleAlert className="size-4 shrink-0" />;
  if (type === "success") return <CheckCircle2 className="size-4 shrink-0" />;
  return <Info className="size-4 shrink-0" />;
}

interface KratosMessagesProps {
  /** Either the whole flow (ui.messages used) or an explicit message list. */
  flow?: KratosFlow | null;
  messages?: KratosMessage[];
  /** Extra ad-hoc error string (e.g. a network failure outside Kratos). */
  error?: string | null;
}

export function KratosMessages({ flow, messages, error }: KratosMessagesProps) {
  const list: KratosMessage[] = messages ?? flow?.ui.messages ?? [];

  if (list.length === 0 && !error) return null;

  return (
    <div className="flex flex-col gap-2">
      {error && (
        <div
          role="alert"
          aria-live="assertive"
          className="flex items-center gap-2 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive"
        >
          <CircleAlert className="size-4 shrink-0" />
          {error}
        </div>
      )}
      {list.map((m, i) => (
        <div
          key={m.id ?? i}
          role={m.type === "error" ? "alert" : "status"}
          aria-live={m.type === "error" ? "assertive" : "polite"}
          className={`flex items-center gap-2 rounded-md px-3 py-2 text-sm ${variantClasses(m.type)}`}
        >
          <Icon type={m.type} />
          {m.text}
        </div>
      ))}
    </div>
  );
}
