"use client";

import * as React from "react";
import { cn } from "cn";

/**
 * The design prototype's `.fra-*` form and panel primitives, rebuilt as
 * Tailwind on the `--fra-*` tokens in app/globals.css.
 *
 * These exist because the employee request screens are one visual system of
 * their own — the design ships them as `assets/css/flight-approval.css`, shared
 * across the overlay, the submitted page and the review page — and repeating a
 * fourteen-class input across three files is how two of them quietly drift
 * apart. Everything here is a faithful translation of that stylesheet, not a
 * reinterpretation: sizes, radii and colours are the values it specifies, read
 * through the tokens rather than hardcoded.
 *
 * Why not shadcn's Input/Label/Select: those are styled for corp's neutral
 * shadcn palette (`--input`, `--ring`, `--border`), which is a different system
 * from `--fra-*`. Dropping them in here would mean overriding most of their
 * classes at every call site, which reads as if the design were being fought.
 * Radix is still used for behaviour wherever behaviour is involved (see the
 * Dialog in RequestApprovalModal) — it is only the skin that is local.
 */

/* ── layout ──────────────────────────────────────────────────────────────── */

/** One numbered step of the overlay. Dashed rule between, none after the last. */
export function FraSection({
  step,
  title,
  note,
  action,
  children,
  className,
}: {
  step?: number;
  title: string;
  note?: string;
  action?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <section
      className={cn(
        "border-b border-dashed border-[var(--fra-border)] py-[20px] last:border-b-0",
        className
      )}
    >
      <div className="mb-[16px] flex items-center justify-between gap-[12px]">
        <h3 className="m-0 flex items-center gap-2.5 text-[15px] font-bold text-[var(--fra-heading)]">
          {step != null && (
            <span
              aria-hidden
              className="inline-flex size-6 shrink-0 items-center justify-center rounded-full bg-[var(--fra-coral)] text-xs text-white"
            >
              {step}
            </span>
          )}
          {title}
          {note && (
            <small className="ml-0.5 text-xs font-medium text-[var(--fra-muted)]">{note}</small>
          )}
        </h3>
        {action}
      </div>
      {children}
    </section>
  );
}

/* ── form controls ───────────────────────────────────────────────────────── */

const FIELD_BASE =
  "block w-full min-h-[38px] rounded-[var(--fra-radius-sm)] border border-[var(--fra-border-strong)] " +
  "bg-[var(--fra-surface)] px-[12px] py-2 text-sm leading-[1.4] text-[var(--fra-text)] outline-0 " +
  "transition-[border-color,box-shadow] placeholder:text-[var(--fra-muted)] placeholder:opacity-80 " +
  "hover:border-[var(--fra-muted)] " +
  "focus:border-[var(--fra-navy-2)] focus:shadow-[0_0_0_3px_rgba(27,77,97,0.15)] " +
  "disabled:cursor-not-allowed disabled:opacity-60 " +
  "aria-[invalid=true]:border-[var(--fra-rejected)] " +
  "aria-[invalid=true]:shadow-[0_0_0_3px_rgba(220,38,38,0.12)]";

/**
 * A labelled field.
 *
 * The label is always visible and always bound by `htmlFor` — a placeholder is
 * not a label, and it disappears exactly when someone is typing and most needs
 * it. The error sits directly beneath its own field rather than in a summary at
 * the top, and `aria-describedby` ties the two together so a screen reader
 * announces the reason, not just "invalid".
 */
export function FraField({
  id,
  label,
  required,
  error,
  hint,
  className,
  children,
}: {
  id: string;
  label: string;
  required?: boolean;
  error?: string;
  hint?: string;
  className?: string;
  children: (props: {
    id: string;
    "aria-invalid": boolean;
    "aria-describedby": string | undefined;
  }) => React.ReactNode;
}) {
  const errorId = `${id}-error`;
  const hintId = `${id}-hint`;
  const describedBy = [error ? errorId : null, hint ? hintId : null].filter(Boolean).join(" ");

  return (
    <div className={className}>
      <label htmlFor={id} className="mb-1.5 block text-[13px] font-semibold text-[var(--fra-text)]">
        {label}
        {required && (
          <>
            {" "}
            <span aria-hidden className="text-[var(--fra-coral)] not-italic">
              *
            </span>
            <span className="sr-only">(required)</span>
          </>
        )}
      </label>
      {children({
        id,
        "aria-invalid": Boolean(error),
        "aria-describedby": describedBy || undefined,
      })}
      {hint && !error && (
        <p id={hintId} className="mt-1.5 text-xs text-[var(--fra-muted)]">
          {hint}
        </p>
      )}
      {error && (
        <p id={errorId} className="mt-1.5 text-[13px] font-medium text-[var(--fra-rejected)]">
          {error}
        </p>
      )}
    </div>
  );
}

export function FraInput({ className, ...props }: React.ComponentProps<"input">) {
  return <input className={cn(FIELD_BASE, className)} {...props} />;
}

export function FraTextarea({ className, ...props }: React.ComponentProps<"textarea">) {
  return <textarea className={cn(FIELD_BASE, "min-h-24 resize-y", className)} {...props} />;
}

/**
 * Native `<select>` with the design's chevron.
 *
 * Native rather than a Radix listbox on purpose: these are short, flat,
 * single-choice lists with no search and no grouping, and the platform control
 * already gets keyboard, type-ahead and the mobile wheel right for free.
 */
export function FraSelect({ className, children, ...props }: React.ComponentProps<"select">) {
  return (
    <div className="relative">
      <select
        className={cn(FIELD_BASE, "cursor-pointer appearance-none pr-9", className)}
        {...props}
      >
        {children}
      </select>
      <svg
        aria-hidden
        viewBox="0 0 16 16"
        className="pointer-events-none absolute top-1/2 right-3 size-3 -translate-y-1/2 fill-none stroke-[var(--fra-muted)] stroke-2"
      >
        <path d="M4 6l4 4 4-4" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </div>
  );
}

/** Prefixed input — the design puts a `$` inside the additional-cost field. */
export function FraInputWithPrefix({
  prefix,
  className,
  ...props
}: React.ComponentProps<"input"> & { prefix: string }) {
  return (
    <div className="relative">
      <span
        aria-hidden
        className="absolute top-1/2 left-3 -translate-y-1/2 text-[15px] text-[var(--fra-muted)]"
      >
        {prefix}
      </span>
      <input className={cn(FIELD_BASE, "pl-8", className)} {...props} />
    </div>
  );
}

/* ── buttons ─────────────────────────────────────────────────────────────── */

const BTN_BASE =
  "inline-flex items-center justify-center gap-2 rounded-[var(--fra-radius-sm)] border " +
  "border-transparent px-3.5 text-sm font-semibold leading-none whitespace-nowrap " +
  "transition-[background-color,border-color,color,box-shadow] " +
  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-coral)] " +
  "disabled:cursor-not-allowed disabled:opacity-50 active:translate-y-px";

/**
 * Heights are 44px, not the prototype's 36px.
 *
 * The design is a desktop mockup; 36px is below the 44x44 minimum touch target,
 * and these are the two controls that submit or abandon a travel request. The
 * rest of the design — radii, colours, weight, the shadow under the primary —
 * is unchanged, so it still reads as the same button.
 */
export const fraButton = {
  primary: cn(
    BTN_BASE,
    "h-11 bg-[var(--fra-coral)] text-white shadow-[0_4px_14px_rgba(244,93,107,0.35)]",
    "hover:bg-[var(--fra-coral-dark)] focus:bg-[var(--fra-coral-dark)]"
  ),
  ghost: cn(
    BTN_BASE,
    "h-11 border-[var(--fra-border-strong)] bg-[var(--fra-surface)] text-[var(--fra-text)]",
    "hover:border-[var(--fra-muted)] hover:bg-[var(--fra-hover)]"
  ),
  approve: cn(
    BTN_BASE,
    "h-11 bg-[var(--fra-approved-solid)] text-white hover:bg-[var(--fra-approved-hover)]"
  ),
};

/** A text button — the design's "Edit" pencil. 44px tap area via padding. */
export function FraLinkButton({ className, ...props }: React.ComponentProps<"button">) {
  return (
    <button
      type="button"
      className={cn(
        "-m-2 inline-flex items-center gap-1.5 bg-transparent p-2 text-[13px] font-medium",
        "text-[var(--fra-muted)] transition-colors hover:text-[var(--fra-coral)]",
        "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-coral)]",
        className
      )}
      {...props}
    />
  );
}

/* ── small display pieces ────────────────────────────────────────────────── */

export function FraAvatar({ name, className }: { name: string; className?: string }) {
  const initials =
    name
      .trim()
      .split(/\s+/)
      .slice(0, 2)
      .map((p) => p.charAt(0).toUpperCase())
      .join("") || "?";
  return (
    <span
      aria-hidden
      className={cn(
        "inline-flex size-9 shrink-0 items-center justify-center rounded-full",
        "bg-[var(--fra-navy-2)] text-xs font-bold text-white",
        className
      )}
    >
      {initials}
    </span>
  );
}

export type FraStatusTone = "pending" | "approved" | "rejected" | "info";

const TONE: Record<FraStatusTone, string> = {
  pending: "bg-[var(--fra-pending-bg)] text-[var(--fra-pending)]",
  approved: "bg-[var(--fra-approved-bg)] text-[var(--fra-approved)]",
  rejected: "bg-[var(--fra-rejected-bg)] text-[var(--fra-rejected)]",
  info: "bg-[var(--fra-info-bg)] text-[var(--fra-info)]",
};

export function FraBadge({
  tone,
  children,
  className,
}: {
  tone: FraStatusTone;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold",
        "leading-[1.2] whitespace-nowrap",
        TONE[tone],
        className
      )}
    >
      <span aria-hidden className="size-1.5 rounded-full bg-current" />
      {children}
    </span>
  );
}

/** The est.-total row under the policy checks. */
export function FraTotalRow({ label, value }: { label: string; value: string }) {
  return (
    <div
      className={cn(
        "flex items-center justify-between rounded-[10px] border border-[var(--fra-border)]",
        "bg-[var(--fra-surface-2)] px-3.5 py-[12px] text-sm"
      )}
    >
      <span>{label}</span>
      <strong className="text-lg text-[var(--fra-heading)]">{value}</strong>
    </div>
  );
}
