package gui

import clay "clay:."
import "core:fmt"
import "../core"

// ─── Shared Helpers ─────────────────────────────────────────────

workspace_nav :: proc(id_prefix, pos_label: string) {
	if clay.UI(clay.ID(fmt.tprintf("%sNav", id_prefix)))({
		layout = {sizing = {width = clay.SizingGrow({}), height = clay.SizingFixed(36)}, layoutDirection = .LeftToRight, childGap = 8, childAlignment = {y = .Center}},
	}) {
		clay_body_text(pos_label, color = CLAY_ACCENT)
		declare_button_small(fmt.tprintf("btn_%s_prev", id_prefix), "< Prev")
		declare_button_small(fmt.tprintf("btn_%s_next", id_prefix), "Next >")
	}
}

// ─── Script Workspace ────────────────────────────────────────────
declare_script_workspace :: proc(app: ^GUI_App_State) {
	page_count := len(app.controller.state.script.pages)
	if page_count == 0 {
		if clay.UI(clay.ID("ScriptEmpty"))(clay_card_style()) {
			clay_title_text("Script")
			clay_body_text("No script pages yet.", color = CLAY_TEXT_TERTIARY)
			clay_body_text("1. Go to Story screen to set up your story idea", color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
			clay_body_text("2. Click 'Generate Script' or press F5", color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
		}
		return
	}

	idx := clamp_script_cursor(page_count, app.summary_opts.script_page_cursor)
	workspace_nav("script", fmt.tprintf("Page %d/%d", idx+1, page_count))

	title := app.controller.state.script.title
	if len(title) > 50 { title = fmt.tprintf("%s...", title[:47]) }
	clay_muted_text(title)

	declare_script_detail(app)
}

// ─── Panels Workspace ────────────────────────────────────────────
declare_panels_workspace :: proc(app: ^GUI_App_State) {
	panel_count := count_script_panels(app.controller.state.script)
	if panel_count == 0 {
		if clay.UI(clay.ID("PanelsEmpty"))(clay_card_style()) {
			clay_title_text("Panels")
			clay_body_text("No panels generated yet.", color = CLAY_TEXT_TERTIARY)
			clay_body_text("Generate a script first, then click 'Generate Panels' or press F6", color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
		}
		return
	}

	idx := clamp_panel_cursor(panel_count, app.summary_opts.panel_cursor)
	workspace_nav("panels", fmt.tprintf("Panel %d/%d", idx+1, panel_count))
	declare_panels_detail(app)
}

// ─── Layout Workspace ────────────────────────────────────────────
declare_layout_workspace :: proc(app: ^GUI_App_State) {
	layout_count := len(app.controller.state.page_layouts)
	if layout_count == 0 {
		if clay.UI(clay.ID("LayoutEmpty"))(clay_card_style()) {
			clay_title_text("Layout")
			clay_body_text("No layouts yet.", color = CLAY_TEXT_TERTIARY)
			clay_body_text("Generate panels first, then click 'Layout Pages' or press F7", color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
		}
		return
	}

	idx := clamp_layout_cursor(layout_count, app.summary_opts.layout_page_cursor)
	workspace_nav("layout", fmt.tprintf("Page %d/%d", idx+1, layout_count))
	declare_layout_detail(app)
}

// ─── Bubbles Workspace ───────────────────────────────────────────
declare_bubbles_workspace :: proc(app: ^GUI_App_State) {
	layout_count := len(app.controller.state.page_layouts)
	if layout_count == 0 {
		if clay.UI(clay.ID("BubblesEmpty"))(clay_card_style()) {
			clay_title_text("Bubbles")
			clay_body_text("No layouts yet.", color = CLAY_TEXT_TERTIARY)
			clay_body_text("Run Layout Auto first, then use this screen to edit speech bubbles", color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
		}
		return
	}

	page_idx := clamp_layout_cursor(layout_count, app.summary_opts.bubble_page_cursor)
	layout_val := app.controller.state.page_layouts[page_idx]
	panel_count := len(layout_val.panels)

	// Bubbles needs dual nav (page + panel)
	if clay.UI(clay.ID("BubblesNav"))({
		layout = {sizing = {width = clay.SizingGrow({}), height = clay.SizingFixed(36)}, layoutDirection = .LeftToRight, childGap = 8, childAlignment = {y = .Center}},
	}) {
		clay_body_text(fmt.tprintf("Page %d/%d • %d panels", page_idx+1, layout_count, panel_count), color = CLAY_ACCENT)
		declare_button_small("btn_bubbles_prev_page", "< Page")
		declare_button_small("btn_bubbles_next_page", "Page >")
		declare_button_small("btn_bubbles_prev_panel", "< Panel")
		declare_button_small("btn_bubbles_next_panel", "Panel >")
	}

	declare_bubbles_detail(app)
}

// ─── Story Workspace ──────────────────────────────────────────────

// ─── Story Workspace ──────────────────────────────────────────────
declare_story_workspace :: proc(app: ^GUI_App_State) {
	if clay.UI(clay.ID("StoryCard"))(clay_card_style()) {
		clay_title_text("Story Setup")

		clay_muted_text("Story Idea")
		if clay.UI(clay.ID("field_idea"))({
			layout = {sizing = {width = clay.SizingGrow({}), height = clay.SizingFit({min = 80, max = 0})}, padding = {top = 8, right = 12, bottom = 8, left = 12}},
			backgroundColor = CLAY_BG_INPUT,
			cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
		}) {
			clay_body_text(app.controller.state.story_idea if len(app.controller.state.story_idea) > 0 else "Enter story idea...")
		}

		if clay.UI(clay.ID("StoryMetaRow"))({layout = {layoutDirection = .LeftToRight, sizing = {width = clay.SizingGrow({}), height = clay.SizingFit({})}, childGap = 12}}) {
			if clay.UI(clay.ID("StoryMetaLeft"))({layout = {layoutDirection = .TopToBottom, sizing = {width = clay.SizingGrow({}), height = clay.SizingFit({})}, childGap = 2}}) {
				clay_muted_text("Genre")
				if clay.UI(clay.ID("field_genre"))({
					layout = clay_input_layout(),
					backgroundColor = CLAY_BG_INPUT,
					cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
				}) {
					clay_body_text(app.controller.state.story_genre if len(app.controller.state.story_genre) > 0 else "Enter genre...")
				}
			}
			if clay.UI(clay.ID("StoryMetaRight"))({layout = {layoutDirection = .TopToBottom, sizing = {width = clay.SizingGrow({}), height = clay.SizingFit({})}, childGap = 2}}) {
				clay_muted_text("Audience")
				if clay.UI(clay.ID("field_audience"))({
					layout = clay_input_layout(),
					backgroundColor = CLAY_BG_INPUT,
					cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
				}) {
					clay_body_text(app.controller.state.target_audience if len(app.controller.state.target_audience) > 0 else "Enter audience...")
				}
			}
		}
	}

	if clay.UI(clay.ID("PathCard"))(clay_card_style()) {
		clay_title_text("Project Paths")

		clay_muted_text("Export Path")
		if clay.UI(clay.ID("field_export"))({
			layout = clay_input_layout(),
			backgroundColor = CLAY_BG_INPUT,
			cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
		}) {
			clay_body_text(app.export_path)
		}

		clay_muted_text("Project Path")
		if clay.UI(clay.ID("field_project"))({
			layout = clay_input_layout(),
			backgroundColor = CLAY_BG_INPUT,
			cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
		}) {
			clay_body_text(app.project_path)
		}

		if clay.UI(clay.ID("StoryConfigRow"))({layout = clay_row_layout()}) {
			clay_muted_text("Pages")
			if clay.UI(clay.ID("field_pages"))({
				layout = {sizing = {width = clay.SizingFixed(60), height = clay.SizingFixed(34)}},
				backgroundColor = CLAY_BG_INPUT,
				cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
			}) {
				clay_body_text(app.local_script_pages)
			}
			clay_muted_text("Format")
			declare_nav_chip("btn_pdf", "PDF", app.export_format == .PDF)
			declare_nav_chip("btn_png", "PNG", app.export_format == .PNG)
			declare_nav_chip("btn_cbz", "CBZ", app.export_format == .CBZ)
			clay_muted_text("Source")
			declare_nav_chip("btn_local", "Local", !app.use_deepseek_script)
			declare_nav_chip("btn_deepseek", "DS", app.use_deepseek_script)
		}
	}
}

// ─── Characters Workspace ─────────────────────────────────────────

// ─── Characters Workspace ─────────────────────────────────────────
declare_characters_workspace :: proc(app: ^GUI_App_State) {
	if clay.UI(clay.ID("CharsCard"))(clay_card_style()) {
		clay_title_text("Characters")
		char_count := len(app.controller.state.characters)
		if char_count == 0 {
			clay_body_text("No characters yet.", color = CLAY_TEXT_TERTIARY)
			clay_body_text("Characters are extracted when you generate a script.", color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
			clay_body_text("Generate Script (F5) to populate characters from your story.", color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
		} else {
			clay_body_text(fmt.tprintf("%d characters found", char_count), color = CLAY_ACCENT)
			for i in 0..<char_count {
				char := app.controller.state.characters[i]
				role_label := character_role_label(char.role)
				if clay.UI(clay.ID(fmt.tprintf("char_%s", char.id)))({
					layout = {layoutDirection = .TopToBottom, padding = {top = 4, right = 8, bottom = 4, left = 8}, childGap = 2},
				}) {
					clay_body_text(fmt.tprintf("%s  [%s]", char.name, role_label), color = CLAY_TEXT_PRIMARY)
					if len(char.description) > 0 {
						clay_body_text(char.description, color = CLAY_TEXT_SECONDARY, size = CLAY_FONT_SIZE_SM)
					}
				}
			}
		}
	}
}


// ─── Export Workspace ─────────────────────────────────────────────
character_role_label :: proc(role: core.Character_Role) -> string {
	switch role {
	case .Protagonist: return "Protagon."
	case .Antagonist: return "Antagon."
	case .Supporting: return "Support."
	case .Extra: return "Extra"
	}
	return "Unknown"
}

// ─── Export Workspace ─────────────────────────────────────────────
declare_export_workspace :: proc(app: ^GUI_App_State) {
	if clay.UI(clay.ID("ExportCard"))(clay_card_style()) {
		clay_title_text("Export")

		ready, total := ready_stage_count(app.controller)
		all_ready := ready == total

		panel_count := len(app.controller.state.panel_images)
		page_count := len(app.controller.state.page_layouts)

		if clay.UI(clay.ID("ExportStats"))({layout = {layoutDirection = .LeftToRight, sizing = {width = clay.SizingGrow({}), height = clay.SizingFit({})}, childGap = 16}}) {
			declare_stat_chip("Pages", page_count)
			declare_stat_chip("Panels", panel_count)
			declare_stat_chip("Ready", ready)
		}

		clay_muted_text(fmt.tprintf("Format: %v  •  Target: %s", app.controller.state.export_format, app.export_path))

		reason := export_block_reason(app.controller.state)
		if len(reason) > 0 {
			if clay.UI(clay.ID("ExportBlocked"))({
				layout = {layoutDirection = .TopToBottom, padding = {top = 8, right = 12, bottom = 8, left = 12}, childGap = 4},
				backgroundColor = CLAY_ERROR_DIM,
				cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
			}) {
				clay_body_text(fmt.tprintf("Blocked: %s", reason), color = CLAY_ERROR)
				clay_body_text("Complete all pipeline stages before exporting.", color = CLAY_TEXT_TERTIARY, size = CLAY_FONT_SIZE_SM)
			}
		} else {
			if clay.UI(clay.ID("ExportReady"))({
				layout = {layoutDirection = .TopToBottom, padding = {top = 8, right = 12, bottom = 8, left = 12}, childGap = 4},
				backgroundColor = CLAY_SUCCESS_DIM,
				cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_SM),
			}) {
				clay_body_text("All pipeline stages complete. Ready!", color = CLAY_SUCCESS)
			}
		}

		// Export action buttons
		if clay.UI(clay.ID("ExportActions"))({layout = {layoutDirection = .LeftToRight, sizing = {width = clay.SizingGrow({}), height = clay.SizingFit({})}, childGap = 8}}) {
			format := app.controller.state.export_format
			declare_button_state_export("btn_export_now", "Export as PDF", format == .PDF)
			declare_button_state_export("btn_export_png", "Export as PNG", format == .PNG)
			declare_button_state_export("btn_export_cbz", "Export as CBZ", format == .CBZ)
		}

		if page_count > 0 {
			if clay.UI(clay.ID("ExportPagesList"))({
				layout = {sizing = {width = clay.SizingGrow({}), height = clay.SizingGrow({})}, layoutDirection = .TopToBottom, childGap = 1},
			}) {
				for l in app.controller.state.page_layouts {
					clay_muted_text(fmt.tprintf("Page %d • %s • %d panels", l.page_number, l.pattern_id, len(l.panels)))
				}
			}
		}
	}
}

declare_button_state_export :: proc(id: string, label: string, is_current_format: bool) {
	bg := CLAY_BTN_DEFAULT
	if is_current_format { bg = CLAY_BTN_SOFT }
	if clay.UI(clay.ID(id))({
		layout = clay_button_layout(),
		backgroundColor = bg,
		cornerRadius = clay.CornerRadiusAll(CLAY_RADIUS_FRAC_BTN),
	}) {
		clay_body_text(label)
	}
}

// ─── Community Workspace ──────────────────────────────────────────

// ─── Community Workspace ──────────────────────────────────────────
declare_community_workspace :: proc(app: ^GUI_App_State) {
	if clay.UI(clay.ID("CommunityCard"))(clay_card_style()) {
		clay_title_text("Community")
		clay_body_text("Community features coming soon", color = CLAY_TEXT_TERTIARY)
	}
}

// ─── Bottom Bar ───────────────────────────────────────────────────
