/**
 * Helpers for reading curtain-specific fields out of a FurnitureItem's
 * metadata bag. Kept in a standalone utility module so both the 3D mesh
 * and the properties panel can read/write the same shape without one
 * importing the other.
 *
 * Metadata shape (all keys optional):
 *   - `leftOpen`: number in [0, 1] — how far the LEFT panel is drawn aside
 *     (0 = fully closed, 1 = fully retracted to the left edge).
 *   - `rightOpen`: number in [0, 1] — mirror of `leftOpen` for the RIGHT
 *     panel.
 *   - `openAmount`: legacy symmetric field. Used as the fallback for both
 *     sides when `leftOpen` / `rightOpen` are absent so existing curtain
 *     rows keep rendering identically.
 *   - `fabricColor`: `#rrggbb` hex string. Falls back to the default when
 *     missing or malformed.
 */

export const DEFAULT_CURTAIN_OPEN_AMOUNT = 0;
export const DEFAULT_CURTAIN_FABRIC_COLOR = '#e8dfc8';

type MetadataBag = Record<string, unknown> | null | undefined;

function readOpenValue(raw: unknown): number | null {
  if (typeof raw !== 'number' || !Number.isFinite(raw)) return null;
  return Math.max(0, Math.min(1, raw));
}

/**
 * Legacy symmetric open amount. Returned only for UI compatibility —
 * the mesh and panel should prefer the per-side helpers below.
 */
export function getCurtainOpenAmount(metadata: MetadataBag): number {
  if (!metadata) return DEFAULT_CURTAIN_OPEN_AMOUNT;
  const v = readOpenValue(metadata['openAmount']);
  return v ?? DEFAULT_CURTAIN_OPEN_AMOUNT;
}

/**
 * Left panel open amount. Prefers the explicit `leftOpen` key, then falls
 * back to the legacy symmetric `openAmount`, then to the default.
 */
export function getCurtainLeftOpen(metadata: MetadataBag): number {
  if (!metadata) return DEFAULT_CURTAIN_OPEN_AMOUNT;
  const explicit = readOpenValue(metadata['leftOpen']);
  if (explicit !== null) return explicit;
  const legacy = readOpenValue(metadata['openAmount']);
  return legacy ?? DEFAULT_CURTAIN_OPEN_AMOUNT;
}

/** Right panel open amount. Symmetric counterpart to {@link getCurtainLeftOpen}. */
export function getCurtainRightOpen(metadata: MetadataBag): number {
  if (!metadata) return DEFAULT_CURTAIN_OPEN_AMOUNT;
  const explicit = readOpenValue(metadata['rightOpen']);
  if (explicit !== null) return explicit;
  const legacy = readOpenValue(metadata['openAmount']);
  return legacy ?? DEFAULT_CURTAIN_OPEN_AMOUNT;
}

/**
 * Returns the curtain fabric color as a `#rrggbb` hex string. Missing or
 * malformed values fall back to the shared default so legacy curtain rows
 * render correctly.
 */
export function getCurtainFabricColor(metadata: MetadataBag): string {
  if (!metadata) return DEFAULT_CURTAIN_FABRIC_COLOR;
  const raw = metadata['fabricColor'];
  return typeof raw === 'string' && /^#[0-9a-fA-F]{6}$/.test(raw) ? raw : DEFAULT_CURTAIN_FABRIC_COLOR;
}
