'use client';

import { useEffect, useId, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { Info, Plus } from 'lucide-react';
import { Button } from '@/components/ui/shared/Button';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import {
  ResponsiveDialogOverlay,
  ResponsiveDialogPanel,
} from '@/components/ui/shared/ResponsiveDialog';
import { FDI_LOWER_LEFT_TO_RIGHT, FDI_UPPER_LEFT_TO_RIGHT, getToothShapeKind } from '@/components/treatment/fdiToothMeta';
import {
  getToothColumnWidthRem,
  getToothGlyphWidthRem,
} from '@/components/treatment/fdiToothScale';
import { getRealisticToothAsset } from '@/components/treatment/realisticToothAssets';
import { toothEdgeKey } from '@/components/treatment/toothSelectionGroups';
import { ToothGlyph } from '@/components/ui/treatment/ToothGlyph';
import type { FdiToothId } from '@/types/treatment';

const TOOTH_NUMBER_GAP = 'mt-1';
/** Extra crown↔number space for realistic SVGs (outside arch transform so it is not cancelled). */
const REALISTIC_NUMBER_GAP = '2mm';
/** Tight interproximal gap between tooth columns. */
const TOOTH_GAP = 'gap-x-px';
/**
 * Centers a mark on the inline-end edge of a tooth column (between this tooth
 * and the next in flex order). Logical `end` + 0-width flex stays correct in LTR and RTL.
 */
const EDGE_MARK_ANCHOR =
  'absolute inset-y-0 end-0 z-10 w-0 flex items-center justify-center';

function quadrantMirrored(fdi: FdiToothId): boolean {
  const q = fdi[0];
  return q === '2' || q === '3';
}

/** Cartoon glyph height factor vs width (realistic assets use aspect ratio from viewBox). */
function cartoonHeightRem(fdi: FdiToothId, widthRem: number): number {
  const kind = getToothShapeKind(fdi);
  const factor = kind === 'canine' ? 2.85 : kind === 'molar' ? 2.45 : 2.65;
  return Number((widthRem * factor).toFixed(3));
}

function toothSize(fdi: FdiToothId): {
  columnWidthRem: number;
  glyphWidthRem: number;
  glyphHeightRem: number | 'auto';
} {
  const glyphWidthRem = getToothGlyphWidthRem(fdi);
  const columnWidthRem = getToothColumnWidthRem(fdi);
  const realistic = Boolean(getRealisticToothAsset(fdi));
  return {
    columnWidthRem,
    glyphWidthRem,
    glyphHeightRem: realistic ? 'auto' : cartoonHeightRem(fdi, glyphWidthRem),
  };
}

function ToothNumber({
  fdi,
  selected,
  widthRem,
  colorClass,
  style,
  interactive,
  disabled,
  onActivate,
}: {
  fdi: FdiToothId;
  selected: boolean;
  widthRem: number;
  colorClass: string;
  style?: CSSProperties;
  interactive: boolean;
  disabled: boolean;
  onActivate: (keys: { shiftKey: boolean; ctrlKey: boolean }) => void;
}) {
  const className = `text-[10px] tabular-nums text-center leading-none ${colorClass}`;
  const boxStyle: CSSProperties = { width: `${widthRem}rem`, ...style };

  if (!interactive) {
    return (
      <span className={className} style={boxStyle}>
        {fdi}
      </span>
    );
  }

  return (
    <button
      type="button"
      disabled={disabled}
      data-fdi={fdi}
      onMouseDown={(e) => {
        if (e.shiftKey || e.ctrlKey || e.metaKey) e.preventDefault();
      }}
      onPointerDown={(e) => {
        if (e.button !== 0) return;
        e.preventDefault();
        onActivate({ shiftKey: e.shiftKey, ctrlKey: e.ctrlKey || e.metaKey });
      }}
      onKeyDown={(e) => {
        if (e.key !== 'Enter' && e.key !== ' ') return;
        e.preventDefault();
        onActivate({ shiftKey: e.shiftKey, ctrlKey: e.ctrlKey || e.metaKey });
      }}
      aria-pressed={selected}
      className={`${className} bg-transparent select-none touch-manipulation focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 ${
        disabled ? 'cursor-not-allowed' : 'cursor-pointer'
      }`}
      style={boxStyle}
    >
      {fdi}
    </button>
  );
}

const CHART_TOOL_BTN_CLASS = 'h-8';

function ArchAssignControl({
  label,
  hint,
  highlighted,
  disabled,
  onClick,
}: {
  label: string;
  hint: string;
  highlighted: boolean;
  disabled: boolean;
  onClick: () => void;
}) {
  return (
    <Button
      type="button"
      size="sm"
      variant={highlighted ? 'secondary' : 'outline'}
      disabled={disabled}
      title={hint}
      aria-pressed={highlighted}
      onClick={onClick}
      className={`${CHART_TOOL_BTN_CLASS} gap-1 ${highlighted ? '' : 'border-dashed'}`}
    >
      {highlighted ? null : <Plus className="h-3.5 w-3.5 shrink-0" aria-hidden />}
      {label}
    </Button>
  );
}

function ArchLabelRow({
  placement,
  interactive,
  label,
  hint,
  highlighted,
  disabled,
  onClick,
}: {
  placement: 'upper' | 'lower';
  interactive: boolean;
  label: string;
  hint: string;
  highlighted: boolean;
  disabled: boolean;
  onClick: () => void;
}) {
  const spacing = placement === 'upper' ? 'mb-1' : 'mt-1';
  if (!interactive) {
    return (
      <p className={`text-[11px] uppercase tracking-wide text-text-muted ${spacing} text-center`}>
        {label}
      </p>
    );
  }
  return (
    <div className={`${spacing} flex justify-center`}>
      <ArchAssignControl
        label={label}
        hint={hint}
        highlighted={highlighted}
        disabled={disabled}
        onClick={onClick}
      />
    </div>
  );
}

interface FdiToothChartProps {
  selected: ReadonlySet<FdiToothId>;
  /**
   * Legacy / read-only: teeth in a connected bridge.
   * When `linkedEdges` is omitted, filled marks are shown between adjacent
   * selected teeth that both appear in this set.
   */
  connectedTeeth?: ReadonlySet<FdiToothId>;
  /** Filled connection edges (`toothEdgeKey(a,b)`). Preferred over `connectedTeeth` for edit mode. */
  linkedEdges?: ReadonlySet<string>;
  onToggle?: (fdi: FdiToothId, event: { shiftKey: boolean }) => void;
  /**
   * Click-to-assign (Exocad): click opens the job picker; Ctrl/drag or Shift copies the last jobs.
   * When set, this replaces `onToggle` for tooth hits.
   */
  onAssignPointer?: (
    fdi: FdiToothId,
    event: { shiftKey: boolean; ctrlKey: boolean; paint: boolean },
  ) => void;
  /** Toggle connect/disconnect for an adjacent selected pair. */
  onToggleLink?: (a: FdiToothId, b: FdiToothId) => void;
  disabled?: boolean;
  /** Non-interactive display (Cases / connection history). */
  readOnly?: boolean;
  /** Visual scale via CSS zoom (0.5 = half size). */
  scale?: number;
  /** Per-tooth accent color for selected glow (prosthesis / treatment-type palettes). */
  toothColors?: Partial<Record<FdiToothId, string>>;
  crownColors?: Partial<Record<FdiToothId, string>>;
  rootColors?: Partial<Record<FdiToothId, string>>;
  archHighlight?: 'upper' | 'lower' | 'both' | null;
  /** Extra control rendered next to Reset in the chart header (e.g. Full View). */
  headerControl?: ReactNode;
  /** Centered overlay on the odontogram (prosthesis picker). */
  overlay?: ReactNode;
  /** Wipe all selected teeth (and attached jobs in the parent). */
  onReset?: () => void;
  resetDisabled?: boolean;
  /** When set, overrides `selected.size > 0` for enabling Reset (e.g. arch jobs). */
  hasResetWork?: boolean;
  /** Overrides the Selected: line (arch labels, mixed arch + teeth). */
  selectedSummary?: ReactNode;
  /** Click Upper/Lower arch labels to assign jaw-level jobs. */
  onArchClick?: (arch: 'upper' | 'lower') => void;
  /** Compact card for embedded case detail panels. */
  compact?: boolean;
  /** Nested in the treatment editor — no extra card chrome. */
  embedded?: boolean;
  className?: string;
}

/**
 * Distal tip for arch look — gentler than pre-SVG angles so realistic glyphs stay readable.
 * Positive rotate = clockwise.
 */
const TOOTH_TWEAKS: Partial<Record<FdiToothId, { offset: number; rotate: number }>> = {
  '18': { offset: 5, rotate: -7 },
  '17': { offset: 6, rotate: -5 },
  '16': { offset: 6, rotate: -3.5 },
  '15': { offset: 6, rotate: -2 },
  '14': { offset: 5, rotate: -1 },
  '13': { offset: 5.5, rotate: -0.5 },
  '12': { offset: 4, rotate: -0.25 },
  '11': { offset: 5, rotate: 0 },
  '21': { offset: 5, rotate: 0 },
  '22': { offset: 4, rotate: 0.25 },
  '23': { offset: 5.5, rotate: 0.5 },
  '24': { offset: 5, rotate: 1 },
  '25': { offset: 6, rotate: 2 },
  '26': { offset: 6, rotate: 3.5 },
  '27': { offset: 6, rotate: 5 },
  '28': { offset: 5, rotate: 7 },

  '48': { offset: -5, rotate: -4 },
  '47': { offset: -6, rotate: -3 },
  '46': { offset: -6, rotate: -2 },
  '45': { offset: -6, rotate: -2 },
  '44': { offset: -5, rotate: -1 },
  '43': { offset: -4, rotate: -0.5 },
  '42': { offset: -4, rotate: -0.25 },
  '41': { offset: -3, rotate: 0 },
  '31': { offset: -3, rotate: 0 },
  '32': { offset: -4, rotate: 0.25 },
  '33': { offset: -4, rotate: 0.5 },
  '34': { offset: -5, rotate: 1 },
  '35': { offset: -6, rotate: 2 },
  '36': { offset: -6, rotate: 2 },
  '37': { offset: -6, rotate: 3 },
  '38': { offset: -5, rotate: 4 },
};

export function FdiToothChart({
  selected,
  connectedTeeth,
  linkedEdges,
  onToggle,
  onAssignPointer,
  onToggleLink,
  disabled,
  readOnly = false,
  scale = 1,
  toothColors,
  crownColors,
  rootColors,
  archHighlight = null,
  headerControl,
  overlay,
  onReset,
  resetDisabled,
  hasResetWork,
  selectedSummary,
  onArchClick,
  compact = false,
  embedded = false,
  className = '',
}: FdiToothChartProps) {
  const t = useTranslations('treatment');
  const tCommon = useTranslations('common');
  const uid = useId().replace(/:/g, '');
  const [hintOpen, setHintOpen] = useState(false);
  const paintingRef = useRef(false);
  const archPeak = 8;
  const interactive = !readOnly && (Boolean(onToggle) || Boolean(onAssignPointer));
  const linkInteractive = interactive && Boolean(onToggleLink);
  const isDisabled = disabled || readOnly;

  useEffect(() => {
    const endPaint = () => {
      paintingRef.current = false;
    };
    window.addEventListener('pointerup', endPaint);
    window.addEventListener('pointercancel', endPaint);
    return () => {
      window.removeEventListener('pointerup', endPaint);
      window.removeEventListener('pointercancel', endPaint);
    };
  }, []);

  const toothSizeClass = (fdi: FdiToothId) => toothSize(fdi);

  const archOffset = (index: number, count: number, upper?: boolean) => {
    const center = (count - 1) / 2;
    const dist = Math.abs(index - center) / center;
    const curve = (1 - Math.pow(dist, 1.45)) * archPeak;
    return upper ? curve : -curve;
  };

  const archRotate = (index: number, count: number) => {
    const center = (count - 1) / 2;
    const normalized = (index - center) / center;
    return normalized * 4;
  };

  const toothAccent = (fdi: FdiToothId) =>
    crownColors?.[fdi] ?? rootColors?.[fdi] ?? toothColors?.[fdi];

  const numberColorClass = (fdi: FdiToothId, isSel: boolean) => {
    if (!isSel) return 'text-text-muted';
    const accent = toothAccent(fdi);
    return accent ? '' : 'text-primary';
  };

  const numberStyle = (fdi: FdiToothId, isSel: boolean): CSSProperties | undefined => {
    if (!isSel) return undefined;
    const accent = toothAccent(fdi);
    return accent ? { color: accent } : undefined;
  };

  const edgeIsLinked = (a: FdiToothId, b: FdiToothId): boolean => {
    const key = toothEdgeKey(a, b);
    if (linkedEdges) return linkedEdges.has(key);
    // Read-only fallback: both teeth marked connected.
    return Boolean(connectedTeeth?.has(a) && connectedTeeth?.has(b));
  };

  /** Circles sit between neighbors, on the crown side (toward FDI numbers). */
  const EdgeRail = ({ teeth }: { teeth: FdiToothId[] }) => {
    const anyVisible = teeth.some((fdi, i) => {
      const next = teeth[i + 1];
      if (!next || !selected.has(fdi) || !selected.has(next)) return false;
      const linked = edgeIsLinked(fdi, next);
      return linkInteractive || linked;
    });
    if (!anyVisible) return null;

    return (
      <div
        className={`flex flex-nowrap justify-center ${TOOTH_GAP} min-w-max mx-auto w-fit h-3.5 items-center`}
      >
        {teeth.map((fdi, i) => {
          const size = toothSizeClass(fdi);
          const prev = i > 0 ? teeth[i - 1] : undefined;
          const next = teeth[i + 1];
          const showEdge = Boolean(next && selected.has(fdi) && selected.has(next));
          const linked = showEdge ? edgeIsLinked(fdi, next!) : false;
          const renderEdge = showEdge && (linkInteractive || linked);
          // Narrow link across this column when both neighboring edges are filled.
          const bridgeLine = Boolean(
            prev &&
              next &&
              selected.has(prev) &&
              selected.has(fdi) &&
              selected.has(next) &&
              edgeIsLinked(prev, fdi) &&
              edgeIsLinked(fdi, next),
          );

          return (
            <div
              key={`e-${fdi}`}
              className="relative h-3.5 flex items-center justify-center"
              style={{ width: `${size.columnWidthRem}rem` }}
            >
              {bridgeLine ? (
                <span
                  className="pointer-events-none absolute inset-x-0 top-1/2 z-0 h-[2px] -translate-y-1/2 bg-primary/75"
                  aria-hidden
                />
              ) : null}
              {renderEdge ? (
                <div className={EDGE_MARK_ANCHOR}>
                  {linkInteractive ? (
                    <button
                      type="button"
                      disabled={isDisabled}
                      title={linked ? t('toothUnlinkHint') : t('toothLinkHint')}
                      aria-label={
                        linked
                          ? t('toothUnlinkAria', { a: fdi, b: next! })
                          : t('toothLinkAria', { a: fdi, b: next! })
                      }
                      aria-pressed={linked}
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        onToggleLink?.(fdi, next!);
                      }}
                      className={`
                        h-3.5 w-3.5 shrink-0 rounded-full border-2 transition-colors
                        focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50
                        ${
                          linked
                            ? 'border-primary bg-primary shadow-sm'
                            : 'border-primary bg-background-secondary hover:bg-primary/15'
                        }
                        ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
                      `}
                    />
                  ) : (
                    <span
                      className="h-2.5 w-2.5 shrink-0 rounded-full bg-primary shadow-sm"
                      title={t('toothConnectedHint')}
                      aria-hidden
                    />
                  )}
                </div>
              ) : null}
            </div>
          );
        })}
      </div>
    );
  };

  const Row = ({ teeth, upper }: { teeth: FdiToothId[]; upper?: boolean }) => (
    <div className="flex flex-col items-center min-w-max mx-auto w-fit gap-y-0.5">
      {/* Lower: crowns face numbers above → rail above teeth */}
      {!upper ? <EdgeRail teeth={teeth} /> : null}
      <div className={`flex flex-nowrap justify-center ${TOOTH_GAP} min-w-max mx-auto w-fit`}>
        {teeth.map((fdi, i) => {
          const kind = getToothShapeKind(fdi);
          const gid = `${uid}-${fdi}`;
          const isSel = selected.has(fdi);
          const size = toothSizeClass(fdi);
          const tweak = TOOTH_TWEAKS[fdi];
          const offsetY = tweak ? tweak.offset : archOffset(i, teeth.length, upper);
          const rotate = tweak ? tweak.rotate : archRotate(i, teeth.length);
          const alignItems = upper ? 'items-end' : 'items-start';
          const accent = toothAccent(fdi);
          const realistic = Boolean(getRealisticToothAsset(fdi));

          const glyph = (
            <ToothGlyph
              fdi={fdi}
              kind={kind}
              gradientId={gid}
              selected={isSel}
              upper={upper}
              mirrored={quadrantMirrored(fdi)}
              upsideDown={upper}
              className="shrink-0 max-h-full"
              style={{
                width: `${size.glyphWidthRem}rem`,
                height: size.glyphHeightRem === 'auto' ? 'auto' : `${size.glyphHeightRem}rem`,
              }}
              accentColor={accent}
              crownAccent={crownColors?.[fdi]}
              rootAccent={rootColors?.[fdi]}
            />
          );

          /** Cover crown/root shift toward the numbers without overlapping neighbors. */
          const hitOverflowPx = Math.abs(offsetY);
          const activateTooth = (keys: { shiftKey: boolean; ctrlKey?: boolean }, paint = false) => {
            if (!interactive || isDisabled) return;
            const ctrlKey = Boolean(keys.ctrlKey);
            if (onAssignPointer) {
              onAssignPointer(fdi, {
                shiftKey: keys.shiftKey,
                ctrlKey,
                paint: paint || ctrlKey,
              });
              return;
            }
            onToggle?.(fdi, { shiftKey: keys.shiftKey });
          };

          return (
            <div
              key={fdi}
              className="flex flex-col items-center"
              style={{ width: `${size.columnWidthRem}rem` }}
            >
              {!upper && realistic ? (
                <div style={{ height: REALISTIC_NUMBER_GAP }} aria-hidden />
              ) : null}
              <div
                className={`group relative box-content flex ${alignItems} justify-center`}
                style={{
                  height: '7.25rem',
                  paddingBottom: upper ? hitOverflowPx : 0,
                  paddingTop: upper ? 0 : hitOverflowPx,
                }}
              >
                {interactive ? (
                  <button
                    type="button"
                    disabled={isDisabled}
                    data-fdi={fdi}
                    onMouseDown={(e) => {
                      if (e.shiftKey || e.ctrlKey || e.metaKey) e.preventDefault();
                    }}
                    onPointerDown={(e) => {
                      if (e.button !== 0) return;
                      e.preventDefault();
                      e.stopPropagation();
                      if (onAssignPointer && !e.shiftKey) {
                        paintingRef.current = true;
                      }
                      activateTooth({
                        shiftKey: e.shiftKey,
                        ctrlKey: e.ctrlKey || e.metaKey,
                      });
                    }}
                    onPointerEnter={() => {
                      if (!onAssignPointer || !paintingRef.current || isDisabled) return;
                      activateTooth({ shiftKey: false }, true);
                    }}
                    onPointerUp={() => {
                      paintingRef.current = false;
                    }}
                    onPointerCancel={() => {
                      paintingRef.current = false;
                    }}
                    onKeyDown={(e) => {
                      if (e.key !== 'Enter' && e.key !== ' ') return;
                      e.preventDefault();
                      activateTooth({ shiftKey: e.shiftKey, ctrlKey: e.ctrlKey || e.metaKey });
                    }}
                    className={`
                      absolute inset-y-[6%] z-10 rounded-[var(--radius-sm)] bg-transparent select-none touch-manipulation
                      focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50
                      ${isDisabled ? 'cursor-not-allowed' : 'cursor-pointer'}
                    `}
                    style={{ left: '22%', right: '22%' }}
                    aria-pressed={isSel}
                    aria-label={
                      isSel
                        ? `${t('toothAria', { fdi })}${t('toothSelectedSuffix')}`
                        : t('toothAria', { fdi })
                    }
                  />
                ) : null}
                <div
                  style={{ transform: `translateY(${offsetY}px) rotate(${rotate}deg)` }}
                  className={`pointer-events-none ${isDisabled ? 'opacity-50' : ''}`}
                  aria-hidden
                >
                  <div
                    className={`
                      rounded-[var(--radius-sm)] p-0.5 transition-transform duration-150
                      ${isSel ? 'scale-105' : ''}
                      ${
                        interactive && !isDisabled
                          ? '[@media(hover:hover)_and_(pointer:fine)]:group-hover:scale-105'
                          : ''
                      }
                    `}
                  >
                    {glyph}
                  </div>
                </div>
              </div>
              {upper && realistic ? (
                <div style={{ height: REALISTIC_NUMBER_GAP }} aria-hidden />
              ) : null}
            </div>
          );
        })}
      </div>
      {/* Upper: crowns face numbers below → rail below teeth */}
      {upper ? <EdgeRail teeth={teeth} /> : null}
    </div>
  );

  const cardClass = embedded
    ? 'space-y-2'
    : compact
      ? 'rounded-lg border border-border/60 bg-background-secondary/30 p-2 space-y-2'
      : 'surface-card p-3 space-y-3';

  const chartBody = (
    <>
      <ArchLabelRow
        placement="upper"
        interactive={Boolean(onArchClick && !readOnly)}
        label={t('upperArch')}
        hint={t('archAssignHint')}
        highlighted={archHighlight === 'upper' || archHighlight === 'both'}
        disabled={isDisabled}
        onClick={() => onArchClick?.('upper')}
      />

      <div className="overflow-x-auto py-1 -mx-1 px-1 select-none" dir="ltr">
        <div className="relative isolate min-w-max mx-auto w-fit select-none">
          <div
            className="pointer-events-none absolute left-1/2 top-3 bottom-3 w-px -translate-x-1/2 bg-border/70"
            aria-hidden
          />
          <div className="relative z-10 space-y-0">
            <div
              className={
                archHighlight === 'upper' || archHighlight === 'both'
                  ? 'rounded-lg bg-primary/10 ring-1 ring-primary/25'
                  : undefined
              }
              onClick={
                onArchClick && !readOnly && !isDisabled
                  ? (e) => {
                      if (e.target === e.currentTarget) onArchClick('upper');
                    }
                  : undefined
              }
            >
              <Row teeth={FDI_UPPER_LEFT_TO_RIGHT} upper />
            </div>
            <div className={`flex flex-nowrap justify-center ${TOOTH_GAP} ${TOOTH_NUMBER_GAP}`}>
              {FDI_UPPER_LEFT_TO_RIGHT.map((fdi) => (
                <ToothNumber
                  key={`u-${fdi}`}
                  fdi={fdi}
                  selected={selected.has(fdi)}
                  widthRem={toothSizeClass(fdi).columnWidthRem}
                  colorClass={numberColorClass(fdi, selected.has(fdi))}
                  style={numberStyle(fdi, selected.has(fdi))}
                  interactive={interactive}
                  disabled={isDisabled}
                  onActivate={(keys) => {
                    if (onAssignPointer) {
                      onAssignPointer(fdi, {
                        shiftKey: keys.shiftKey,
                        ctrlKey: keys.ctrlKey,
                        paint: keys.ctrlKey,
                      });
                      return;
                    }
                    onToggle?.(fdi, { shiftKey: keys.shiftKey });
                  }}
                />
              ))}
            </div>

            <div className="my-2 h-px w-full bg-border/70" role="separator" aria-hidden />

            <div className="pt-0.5">
              <div className={`flex flex-nowrap justify-center ${TOOTH_GAP}`}>
                {FDI_LOWER_LEFT_TO_RIGHT.map((fdi) => (
                  <ToothNumber
                    key={`l-${fdi}`}
                    fdi={fdi}
                    selected={selected.has(fdi)}
                    widthRem={toothSizeClass(fdi).columnWidthRem}
                    colorClass={numberColorClass(fdi, selected.has(fdi))}
                    style={numberStyle(fdi, selected.has(fdi))}
                    interactive={interactive}
                    disabled={isDisabled}
                  onActivate={(keys) => {
                    if (onAssignPointer) {
                      onAssignPointer(fdi, {
                        shiftKey: keys.shiftKey,
                        ctrlKey: keys.ctrlKey,
                        paint: keys.ctrlKey,
                      });
                      return;
                    }
                    onToggle?.(fdi, { shiftKey: keys.shiftKey });
                  }}
                />
              ))}
            </div>
            <div className={TOOTH_NUMBER_GAP}>
                <div
                  className={
                    archHighlight === 'lower' || archHighlight === 'both'
                      ? 'rounded-lg bg-primary/10 ring-1 ring-primary/25'
                      : undefined
                  }
                  onClick={
                    onArchClick && !readOnly && !isDisabled
                      ? (e) => {
                          if (e.target === e.currentTarget) onArchClick('lower');
                        }
                      : undefined
                  }
                >
                  <Row teeth={FDI_LOWER_LEFT_TO_RIGHT} />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <ArchLabelRow
        placement="lower"
        interactive={Boolean(onArchClick && !readOnly)}
        label={t('lowerArch')}
        hint={t('archAssignHint')}
        highlighted={archHighlight === 'lower' || archHighlight === 'both'}
        disabled={isDisabled}
        onClick={() => onArchClick?.('lower')}
      />
    </>
  );

  return (
    <div className={`${cardClass} ${className}`}>
      <div className="flex items-start justify-between gap-2">
        <div className="flex min-w-0 items-center gap-1">
          <h3 className="text-sm font-semibold text-text-primary">
            {compact || embedded ? t('toothChartTitleCompact') : t('toothChartTitle')}
          </h3>
          {!compact && !embedded ? (
            <button
              type="button"
              onClick={() => setHintOpen(true)}
              className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-text-muted hover:bg-background-card hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
              aria-label={t('toothChartHelpAria')}
            >
              <Info className="h-4 w-4" aria-hidden />
            </button>
          ) : null}
        </div>
        <div className="flex min-w-0 flex-col items-end gap-1.5">
          {headerControl || (onReset && !readOnly) ? (
            <div className="flex flex-wrap items-center justify-end gap-1.5">
              {headerControl}
              {onReset && !readOnly ? (
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  className={CHART_TOOL_BTN_CLASS}
                  disabled={resetDisabled || isDisabled || !(hasResetWork ?? selected.size > 0)}
                  onClick={onReset}
                  aria-label={t('resetChartAria')}
                >
                  {t('resetChart')}
                </Button>
              ) : null}
            </div>
          ) : null}
          <p className="min-w-0 text-[11px] text-text-secondary tabular-nums text-end">
            {t('selectedLabel')}{' '}
            {selectedSummary ??
              (selected.size === 0 ? t('selectedEmpty') : [...selected].sort().join(', '))}
          </p>
        </div>
      </div>

      {scale !== 1 ? (
        <div className="relative mx-auto w-fit origin-top" style={{ zoom: scale }}>
          {chartBody}
          {overlay}
        </div>
      ) : (
        <div className="relative">
          {chartBody}
          {overlay}
        </div>
      )}

      {hintOpen ? (
        <ResponsiveDialogOverlay onBackdropClick={() => setHintOpen(false)}>
          <ResponsiveDialogPanel
            role="dialog"
            aria-modal="true"
            aria-labelledby={`${uid}-chart-hint-title`}
            maxWidthClass="sm:max-w-md"
          >
            <div className="flex items-start justify-between gap-2 mb-3">
              <h4
                id={`${uid}-chart-hint-title`}
                className="text-sm font-semibold text-text-primary pe-2"
              >
                {t('toothChartHelpAria')}
              </h4>
              <DialogCloseButton onClick={() => setHintOpen(false)} />
            </div>
            <p className="text-sm text-text-secondary leading-relaxed">
              {onAssignPointer ? t('toothChartHintAssign') : t('toothChartHint')}
            </p>
            <div className="mt-4">
              <Button type="button" variant="outline" fullWidth onClick={() => setHintOpen(false)}>
                {tCommon('close')}
              </Button>
            </div>
          </ResponsiveDialogPanel>
        </ResponsiveDialogOverlay>
      ) : null}
    </div>
  );
}
