import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";

export interface Config {
  log_path: string | null;
  poe_window_match: string;
  overlay_only_when_focused: boolean;
  overlay_x: number;
  overlay_y: number;
  overlay_width: number;
  overlay_font_size: number;
  hotkey_next: string;
  hotkey_prev: string;
  hotkey_toggle: string;
  hotkey_timer_pause: string;
  hotkey_layout: string;
  feature_layouts: boolean;
  layout_x: number;
  layout_y: number;
  layout_w: number;
  layout_h: number;
  timer_enabled: boolean;
  timer_pause_in_town: boolean;
  timer_afk_enabled: boolean;
  timer_afk_seconds: number;
  timer_pause_unfocused: boolean;
  current_step: number;
  show_optionals: boolean;
  league_start: boolean;
  lookahead: number;
  show_recommendation: boolean;
  active_character: string | null;
  profiles: Profile[];
}

export interface Profile {
  name: string;
  current_step: number;
  league_start: boolean;
  show_optionals: boolean;
}

export interface Status {
  character: string;
  class: string;
  level: number;
  area_id: string;
  area_name: string;
  area_level: number;
  area_seed: string;
  act: number;
  game_focused: boolean;
}

export interface Area {
  id: string;
  name: string;
  recommendation: string | null;
  group: number;
}

export interface Step {
  lines: string[];
  section: number;
  target_area: string | null;
}

export interface GuideData {
  steps: Step[];
  areas: Record<string, Area>;
  section_count: number;
}

export interface RunTimer {
  active: boolean;
  finished: boolean;
  manual_pause: boolean;
  auto_paused: boolean;
  afk_paused: boolean;
  total_seconds: number;
  act_seconds: number;
  current_act: number;
  splits: number[];
  run_name: string | null;
}

export const getConfig = () => invoke<Config>("get_config");
export const saveConfig = (cfg: Config) => invoke("save_config", { new: cfg });
export const getStatus = () => invoke<Status>("get_status");
export const getGuide = () => invoke<GuideData>("get_guide");
export const getGems = () => invoke<Record<string, Record<string, number[]>>>("get_gems");
export const detectLogs = () => invoke<string[]>("detect_logs");
export const getTimer = () => invoke<RunTimer>("get_timer");
export const timerStart = () => invoke("timer_start");
export const timerPause = () => invoke("timer_pause");
export const timerReset = () => invoke("timer_reset");
export const stepDelta = (delta: number) => invoke("step_delta", { delta });
export const stepGoto = (newIndex: number) => invoke("step_goto", { new: newIndex });
export const createProfile = (name: string, leagueStart: boolean) =>
  invoke("create_profile", { name, leagueStart });
export const deleteProfile = (name: string) => invoke("delete_profile", { name });
export const selectProfile = (name: string) => invoke("select_profile", { name });
export const setOverlayLocked = (locked: boolean) => invoke("set_overlay_locked", { locked });
export const toggleOverlay = () => invoke("toggle_overlay");
export const saveOverlayGeometry = () => invoke("save_overlay_geometry");
export const setOverlayHeight = (height: number) => invoke("set_overlay_height", { height });
export const restoreOverlayPosition = () => invoke("restore_overlay_position");
export const toggleLayout = () => invoke("toggle_layout");
export const setLayoutSize = (width: number, height: number) =>
  invoke("set_layout_size", { width, height });
export const startLayoutResize = () => invoke("start_layout_resize");
export const endLayoutResize = () => invoke("end_layout_resize");
export const saveLayoutGeometry = () => invoke("save_layout_geometry");
export const startLayoutDrag = () => invoke("start_layout_drag");
export const endLayoutDrag = () => invoke("end_layout_drag");

// Event helpers ------------------------------------------------------------
export const onStatus = (cb: (s: Status) => void): Promise<UnlistenFn> =>
  listen<Status>("status://update", (e) => cb(e.payload));
export const onStep = (cb: (i: number) => void): Promise<UnlistenFn> =>
  listen<number>("tracker://step", (e) => cb(e.payload));
export const onConfig = (cb: (c: Config) => void): Promise<UnlistenFn> =>
  listen<Config>("config://update", (e) => cb(e.payload));
export const onFocus = (cb: (f: boolean) => void): Promise<UnlistenFn> =>
  listen<boolean>("focus://update", (e) => cb(e.payload));
export const onOverlayToggle = (cb: () => void): Promise<UnlistenFn> =>
  listen("overlay://toggle", () => cb());
export const onOverlayLocked = (cb: (locked: boolean) => void): Promise<UnlistenFn> =>
  listen<boolean>("overlay://locked", (e) => cb(e.payload));
export const onGuideReload = (cb: () => void): Promise<UnlistenFn> =>
  listen("guide://reload", () => cb());
export const onTimer = (cb: (t: RunTimer) => void): Promise<UnlistenFn> =>
  listen<RunTimer>("timer://update", (e) => cb(e.payload));

/** Format seconds as h:mm:ss or m:ss. */
export function fmtTime(total: number): string {
  const s = Math.floor(total);
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = s % 60;
  const pad = (n: number) => n.toString().padStart(2, "0");
  return h > 0 ? `${h}:${pad(m)}:${pad(sec)}` : `${m}:${pad(sec)}`;
}
