package gui

import "../core"
import "../ui"

ready_stage_count :: proc(controller: ui.App_Controller) -> (ready: int, total: int) {
	script_ok := len(controller.state.script.pages) > 0
	panels_ok := len(controller.state.panel_images) > 0
	layout_ok := len(controller.state.page_layouts) > 0
	export_ok := panels_ok && layout_ok
	ready = 0
	if script_ok { ready += 1 }
	if panels_ok { ready += 1 }
	if layout_ok { ready += 1 }
	if export_ok { ready += 1 }
	return ready, 4
}

export_block_reason :: proc(state: core.Comic_State) -> string {
	if len(state.panel_images) == 0 && len(state.page_layouts) == 0 {
		return "need panels + layout"
	}
	if len(state.panel_images) == 0 {
		return "need panels"
	}
	if len(state.page_layouts) == 0 {
		return "need layout"
	}
	return ""
}

clamp_script_cursor :: proc(page_count, cursor: int) -> int {
	if page_count <= 0 {
		return 0
	}
	if cursor < 0 {
		return 0
	}
	if cursor >= page_count {
		return page_count - 1
	}
	return cursor
}

clamp_panel_cursor :: proc(panel_count, cursor: int) -> int {
	if panel_count <= 0 {
		return 0
	}
	if cursor < 0 {
		return 0
	}
	if cursor >= panel_count {
		return panel_count - 1
	}
	return cursor
}

panel_by_flat_index :: proc(script: core.Comic_Script, panel_idx: int) -> (core.Panel, int, bool) {
	if panel_idx < 0 {
		return core.Panel{}, 0, false
	}
	flat := 0
	for page in script.pages {
		for panel in page.panels {
			if flat == panel_idx {
				return panel, page.page_number, true
			}
			flat += 1
		}
	}
	return core.Panel{}, 0, false
}

clamp_layout_cursor :: proc(layout_count, cursor: int) -> int {
	if layout_count <= 0 {
		return 0
	}
	if cursor < 0 {
		return 0
	}
	if cursor >= layout_count {
		return layout_count - 1
	}
	return cursor
}

Layout_Validation_Result :: struct {
	coverage_pct:     f32,
	missing_bindings:  int,
	bounds_violations: int,
	total_panels:      int,
}

validate_layout_page :: proc(layout: core.Page_Layout, panel_images: map[string]core.Panel_Image) -> Layout_Validation_Result {
	result: Layout_Validation_Result
	result.total_panels = len(layout.panels)

	page_area := f32(layout.width) * f32(layout.height)
	covered_area: f32 = 0
	for p in layout.panels {
		cell_w := p.layout_cell.w * f32(layout.width)
		cell_h := p.layout_cell.h * f32(layout.height)
		covered_area += cell_w * cell_h
	}
	if page_area > 0 {
		result.coverage_pct = covered_area / page_area * 100
	}

	for p in layout.panels {
		if _, has := panel_images[p.panel_id]; !has {
			result.missing_bindings += 1
		}
	}

	for p in layout.panels {
		c := p.layout_cell
		if c.x < 0 || c.y < 0 || c.x+c.w > 1.001 || c.y+c.h > 1.001 {
			result.bounds_violations += 1
		}
	}

	return result
}