import {
  defaultWidgetSettings,
  isWidgetVisibleOn,
  type Position as BackendPosition,
  type WidgetLocationPreset,
  type WidgetSettings,
  type WidgetVisibleOptionId,
} from "@accessibit/types";

// ─── UI Types ────────────────────────────────────────────────────────────────

export type IconStyle = "wheelchair" | "universal" | "eye";
export type Size = "small" | "medium" | "large";
export type OffsetUnit = "px" | "%";
export type UiPosition =
  | "top-left"
  | "top-center"
  | "top-right"
  | "middle-left"
  | "middle-right"
  | "bottom-left"
  | "bottom-center"
  | "bottom-right";

export interface UiConfig {
  iconColor: string;
  internalColor: string;
  iconStyle: IconStyle;
  desktopCustomPx: number;
  mobileCustomPx: number;
  desktopPosition: UiPosition;
  desktopOffsetH: number;
  desktopOffsetV: number;
  desktopOffsetHUnit: OffsetUnit;
  desktopOffsetVUnit: OffsetUnit;
  mobilePosition: UiPosition;
  mobileOffsetH: number;
  mobileOffsetV: number;
  mobileOffsetHUnit: OffsetUnit;
  mobileOffsetVUnit: OffsetUnit;
  showOnDesktop: boolean;
  showOnMobile: boolean;
  language: string;
  enabledTools: Record<string, boolean>;
  scriptNonce: string;
}

// ─── Static maps ─────────────────────────────────────────────────────────────

const ICON_UI_TO_BACKEND: Record<IconStyle, "1" | "2" | "3"> = {
  universal: "1",
  wheelchair: "2",
  eye: "3",
};

const ICON_BACKEND_TO_UI: Record<"1" | "2" | "3", IconStyle> = {
  "1": "universal",
  "2": "wheelchair",
  "3": "eye",
};

const POSITION_BACKEND_TO_UI: Record<WidgetLocationPreset, UiPosition> = {
  "top-left": "top-left",
  "top-center": "top-center",
  "top-right": "top-right",
  "mid-left": "middle-left",
  "mid-right": "middle-right",
  "bottom-left": "bottom-left",
  "bottom-center": "bottom-center",
  "bottom-right": "bottom-right",
};

export const TOOL_UI_TO_OPTION_IDS: Record<string, WidgetVisibleOptionId[]> = {
  "Text Size": ["font_up", "font_down"],
  "Readable Text": ["readable_text"],
  "Text Align": ["text_align"],
  "Line Height": ["line_height"],
  "Text Spacing": ["text_spacing"],
  "High Contrast": ["high_contrast"],
  "Single Color": ["single_color"],
  "Invert Colors": ["invert_colors"],
  "Red Deficiency": ["red_deficiency"],
  "Green Deficiency": ["green_deficiency"],
  "Blue Deficiency": ["blue_deficiency"],
  "Highlight Links": ["highlight_links"],
  "Highlight Titles": ["highlight_titles"],
  "Hide Images": ["hide_images"],
  "Large White Cursor": ["large_white_cursor"],
  "Large Black Cursor": ["large_black_cursor"],
  "Reading Mask": ["reading_mask"],
  "Reading Guide": ["reading_guide"],
  "Stop Animations": ["stop_animations"],
  "Keyboard Nav": ["keyboard_nav"],
  "Page Summary": ["page_summary"],
};

// ─── Position defaults ───────────────────────────────────────────────────────

/**
 * The default edge inset per device, matching defaultWidgetSettings (desktop
 * 24px, mobile 12px). Used both when reading a bare preset string and when the
 * user picks a position in the panel (which resets the paddings to these).
 */
export const DEFAULT_DEVICE_INSET: Record<"desktop" | "mobile", number> = {
  desktop: 24,
  mobile: 12,
};

// ─── Size helpers ────────────────────────────────────────────────────────────

export const UI_PRESET_SIZES: Record<Size, number> = {
  small: 38,
  medium: 48,
  large: 58,
};

function readBackendSize(value: unknown, fallbackPx: number): number {
  if (typeof value === "number") return value;
  if (value === "small" || value === "medium" || value === "large") {
    return UI_PRESET_SIZES[value];
  }
  return fallbackPx;
}

function writeBackendSize(customPx: number): number | Size {
  const match = (Object.keys(UI_PRESET_SIZES) as Size[]).find(
    (id) => UI_PRESET_SIZES[id] === customPx,
  );
  return match ?? customPx;
}

// ─── Position helpers ────────────────────────────────────────────────────────

interface ReadLocationResult {
  position: UiPosition;
  offsetH: number;
  offsetV: number;
  offsetHUnit: OffsetUnit;
  offsetVUnit: OffsetUnit;
}

interface AxisOffsets {
  offsetH: number;
  offsetV: number;
  offsetHUnit: OffsetUnit;
  offsetVUnit: OffsetUnit;
}

/**
 * Whether a position centers an axis. `middle-*` centers vertically (stored as
 * `top: X%`), `*-center` centers horizontally (`left: X%`). On that axis a
 * percentage means "center-anchored at X%" (the widget translates it to true
 * center); pixels mean an edge inset.
 */
export function isVerticalCentered(pos: UiPosition): boolean {
  return pos === "middle-left" || pos === "middle-right";
}
export function isHorizontalCentered(pos: UiPosition): boolean {
  return pos === "top-center" || pos === "bottom-center";
}

/**
 * Default paddings for a position: the centered axis defaults to 50% (true
 * center), edge axes to the device inset in px.
 */
export function positionOffsetDefaults(
  pos: UiPosition,
  inset: number,
): AxisOffsets {
  return {
    offsetH: isHorizontalCentered(pos) ? 50 : inset,
    offsetHUnit: isHorizontalCentered(pos) ? "%" : "px",
    offsetV: isVerticalCentered(pos) ? 50 : inset,
    offsetVUnit: isVerticalCentered(pos) ? "%" : "px",
  };
}

/**
 * Recompute the position after a unit change, keeping the panel grid in sync
 * with the paddings: a `%` on the centering key (top for middle, left for
 * center) means center-anchored; px means an edge. Preserves the position's
 * edge choice (top vs bottom, left vs right). Returns null for the impossible
 * "middle-center" (both axes centered) so the caller can reject the toggle.
 */
export function derivePosition(
  pos: UiPosition,
  offsetHUnit: OffsetUnit,
  offsetVUnit: OffsetUnit,
): UiPosition | null {
  const vKey: "top" | "bottom" = pos.startsWith("bottom") ? "bottom" : "top";
  const hKey: "left" | "right" = pos.endsWith("right") ? "right" : "left";
  const vAnchor =
    vKey === "top" ? (offsetVUnit === "%" ? "middle" : "top") : "bottom";
  const hAnchor =
    hKey === "left" ? (offsetHUnit === "%" ? "center" : "left") : "right";
  if (vAnchor === "middle" && hAnchor === "center") return null;
  return `${vAnchor}-${hAnchor}` as UiPosition;
}

/** Split a stored CSS length ("24px", "10%") into a number + unit. */
function parseLength(value: string | undefined): {
  n: number;
  unit: OffsetUnit;
} {
  if (value === undefined) return { n: 0, unit: "px" };
  const unit: OffsetUnit = value.trim().endsWith("%") ? "%" : "px";
  const n = parseFloat(value);
  return { n: Number.isFinite(n) ? n : 0, unit };
}

const isPercent = (v: string | undefined): boolean =>
  typeof v === "string" && v.trim().endsWith("%");

function readBackendLocation(
  value: unknown,
  fallbackPreset: UiPosition,
  defaultInset: number,
): ReadLocationResult {
  const fromDefaults = (pos: UiPosition): ReadLocationResult => ({
    position: pos,
    ...positionOffsetDefaults(pos, defaultInset),
  });

  // A bare preset string carries no explicit offset → use that position's
  // defaults so the padding inputs match what the widget renders.
  if (typeof value === "string" && value in POSITION_BACKEND_TO_UI) {
    return fromDefaults(POSITION_BACKEND_TO_UI[value as WidgetLocationPreset]);
  }
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return fromDefaults(fallbackPreset);
  }

  const p = value as Partial<
    Record<"top" | "bottom" | "left" | "right", string>
  >;
  if (
    p.top === undefined &&
    p.bottom === undefined &&
    p.left === undefined &&
    p.right === undefined
  ) {
    return fromDefaults(fallbackPreset);
  }

  const defaultLen = { n: defaultInset, unit: "px" as OffsetUnit };

  // Vertical: `top: X%` → center-anchored ("middle"); `top`/`bottom` px → edge.
  let vName: "top" | "middle" | "bottom";
  let vLen: { n: number; unit: OffsetUnit };
  if (p.top !== undefined && isPercent(p.top)) {
    vName = "middle";
    vLen = parseLength(p.top);
  } else if (p.top !== undefined) {
    vName = "top";
    vLen = parseLength(p.top);
  } else if (p.bottom !== undefined) {
    vName = "bottom";
    vLen = parseLength(p.bottom);
  } else {
    const hasH = p.left !== undefined || p.right !== undefined;
    vName = hasH ? "middle" : "top";
    vLen = hasH ? { n: 50, unit: "%" } : defaultLen;
  }

  // Horizontal: `left: X%` → center-anchored ("center"); `left`/`right` px → edge.
  let hName: "left" | "center" | "right";
  let hLen: { n: number; unit: OffsetUnit };
  if (p.left !== undefined && isPercent(p.left)) {
    hName = "center";
    hLen = parseLength(p.left);
  } else if (p.left !== undefined) {
    hName = "left";
    hLen = parseLength(p.left);
  } else if (p.right !== undefined) {
    hName = "right";
    hLen = parseLength(p.right);
  } else {
    hName = "right";
    hLen = defaultLen;
  }

  // Compose; "middle-center" has no grid cell so both-centered falls back.
  const position: UiPosition =
    vName === "middle" && hName === "center"
      ? fallbackPreset
      : (`${vName}-${hName}` as UiPosition);

  return {
    position,
    offsetH: hLen.n,
    offsetV: vLen.n,
    offsetHUnit: hLen.unit,
    offsetVUnit: vLen.unit,
  };
}

function writeBackendLocation(
  uiPosition: UiPosition,
  offsetH: number,
  offsetV: number,
  offsetHUnit: OffsetUnit,
  offsetVUnit: OffsetUnit,
): BackendPosition {
  // Each position anchors to one vertical key (top for middle & top-*, bottom
  // for bottom-*) and one horizontal key (left for center & *-left, right for
  // *-right). A `%` unit on the centered axis makes it center-anchored; px is an
  // edge inset. Both axes are always written explicitly (WYSIWYG paddings).
  const vKey: "top" | "bottom" = uiPosition.startsWith("bottom")
    ? "bottom"
    : "top";
  const hKey: "left" | "right" = uiPosition.endsWith("right")
    ? "right"
    : "left";
  return {
    [vKey]: `${offsetV}${offsetVUnit}`,
    [hKey]: `${offsetH}${offsetHUnit}`,
  };
}

// ─── Tool helpers ────────────────────────────────────────────────────────────

function readTools(
  visibleOptions: WidgetSettings["visibleOptions"],
): Record<string, boolean> {
  const tools: Record<string, boolean> = {};
  for (const [uiKey, optionIds] of Object.entries(TOOL_UI_TO_OPTION_IDS)) {
    tools[uiKey] = optionIds.every((id) => visibleOptions[id] !== false);
  }
  return tools;
}

function writeTools(
  tools: Record<string, boolean>,
): WidgetSettings["visibleOptions"] {
  const out: WidgetSettings["visibleOptions"] = {};
  for (const [uiKey, optionIds] of Object.entries(TOOL_UI_TO_OPTION_IDS)) {
    const value = tools[uiKey] !== false;
    for (const id of optionIds) out[id] = value;
  }
  return out;
}

// ─── Public API ──────────────────────────────────────────────────────────────

export function fromSettings(settings: WidgetSettings): UiConfig {
  const desktopCustomPx = readBackendSize(
    settings.size.desktop,
    UI_PRESET_SIZES.medium,
  );
  const mobileCustomPx = readBackendSize(
    settings.size.mobile,
    UI_PRESET_SIZES.medium,
  );
  // Default insets match defaultWidgetSettings (desktop 24px, mobile 12px) so a
  // bare preset string reads back as the value the widget actually renders.
  const desktopLoc = readBackendLocation(
    settings.location.desktop,
    "bottom-right",
    DEFAULT_DEVICE_INSET.desktop,
  );
  const mobileLoc = readBackendLocation(
    settings.location.mobile,
    "bottom-right",
    DEFAULT_DEVICE_INSET.mobile,
  );

  return {
    iconColor: settings.iconColor,
    internalColor: settings.innerColor,
    iconStyle: ICON_BACKEND_TO_UI[settings.icon],
    desktopCustomPx,
    mobileCustomPx,
    desktopPosition: desktopLoc.position,
    desktopOffsetH: desktopLoc.offsetH,
    desktopOffsetV: desktopLoc.offsetV,
    desktopOffsetHUnit: desktopLoc.offsetHUnit,
    desktopOffsetVUnit: desktopLoc.offsetVUnit,
    mobilePosition: mobileLoc.position,
    mobileOffsetH: mobileLoc.offsetH,
    mobileOffsetV: mobileLoc.offsetV,
    mobileOffsetHUnit: mobileLoc.offsetHUnit,
    mobileOffsetVUnit: mobileLoc.offsetVUnit,
    showOnDesktop: isWidgetVisibleOn(settings, "desktop"),
    showOnMobile: isWidgetVisibleOn(settings, "mobile"),
    language: settings.lang,
    enabledTools: readTools(settings.visibleOptions),
    scriptNonce: settings.nonce,
  };
}

export function toSettings(config: UiConfig): WidgetSettings {
  return {
    iconColor: config.iconColor,
    innerColor: config.internalColor,
    icon: ICON_UI_TO_BACKEND[config.iconStyle],
    size: {
      desktop: writeBackendSize(config.desktopCustomPx),
      mobile: writeBackendSize(config.mobileCustomPx),
    },
    location: {
      desktop: writeBackendLocation(
        config.desktopPosition,
        config.desktopOffsetH,
        config.desktopOffsetV,
        config.desktopOffsetHUnit,
        config.desktopOffsetVUnit,
      ),
      mobile: writeBackendLocation(
        config.mobilePosition,
        config.mobileOffsetH,
        config.mobileOffsetV,
        config.mobileOffsetHUnit,
        config.mobileOffsetVUnit,
      ),
    },
    visibility: {
      desktop: config.showOnDesktop,
      mobile: config.showOnMobile,
    },
    lang: config.language,
    nonce: config.scriptNonce,
    visibleOptions: writeTools(config.enabledTools),
  };
}

export const DEFAULT_UI_CONFIG: UiConfig = fromSettings(defaultWidgetSettings);

/**
 * Select a position for one device and reset that device's paddings to the
 * position's default inset (24px desktop / 12px mobile) in px. This is what the
 * position grid applies on selection so each position starts from a clean
 * default rather than inheriting the previous position's custom values.
 */
export function withPositionDefaults(
  config: UiConfig,
  device: "desktop" | "mobile",
  pos: UiPosition,
): UiConfig {
  const d = positionOffsetDefaults(pos, DEFAULT_DEVICE_INSET[device]);
  if (device === "desktop") {
    return {
      ...config,
      desktopPosition: pos,
      desktopOffsetH: d.offsetH,
      desktopOffsetV: d.offsetV,
      desktopOffsetHUnit: d.offsetHUnit,
      desktopOffsetVUnit: d.offsetVUnit,
    };
  }
  return {
    ...config,
    mobilePosition: pos,
    mobileOffsetH: d.offsetH,
    mobileOffsetV: d.offsetV,
    mobileOffsetHUnit: d.offsetHUnit,
    mobileOffsetVUnit: d.offsetVUnit,
  };
}
