export const FEATURE_PANEL_WIDTH = 480

const SCREEN_WIDTH = 1920
const SCREEN_HEIGHT = 1080
const PANEL_DEFAULT_HEIGHT = 176
const PANEL_MIN_VISIBLE_HEIGHT = 112
const PANEL_MAX_HEIGHT = 272
const PANEL_ANCHOR_GAP = 18

function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max)
}

/**
 * Presentation-only layout for map feature cards.
 * Keeps the card above the clicked feature and shrinks the scrollable body when
 * vertical space is limited. Querying and selected-feature state stay untouched.
 */
export function createFeaturePanelLayout({
  point,
  rowCount = 0,
  loading = false,
  empty = false,
  safeLeft = 448,
  safeRight = 1472,
  preferredTop = 196,
  safeTop = 94,
}) {
  if (!point) {
    return {
      width: FEATURE_PANEL_WIDTH,
      height: PANEL_DEFAULT_HEIGHT,
      style: {},
    }
  }

  const normalizedRows = clamp(Number(rowCount) || 0, 0, 10)
  const contentHeight = loading || empty
    ? PANEL_DEFAULT_HEIGHT
    : 58 + Math.max(normalizedRows, 1) * 27
  const desiredHeight = clamp(contentHeight, PANEL_DEFAULT_HEIGHT, PANEL_MAX_HEIGHT)
  const anchorBottom = clamp(point.y - PANEL_ANCHOR_GAP, 72, SCREEN_HEIGHT - 28)
  const preferredSpace = anchorBottom - preferredTop
  const safeSpace = anchorBottom - safeTop

  let height = desiredHeight
  let top = anchorBottom - desiredHeight

  if (preferredSpace >= PANEL_MIN_VISIBLE_HEIGHT) {
    height = Math.min(desiredHeight, preferredSpace)
    top = anchorBottom - height
  } else if (safeSpace >= PANEL_MIN_VISIBLE_HEIGHT) {
    height = Math.min(desiredHeight, safeSpace)
    top = anchorBottom - height
  } else {
    const hardTop = 72
    height = Math.max(112, Math.min(desiredHeight, anchorBottom - hardTop))
    top = anchorBottom - height
  }

  const corridorLeft = clamp(safeLeft, 24, SCREEN_WIDTH - FEATURE_PANEL_WIDTH - 24)
  const corridorRight = clamp(safeRight, corridorLeft + FEATURE_PANEL_WIDTH, SCREEN_WIDTH - 24)
  const left = clamp(
    point.x - FEATURE_PANEL_WIDTH / 2,
    corridorLeft,
    corridorRight - FEATURE_PANEL_WIDTH,
  )
  const anchorX = clamp(point.x - left, 28, FEATURE_PANEL_WIDTH - 28)

  return {
    width: FEATURE_PANEL_WIDTH,
    height: Math.round(height),
    style: {
      left: `${Math.round(left)}px`,
      top: `${Math.round(top)}px`,
      right: "auto",
      bottom: "auto",
      width: `${FEATURE_PANEL_WIDTH}px`,
      "--feature-panel-anchor-x": `${Math.round(anchorX)}px`,
    },
  }
}
