"use client";

import type { ReactNode } from "react";
import { useTranslation } from "@enode/core/translations/hooks";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import { useUnreadCount } from "@enode/core/notifications/hooks";
import { EnodeMark } from "@enode/ui/enode-mark";
import {
  BellFillIcon,
  BugIcon,
  GlobeIcon,
  LiveFillIcon,
  PersonFillIcon,
  SidebarIcon,
  StationsFillIcon,
} from "./icons";
import { useLiveSessionEntry } from "./live-session-row";
import { useCheckInPromptOpen } from "./notifications/open-prompts";
import {
  RAIL_WIDTH,
  uploadBadge,
  type RailMenuItem,
  type UploadBadge,
} from "./tablet-rail-model";
import { useOfflineStatus } from "./use-offline-status";

/**
 * The rail's surface: the avatar fallback's muted platinum-green stops, top to
 * bottom (a diagonal on a tall, narrow rail reads as a left→right fade). Light
 * in light mode, dark in dark mode, so `text-foreground-default` keeps the
 * icons legible on both.
 */
export const RAIL_SURFACE_CLASS =
  "bg-gradient-to-b from-foreground-platinum-green-disabled to-foreground-platinum-green-disabled/40 text-foreground-default";

/**
 * Reversible trial: the rail in plain Deep Green with white icons, identical
 * in light and dark mode. `false` restores {@link RAIL_SURFACE_CLASS}.
 *
 * @remarks The rail renders as a `.theme-dark` subtree, so everything on it
 * that reads a token (badges, the live dot's success / warning, the unread
 * dot) takes its dark-surface value in both schemes. Its popovers are portaled
 * to `document.body`, so they keep the page's scheme.
 */
const DEEP_GREEN_RAIL = true;

const RAIL_NAV_SURFACE_CLASS = DEEP_GREEN_RAIL
  ? "theme-dark bg-brand-deep-green text-white"
  : RAIL_SURFACE_CLASS;

// Active item, divider and avatar: white on the Deep Green rail; the old rail
// keeps its red-orange active tile and platinum-green details.
export const RAIL_ACTIVE_CLASS = DEEP_GREEN_RAIL
  ? "bg-white/15 text-white"
  : "bg-foreground-red-orange/10 text-brand-red-orange";
const RAIL_DIVIDER_CLASS = DEEP_GREEN_RAIL
  ? "border-white/25"
  : "border-foreground-platinum-green/50";
const RAIL_AVATAR_CLASS = DEEP_GREEN_RAIL
  ? "bg-white/15 text-white ring-1 ring-white/25"
  : "bg-gradient-to-br from-foreground-platinum-green-disabled to-foreground-platinum-green-disabled/60 text-foreground-default ring-1 ring-surface-stroke-muted";

// The tablet's main navigation: a narrow rail of icon-only buttons (Live,
// Stations, Notifications, Portal at the top; Account alone at the foot). Each item's
// name and state live in its aria-label and tooltip; status shows as a dot or
// badge on the icon. Like the iPadOS sidebar, the rail collapses off the left
// edge (the sidebar button at its top); the same button in the first column's
// header brings it back (`rail-header-toggle.tsx`). Stations,
// Notifications and Account each open a menu beside themselves (`RailPopover`); a menu entry opens a screen in
// the content area. `TabletRailView` is pure props so galleries and tests can
// render it; `TabletRail` feeds it from the live hooks. Colours are design
// tokens only, so light and dark both work.

/** Which live-session caption the Live item shows. */
export type RailLiveState = "none" | "waiting" | "live";

/** Plain props of {@link TabletRailView}: state plus callbacks, no hooks. */
export interface TabletRailViewProps {
  /** Live item: not in a session, in the lobby (waiting), or live. */
  liveState: RailLiveState;
  /** Opens the join / session sheet. */
  onOpenLive: () => void;
  /** What the Live tap opened, rendered beside the rail. */
  liveSheet?: ReactNode;
  /** Opens the Enode Portal (History). */
  onOpenPortal: () => void;
  /** Upload badge on the "Stations" item. */
  upload: UploadBadge;
  /** Toggles the Stations menu beside the item (the item is its anchor). */
  onOpenStations: (anchor: HTMLElement) => void;
  /** The foot item shown active: its menu or one of its screens is open. */
  active?: RailMenuItem | null;
  /** The foot item whose menu is open (aria-expanded). */
  expanded?: RailMenuItem | null;
  /** Unread notifications waiting. */
  unreadCount: number;
  /** Toggles the Alerts menu beside the item. */
  onOpenNotifications: (anchor: HTMLElement) => void;
  /** Initials for the account avatar; empty or absent shows a person icon. */
  initials?: string;
  /** Toggles the Account menu beside the item. */
  onOpenAccount: (anchor: HTMLElement) => void;
  /** Hides the rail; absent = no collapse button. */
  onCollapse?: () => void;
  /** Opens the debug screens; given in debug builds only (bug item). */
  onOpenDebug?: () => void;
}

/** Props of the live {@link TabletRail}. */
export interface TabletRailProps {
  onOpenPortal: () => void;
  onOpenStations: (anchor: HTMLElement) => void;
  active?: RailMenuItem | null;
  expanded?: RailMenuItem | null;
  onOpenNotifications: (anchor: HTMLElement) => void;
  onOpenAccount: (anchor: HTMLElement) => void;
  onCollapse?: () => void;
  onOpenDebug?: () => void;
}

/** Icon-only rail button: 48 px square, the shared tap target of every item. */
const RAIL_BUTTON_CLASS =
  "flex size-12 shrink-0 items-center justify-center rounded-xl transition-colors hover:bg-current/10";

/** Rail button without the hover / active tile (the account avatar). */
const RAIL_BARE_BUTTON_CLASS =
  "flex size-12 shrink-0 items-center justify-center rounded-full";

function RailItem({
  label,
  caption,
  badgeLabel,
  description,
  onClick,
  icon,
  testId,
  active = false,
  menuOpen,
  tile = true,
}: {
  /**
   * Hover / active tile behind the icon. Off for the account avatar: the
   * tile drew a halo around the circle (sticky after a tap on iPad); the
   * avatar shows its own active state.
   */
  tile?: boolean;
  /** Marks the current destination (aria-current, tinted tile). */
  active?: boolean;
  /** Set for items that open a menu: whether it is open (aria-expanded). */
  menuOpen?: boolean;
  label: string;
  /** The item's state, spoken after the label (the icon shows it as a dot). */
  caption: string;
  /** Extra spoken text (e.g. the upload badge), appended to the aria-label. */
  badgeLabel?: string;
  description?: string;
  /** Gets the item's button, for a menu anchored to it. */
  onClick: (target: HTMLElement) => void;
  icon: ReactNode;
  testId: string;
}) {
  const ariaLabel = [
    label,
    caption !== label ? caption : "",
    badgeLabel ?? "",
  ]
    .filter((part) => part !== "")
    .join(", ");
  return (
    // eslint-disable-next-line jsx-a11y/role-supports-aria-props -- spec asks for aria-description
    <button
      type="button"
      onClick={(event) => onClick(event.currentTarget)}
      aria-label={ariaLabel}
      aria-description={description}
      aria-current={active ? "page" : undefined}
      aria-haspopup={menuOpen === undefined ? undefined : "dialog"}
      aria-expanded={menuOpen}
      title={label}
      data-testid={testId}
      className={
        tile
          ? `${RAIL_BUTTON_CLASS} ${
              active ? RAIL_ACTIVE_CLASS : ""
            }`
          : RAIL_BARE_BUTTON_CLASS
      }
    >
      {icon}
    </button>
  );
}

/**
 * One size for every rail icon (24 px in the 48 px button, 2026-11-23): the
 * glyphs are solid and fill their box, so they read with the same weight.
 */
const RAIL_ICON_CLASS = "size-6";

function IconBox({ children }: { children: ReactNode }) {
  return (
    <span className="relative flex size-7 items-center justify-center">
      {children}
    </span>
  );
}

/**
 * The tablet side rail, pure: everything arrives as props. Same markup the
 * live {@link TabletRail} renders.
 */
export function TabletRailView({
  liveState,
  onOpenLive,
  liveSheet,
  onOpenPortal,
  upload,
  onOpenStations,
  active = null,
  expanded = null,
  unreadCount,
  onOpenNotifications,
  initials,
  onOpenAccount,
  onCollapse,
  onOpenDebug,
}: TabletRailViewProps) {
  const { t } = useTranslation();

  const liveCaption =
    liveState === "live"
      ? t("Live")
      : liveState === "waiting"
        ? t("Waiting")
        : t("Join");

  const alertsCaption =
    unreadCount > 0 ? t("{count} new", { count: unreadCount }) : t("None");

  // "Stations": what its menu holds (the training and feedback stations of
  // this device). No device word, so Android never reads "iPad", and not
  // "This device" — that name belongs to the Settings tab alone. The save
  // state lives in its menu, not as a caption here.
  const stations = t("Stations");
  const badgeLabel =
    upload.kind === "waiting"
      ? t("{count, plural, one {# waiting to upload} other {# waiting to upload}}", {
          count: upload.count,
        })
      : upload.kind === "failed"
        ? t("{count, plural, one {# upload failed} other {# uploads failed}}", {
            count: upload.count,
          })
        : undefined;

  return (
    <nav
      aria-label={t("Main")}
      style={{ width: RAIL_WIDTH }}
      // Scrolls (scroll bar hidden) when the window is shorter than the rail's
      // items — otherwise the account at the foot is clipped
      // off the bottom and unreachable.
      className={`flex h-full min-h-0 shrink-0 flex-col items-center gap-1 overflow-y-auto overscroll-contain scrollbar-none pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-[calc(0.75rem+env(safe-area-inset-top))] ${RAIL_NAV_SURFACE_CLASS}`}
    >
      <div className="flex h-12 shrink-0 items-center justify-center">
        <EnodeMark className="size-7" />
      </div>

      {onCollapse && (
        <button
          type="button"
          onClick={onCollapse}
          aria-label={t("Hide sidebar")}
          title={t("Hide sidebar")}
          data-testid="rail-collapse"
          className={RAIL_BUTTON_CLASS}
        >
          <SidebarIcon className="h-5 w-6" />
        </button>
      )}
      {onCollapse && (
        // Thin divider: the collapse button is rail chrome, the items below
        // are the navigation.
        <div
          aria-hidden="true"
          className={`my-1 w-8 shrink-0 border-t ${RAIL_DIVIDER_CLASS}`}
        />
      )}

      <RailItem
        testId="rail-live"
        label={t("Live")}
        caption={liveCaption}
        onClick={onOpenLive}
        icon={
          <IconBox>
            <LiveFillIcon className={RAIL_ICON_CLASS} />
            {liveState !== "none" && (
              <span
                aria-hidden="true"
                className={`absolute -top-0.5 -right-0.5 size-2 rounded-full ${
                  liveState === "live"
                    ? "bg-feedback-success"
                    : "bg-feedback-warning"
                }`}
              />
            )}
          </IconBox>
        }
      />
      {liveSheet}

      <RailItem
        testId="rail-stations"
        label={stations}
        caption=""
        badgeLabel={badgeLabel}
        active={active === "stations"}
        menuOpen={expanded === "stations"}
        onClick={onOpenStations}
        icon={
          <IconBox>
            <StationsFillIcon className={RAIL_ICON_CLASS} />
            {upload.kind !== "none" ? (
              <span
                aria-hidden="true"
                className={`absolute -top-0.5 -right-1.5 min-w-4 rounded-full px-1 text-center text-[10px] font-semibold leading-4 ${
                  upload.kind === "failed"
                    ? "bg-foreground-red-orange/10 text-foreground-default ring-1 ring-foreground-red-orange/30"
                    : "bg-feedback-warning-surface text-feedback-warning ring-1 ring-feedback-warning"
                }`}
              >
                {upload.count > 9 ? "9+" : upload.count}
              </span>
            ) : null}
          </IconBox>
        }
      />

      <RailItem
        testId="rail-alerts"
        label={t("Notifications")}
        caption={alertsCaption}
        active={active === "alerts"}
        menuOpen={expanded === "alerts"}
        onClick={onOpenNotifications}
        icon={
          <IconBox>
            <BellFillIcon className={RAIL_ICON_CLASS} />
            {unreadCount > 0 && (
              <span
                aria-hidden="true"
                className="absolute -top-0.5 -right-0.5 size-2 rounded-full bg-foreground-red-orange"
              />
            )}
          </IconBox>
        }
      />

      <RailItem
        testId="rail-history"
        label={t("Portal")}
        caption=""
        description={t("opens the Enode Portal")}
        onClick={onOpenPortal}
        icon={
          <IconBox>
            <GlobeIcon className={RAIL_ICON_CLASS} />
          </IconBox>
        }
      />

      {/* Everything above is the rail's items; Account alone sits at the
          foot (ADR 0015, 2026-11-23). */}
      <div className="flex-1" />

      {onOpenDebug && (
        <RailItem
          testId="rail-debug"
          label={t("Debug")}
          caption=""
          onClick={onOpenDebug}
          icon={
            <IconBox>
              <BugIcon className={RAIL_ICON_CLASS} />
            </IconBox>
          }
        />
      )}

      <RailItem
        testId="rail-account"
        label={t("Account")}
        caption=""
        active={active === "account"}
        menuOpen={expanded === "account"}
        onClick={onOpenAccount}
        tile={false}
        icon={
          <span
            // The avatar looks the same open or not — no orange tint when
            // its menu or a screen of it is open (owner 23.11.26; a ring read
            // as a warning outline, owner 20.11.26). aria-current and
            // aria-expanded still say it.
            className={`flex size-11 shrink-0 items-center justify-center rounded-full text-sm font-medium ${RAIL_AVATAR_CLASS}`}
          >
            {initials ? initials : <PersonFillIcon className="size-5" />}
          </span>
        }
      />
    </nav>
  );
}

/** Up to two initials from a display name, uppercased; "" when there is none. */
function initialsOf(name: string | null | undefined): string {
  const parts = (name ?? "").trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return "";
  const first = parts[0]!.charAt(0);
  const last = parts.length > 1 ? parts[parts.length - 1]!.charAt(0) : "";
  return (first + last).toUpperCase();
}

/**
 * The live tablet rail: reads the upload status, live
 * session entry, unread count and signed-in user, and renders
 * {@link TabletRailView}.
 */
export function TabletRail({
  onOpenPortal,
  onOpenStations,
  active,
  expanded,
  onOpenNotifications,
  onOpenAccount,
  onCollapse,
  onOpenDebug,
}: TabletRailProps) {
  const offline = useOfflineStatus();
  const entry = useLiveSessionEntry();
  const unread = useUnreadCount();
  const checkInOpen = useCheckInPromptOpen();
  const user = useCurrentUser();

  const liveState: RailLiveState =
    entry.state === "none"
      ? "none"
      : entry.state === "live"
        ? "live"
        : "waiting";

  return (
    <TabletRailView
      liveState={liveState}
      onOpenLive={entry.open}
      liveSheet={entry.sheet}
      onOpenPortal={onOpenPortal}
      upload={uploadBadge({
        pendingCount: offline.pendingCount,
        pendingVideoCount: offline.pendingVideoCount,
        pendingAnswerCount: offline.pendingAnswerCount,
        stuckCount: offline.stuckCount,
      })}
      onOpenStations={onOpenStations}
      active={active}
      expanded={expanded}
      unreadCount={unread + (checkInOpen ? 1 : 0)}
      onOpenNotifications={onOpenNotifications}
      initials={initialsOf(user?.name)}
      onOpenAccount={onOpenAccount}
      onCollapse={onCollapse}
      onOpenDebug={onOpenDebug}
    />
  );
}

