extends Control
## CC skill slot (Boss 2026-10-21): one round button right beside AUTO for the class crowd-control skill
## (server/cc.gd: one CC skill per launch class, 3 branches each = 15 branches, cooldown 120 s).
##  - shows the skill icon, the cooldown sweep + seconds, the key (Settings action "cc_skill", default C) and "CC"
##  - which skill: AUTO setting "cc_slot" (PlayerState.auto_cfg, saved per character, synced like every AUTO
##    setting) = a CC skill dropped on the slot; "" or a skill the hero cannot use now = the class CC skill learned
##    (auto pick, follows class switches). Drop a CC skill from the Skills window / hotbar here; right-click = auto.
##  - press / key: casts it (enemy skills go at the current target, else the nearest monster in range, else the
##    usual "click a monster"). AUTO keeps casting the CC skill by itself (setting "auto_cc", unchanged).
## Place: PC pad mode between AUTO and the ASURA button (skill_pad.gd C0 + CC_OFF); touch mode right of the AUTO gear
## in the bottom row (also without the skill pad). Hook: hud.gd _ready attaches it after HudSkin.apply.

const Pad = preload("res://scripts/ui/skill_pad.gd")
const Icons = preload("res://scripts/icons.gd")
const UiSkin = preload("res://scripts/ui/ui_skin.gd")
const Kanit = preload("res://scripts/ui/kanit.gd")
const CC = preload("res://scripts/server/cc.gd")

## diameter on the pad (x the pad scale k) and its centre from the pad's attack centre (skill_pad.gd C0):
## halfway between AUTO (C0 + AUTO_OFF, d 86) and the ASURA button (C0 + ASURA6_OFF, d 135), on AUTO's line
const D := 72.0
const CC_OFF := Vector2(-210.0, 14.0)
## touch layer: bottom row, right of the AUTO settings gear (hud AUTO 306..390, gear 396..436, centre anchor)
const TOUCH_L := 446.0
const TOUCH_D := 72.0

var hud = null
var btn: Button
var art: Control
var _t := 0.0


static func attach(h) -> Control:
	var s = load("res://scripts/ui/cc_slot.gd").new()
	s.name = "CcSlot"
	s.hud = h
	h.ui_root.add_child(s)
	s.build()
	return s


func build() -> void:
	set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
	mouse_filter = Control.MOUSE_FILTER_IGNORE
	btn = Button.new()
	btn.name = "CcSlotButton"
	btn.focus_mode = Control.FOCUS_NONE
	var st: Array = UiSkin.ring("hot")
	btn.add_theme_stylebox_override("normal", st[0])
	btn.add_theme_stylebox_override("hover", st[1])
	btn.add_theme_stylebox_override("pressed", st[2])
	btn.add_theme_stylebox_override("focus", StyleBoxEmpty.new())
	btn.pressed.connect(press)
	btn.gui_input.connect(_input_btn)
	btn.set_drag_forwarding(Callable(), _can_drop, _drop)
	add_child(btn)
	art = SlotArt.new()
	art.slot = self
	art.mouse_filter = Control.MOUSE_FILTER_IGNORE
	art.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
	btn.add_child(art)
	get_viewport().size_changed.connect(layout)
	layout()


## Row mode: the touch layer is on (or there is no skill pad, classic UI) - AUTO sits in the bottom row.
func _touch_on() -> bool:
	var pad = hud.get_meta("ui3_pad", null) if hud.has_meta("ui3_pad") else null
	if pad == null or not is_instance_valid(pad):
		return true
	var tc = hud.ui_root.get_node_or_null("TouchControls")
	return (tc != null and tc.visible) or not pad.visible


func pad_k() -> float:
	var vp := get_viewport_rect().size
	return clampf(minf(vp.x / 1600.0, vp.y / 900.0), 0.72, 1.0)


var _touch := false


func layout() -> void:
	_touch = _touch_on()
	if _touch:
		btn.anchor_left = 0.5
		btn.anchor_right = 0.5
		btn.anchor_top = 1.0
		btn.anchor_bottom = 1.0
		btn.offset_left = TOUCH_L
		btn.offset_right = TOUCH_L + TOUCH_D
		btn.offset_top = -8.0 - TOUCH_D - 4.0
		btn.offset_bottom = -12.0
		btn.custom_minimum_size = Vector2(TOUCH_D, TOUCH_D)
	else:
		var k := pad_k()
		Pad._place(btn, (Pad.C0 + CC_OFF) * k, D * k)


# ---------------------------------------------------------------- which skill

## The AUTO setting "cc_slot" ("" = auto).
static func chosen() -> String:
	var c = PlayerState.ch
	if c == null:
		return ""
	return str(PlayerState.auto_cfg.get("cc_slot", ""))


## The CC skill this slot uses now ("" = none): the dropped one while the hero can use it, else the class CC skill.
static func skill_id() -> String:
	if PlayerState.ch == null:
		return ""
	var s := chosen()
	if s != "" and CC.is_cc(s) and PlayerState.skill_lv(s) > 0 and _of_class(s):
		return s
	return CC.skill_of(str(PlayerState.job))


## Picked automatically (no usable dropped skill).
static func is_auto() -> bool:
	var s := chosen()
	return not (s != "" and CC.is_cc(s) and PlayerState.skill_lv(s) > 0 and _of_class(s))


static func _of_class(sid: String) -> bool:
	return sid in (GameData.jobs.get(str(PlayerState.job), {}).get("skills", []) as Array)


static func set_choice(sid: String) -> void:
	if PlayerState.ch == null:
		return
	# written into the AUTO settings: saved with the character (character_state.gd AUTO_DEFAULTS "cc_slot"),
	# sent to the server by remote_server.gd like any AUTO setting
	PlayerState.auto_cfg["cc_slot"] = sid


func _can_drop(_at: Vector2, data: Variant) -> bool:
	if not (data is Dictionary and str(data.get("type", "")) == "hotbar_entry"):
		return false
	var e := str(data.get("entry", ""))
	return e.begins_with("skill:") and CC.is_cc(e.substr(6))


func _drop(_at: Vector2, data: Variant) -> void:
	var sid := str(data.get("entry", "")).substr(6)
	set_choice(sid)
	PlayerState.msg(load("res://scripts/ui/quest_steps.gd").t2("CC slot: %s", "ช่องสกิลควบคุม: %s") % GameData.skill_name(sid), Color(0.75, 0.6, 1.0))


func _input_btn(ev: InputEvent) -> void:
	if ev is InputEventMouseButton and ev.pressed and ev.button_index == MOUSE_BUTTON_RIGHT:
		# back to the automatic pick
		set_choice("")
		btn.accept_event()


# ---------------------------------------------------------------- use

## Press / key "cc_skill": casts the slot's skill. Returns what happened (tests): "cast", "target", "aim", "none", "locked".
func press() -> String:
	var pl = hud.player if hud else null
	var sid := skill_id()
	if pl == null or PlayerState.ch == null:
		return "none"
	if sid == "":
		PlayerState.msg(load("res://scripts/ui/quest_steps.gd").t2("This class has no CC skill.", "อาชีพนี้ไม่มีสกิลควบคุม"), Color(1, 0.8, 0.6))
		return "none"
	if PlayerState.skill_lv(sid) <= 0:
		PlayerState.msg(load("res://scripts/ui/quest_steps.gd").t2("%s: learned free at Base Lv %d.", "%s: ได้ฟรีเมื่อเลเวล %d") % [GameData.skill_name(sid), int(GameData.skill(sid).get("min_base", 20))], Color(1, 0.8, 0.6))
		return "locked"
	pl.manual_control()
	var tgt = pl.get("attack_target")
	var has_t: bool = tgt != null and is_instance_valid(tgt) and not bool(tgt.get("dead"))
	if str(GameData.skill(sid).get("target", "")) == "enemy" and not has_t and str(pl.get("casting")) == "":
		var tc = hud.ui_root.get_node_or_null("TouchControls")
		var reach := float(GameData.skill(sid).get("range", 12.0)) + 2.0
		var m = tc.nearest("monsters", reach) if tc and tc.has_method("nearest") else null
		if m != null:
			hud.set_target(m)
			pl.send({"t": "skill", "id": sid, "target": m.id, "auto": 0})
			return "target"
	pl.use_skill(sid)
	return "cast" if has_t or str(GameData.skill(sid).get("target", "")) != "enemy" else "aim"


func key_text() -> String:
	return Settings.key_hint("cc_skill") if Settings.has_method("key_hint") else ""


func tip() -> String:
	var Q = load("res://scripts/ui/quest_steps.gd")
	var sid := skill_id()
	var key := key_text()
	var head: String = Q.t2("CC skill slot", "ช่องสกิลควบคุม (CC)") + (("  (" + key + ")") if key != "" else "")
	if sid == "":
		return head + "\n" + Q.t2("This class has no CC skill.", "อาชีพนี้ไม่มีสกิลควบคุม")
	var lines: Array = [head, GameData.skill_name(sid)]
	if PlayerState.skill_lv(sid) <= 0:
		lines.append(Q.t2("Learned free at Base Lv %d.", "ได้ฟรีเมื่อเลเวล %d") % int(GameData.skill(sid).get("min_base", 20)))
	else:
		var br := CC.branch_id(PlayerState.ch, sid)
		for b in CC.branches(sid):
			if str(b.get("id", "")) == br:
				lines.append(Q.t2("Branch: %s", "สาย: %s") % (str(b.get("name_th", b.get("name", br))) if Q.th() else str(b.get("name", br))))
		lines.append(Q.t2("Cooldown %d s", "คูลดาวน์ %d วินาที") % int(GameData.skill(sid).get("cooldown", 120)))
	lines.append(Q.t2("Auto: the class CC skill" if is_auto() else "Set by you (right-click: auto)",
		"อัตโนมัติ: สกิลควบคุมของอาชีพ" if is_auto() else "ตั้งเอง (คลิกขวา: กลับเป็นอัตโนมัติ)"))
	lines.append(Q.t2("Drag a CC skill here. AUTO casts it by itself (AUTO settings: CC skill).",
		"ลากสกิลควบคุมมาวางที่นี่ได้ · ออโต้ใช้เองอัตโนมัติ (ตั้งค่าออโต้: สกิลควบคุม)"))
	return "\n".join(lines)


func _process(delta: float) -> void:
	_t -= delta
	if _t > 0.0:
		return
	_t = 0.25
	var t_on := _touch_on()
	if t_on != _touch:
		layout()
	elif not t_on:
		# the pad re-scales with the view (size_changed) - cheap check that we still match it
		var want := (Pad.C0 + CC_OFF) * pad_k()
		if absf(btn.offset_left - (want.x - D * pad_k() * 0.5)) > 0.5:
			layout()
	visible = PlayerState.ch != null and hud.auto_btn != null and hud.auto_btn.is_visible_in_tree()
	var tt := tip()
	if UiSkin.v3():
		btn.set_meta("ui3_tip", "text:ccslot")
		btn.set_meta("ui3_tip_text", tt)
		btn.tooltip_text = ""
	else:
		btn.tooltip_text = tt


## The slot face: round skill icon, CC cooldown sweep + seconds, key at the top-left, "CC" ribbon at the bottom,
## a small "A" badge while auto-picked, a padlock before Lv 20, a faint rune when the class has no CC skill.
class SlotArt extends Control:
	var slot = null

	func _process(_d: float) -> void:
		queue_redraw()

	func _draw() -> void:
		if slot == null:
			return
		var sid: String = slot.skill_id()
		var c := size * 0.5
		var s := size.x / 72.0
		var r := size.x * 0.5 - maxf(4.0, roundf(size.x * 0.07))
		var v4: bool = UiSkin.v4()
		var lv: int = PlayerState.skill_lv(sid) if sid != "" else 0
		var violet := Color("#b48cff")
		draw_circle(c, r, Color("#2f2a4a") if v4 else Color("#1e1430"))
		var tex: Texture2D = Icons.skill_icon(sid) if sid != "" else null
		if tex:
			var pts := PackedVector2Array()
			var uvs := PackedVector2Array()
			for i in 40:
				var a := TAU * i / 40.0
				var p := c + Vector2(cos(a), sin(a)) * r
				pts.append(p)
				uvs.append((p - (c - Vector2(r, r))) / (r * 2.0))
			draw_colored_polygon(pts, Color(1, 1, 1, 1.0 if lv > 0 else 0.4), uvs, tex)
		elif sid == "":
			# no CC skill for this class: a faint rune
			draw_arc(c, r * 0.7, 0.0, TAU, 40, Color(violet, 0.3), 1.5 * s, true)
		var cd: Vector2 = Pad.cd_of(sid) if lv > 0 else Vector2.ZERO
		if lv > 0:
			Pad.draw_sweep(self, c, r, cd)
			if cd.x <= 0.0:
				var g := 0.5 + 0.5 * sin(Time.get_ticks_msec() / 1000.0 * 4.0)
				draw_arc(c, r + 1.5 * s, 0.0, TAU, 48, Color(violet, 0.35 + 0.4 * g), 3.0 * s, true)
		elif sid != "":
			load("res://scripts/ui/unlock_card.gd").draw_padlock(self, c, r * 0.5)
		draw_arc(c, r, 0.0, TAU, 48, Color(violet.darkened(0.2), 0.95), 2.0 * s, true)
		var f: Font = Kanit.font("Bold")
		# key (top-left, like the hotbar's F1..F9)
		var key: String = slot.key_text()
		if key != "":
			var fk := int(round(12.0 * s))
			draw_string_outline(f, Vector2(4.0 * s, 14.0 * s), key, HORIZONTAL_ALIGNMENT_LEFT, -1, fk, int(round(4.0 * s)), Color(0, 0, 0, 0.9))
			draw_string(f, Vector2(4.0 * s, 14.0 * s), key, HORIZONTAL_ALIGNMENT_LEFT, -1, fk, Color(1, 0.92, 0.7))
		# "CC" ribbon at the bottom
		var word := "CC"
		var fs := int(round(12.0 * s))
		var w := f.get_string_size(word, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
		var pr := Rect2(Vector2(c.x - w * 0.5 - 6.0 * s, size.y - 15.0 * s), Vector2(w + 12.0 * s, 14.0 * s))
		var sb := StyleBoxFlat.new()
		sb.bg_color = Color("#5a3aa0")
		sb.border_color = Color("#fff4d6")
		sb.set_border_width_all(maxi(1, int(round(1.5 * s))))
		sb.set_corner_radius_all(int(7.0 * s))
		draw_style_box(sb, pr)
		draw_string(f, Vector2(c.x - w * 0.5, pr.position.y + 11.5 * s), word, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Color.WHITE)
		# auto-picked badge (top-right)
		if sid != "" and slot.is_auto():
			var bc := Vector2(size.x - 9.0 * s, 9.0 * s)
			draw_circle(bc, 7.5 * s, Color("#3fae3a"))
			draw_arc(bc, 7.5 * s, 0.0, TAU, 20, Color("#fff4d6"), 1.2 * s, true)
			var fa := int(round(10.0 * s))
			var aw := f.get_string_size("A", HORIZONTAL_ALIGNMENT_LEFT, -1, fa).x
			draw_string(f, bc + Vector2(-aw * 0.5, fa * 0.36), "A", HORIZONTAL_ALIGNMENT_LEFT, -1, fa, Color.WHITE)
