package browser

import "fmt"

// pressKeyEntry define los atributos CDP de una tecla especial.
type pressKeyEntry struct {
	vk   int
	key  string
	code string
	text string
}

// pressKeyTable mapea nombres de tecla a sus atributos CDP.
var pressKeyTable = map[string]pressKeyEntry{
	"Enter":      {vk: 13, key: "Enter", code: "Enter", text: "\r"},
	"Tab":        {vk: 9, key: "Tab", code: "Tab"},
	"Escape":     {vk: 27, key: "Escape", code: "Escape"},
	"Backspace":  {vk: 8, key: "Backspace", code: "Backspace"},
	"Delete":     {vk: 46, key: "Delete", code: "Delete"},
	"ArrowUp":    {vk: 38, key: "ArrowUp", code: "ArrowUp"},
	"ArrowDown":  {vk: 40, key: "ArrowDown", code: "ArrowDown"},
	"ArrowLeft":  {vk: 37, key: "ArrowLeft", code: "ArrowLeft"},
	"ArrowRight": {vk: 39, key: "ArrowRight", code: "ArrowRight"},
	"Home":       {vk: 36, key: "Home", code: "Home"},
	"End":        {vk: 35, key: "End", code: "End"},
	"PageUp":     {vk: 33, key: "PageUp", code: "PageUp"},
	"PageDown":   {vk: 34, key: "PageDown", code: "PageDown"},
	"Space":      {vk: 32, key: " ", code: "Space", text: " "},
}

// CdpPressKey pulsa una tecla especial por nombre usando Input.dispatchKeyEvent.
// Soporta: Enter, Tab, Escape, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft,
// ArrowRight, Home, End, PageUp, PageDown, Space.
// Actua sobre el elemento con foco activo en la pagina.
func CdpPressKey(c *CDPConn, keyName string) error {
	if c == nil {
		return fmt.Errorf("cdp press key: conexion nula")
	}

	entry, ok := pressKeyTable[keyName]
	if !ok {
		return fmt.Errorf("cdp press key: tecla no soportada: %s", keyName)
	}

	down := map[string]any{
		"type":                  "keyDown",
		"windowsVirtualKeyCode": entry.vk,
		"key":                   entry.key,
		"code":                  entry.code,
	}
	if entry.text != "" {
		down["text"] = entry.text
	}
	if _, err := c.sendCDP("Input.dispatchKeyEvent", down); err != nil {
		return fmt.Errorf("cdp press key: keyDown %q: %w", keyName, err)
	}

	up := map[string]any{
		"type":                  "keyUp",
		"windowsVirtualKeyCode": entry.vk,
		"key":                   entry.key,
		"code":                  entry.code,
	}
	if _, err := c.sendCDP("Input.dispatchKeyEvent", up); err != nil {
		return fmt.Errorf("cdp press key: keyUp %q: %w", keyName, err)
	}

	return nil
}
