local imgui = require 'mimgui'
local faicons = require 'fAwesome6'
local inicfg = require 'inicfg'

local GUI = {}

--================================================---
--  GUI STYLING & HELPERS
--================================================---

function GUI.applyModernStyle()
    local style = imgui.GetStyle()
    local colors = style.Colors
    
    local accentColor = imgui.ImVec4(0.1, 0.5, 0.9, 1.0)
    local accentColorHover = imgui.ImVec4(0.2, 0.6, 1.0, 1.0)
    local bgColor = imgui.ImVec4(0.08, 0.08, 0.1, 1.0)
    local itemBgColor = imgui.ImVec4(0.12, 0.12, 0.15, 1.0)
    local textColor = imgui.ImVec4(0.9, 0.9, 0.9, 1.0)

    style.WindowPadding = imgui.ImVec2(8, 8)
    style.FramePadding = imgui.ImVec2(6, 4)
    style.ItemSpacing = imgui.ImVec2(8, 6)
    style.ItemInnerSpacing = imgui.ImVec2(4, 4)
    style.IndentSpacing = 20.0
    style.ScrollbarSize = 14.0
    style.GrabMinSize = 20.0
    
    style.WindowRounding = 6.0
    style.ChildRounding = 6.0
    style.FrameRounding = 4.0
    style.GrabRounding = 4.0
    style.ScrollbarRounding = 4.0
    
    colors[imgui.Col.Text]                   = textColor
    colors[imgui.Col.TextDisabled]           = imgui.ImVec4(0.5, 0.5, 0.5, 1.0)
    colors[imgui.Col.WindowBg]               = bgColor
    colors[imgui.Col.ChildBg]                = imgui.ImVec4(0.09, 0.09, 0.11, 1.0)
    colors[imgui.Col.PopupBg]                = bgColor
    colors[imgui.Col.Border]                 = imgui.ImVec4(0.3, 0.3, 0.3, 1.0)
    colors[imgui.Col.BorderShadow]           = imgui.ImVec4(0.0, 0.0, 0.0, 0.0)
    
    colors[imgui.Col.FrameBg]                = itemBgColor
    colors[imgui.Col.FrameBgHovered]         = imgui.ImVec4(0.2, 0.2, 0.25, 1.0)
    colors[imgui.Col.FrameBgActive]          = accentColor
    
    colors[imgui.Col.TitleBg]                = itemBgColor
    colors[imgui.Col.TitleBgActive]          = accentColor
    colors[imgui.Col.TitleBgCollapsed]       = itemBgColor
    
    colors[imgui.Col.MenuBarBg]              = itemBgColor
    
    colors[imgui.Col.ScrollbarBg]            = itemBgColor
    colors[imgui.Col.ScrollbarGrab]          = imgui.ImVec4(0.4, 0.4, 0.4, 1.0)
    colors[imgui.Col.ScrollbarGrabHovered]   = imgui.ImVec4(0.6, 0.6, 0.6, 1.0)
    colors[imgui.Col.ScrollbarGrabActive]    = imgui.ImVec4(0.8, 0.8, 0.8, 1.0)
    
    colors[imgui.Col.CheckMark]              = accentColorHover
    
    colors[imgui.Col.SliderGrab]             = accentColor
    colors[imgui.Col.SliderGrabActive]       = accentColorHover
    
    colors[imgui.Col.Button]                 = accentColor
    colors[imgui.Col.ButtonHovered]          = accentColorHover
    colors[imgui.Col.ButtonActive]           = imgui.ImVec4(0.05, 0.4, 0.8, 1.0)
    
    colors[imgui.Col.Header]                 = accentColor
    colors[imgui.Col.HeaderHovered]          = accentColorHover
    colors[imgui.Col.HeaderActive]           = imgui.ImVec4(0.05, 0.4, 0.8, 1.0)
    
    colors[imgui.Col.Separator]              = imgui.ImVec4(0.3, 0.3, 0.3, 1.0)
    colors[imgui.Col.SeparatorHovered]       = accentColor
    colors[imgui.Col.SeparatorActive]        = accentColorHover
    
    colors[imgui.Col.ResizeGrip]             = imgui.ImVec4(0.2, 0.2, 0.2, 1.0)
    colors[imgui.Col.ResizeGripHovered]      = accentColor
    colors[imgui.Col.ResizeGripActive]       = accentColorHover
end

function GUI.SideButton(label, index, active_index_ptr)
    local isActive = (active_index_ptr[0] == index)
    
    if isActive then
        imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(0.1, 0.5, 0.9, 1.0))
        imgui.PushStyleColor(imgui.Col.Text, imgui.ImVec4(1, 1, 1, 1))
    else
        imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(0.12, 0.12, 0.15, 1.0))
        imgui.PushStyleColor(imgui.Col.Text, imgui.ImVec4(0.7, 0.7, 0.7, 1.0))
    end
    
    if imgui.Button(label, imgui.ImVec2(imgui.GetContentRegionAvail().x, 40)) then
        active_index_ptr[0] = index
    end
    
    imgui.PopStyleColor(2)
end

--================================================---
--  GUI RENDER FUNCTIONS
--================================================---

function GUI.render_main_window(state)
    local u8 = require('encoding').UTF8

    -- Deconstruct state for easier access
    local cheats = state.cheats
    local gui_state = state.gui
    local Core = require 'lib.Zuph.core' -- Need this for toggle functions

    local win_width, win_height = 550, 450
    local header_height = 45
    local btn_w, btn_h = 24, 24
    local spacing = imgui.GetStyle().ItemSpacing.x

    if gui_state.minimized[0] then
        imgui.SetNextWindowSize(imgui.ImVec2(80, 80), imgui.Cond.FirstUseEver)
        imgui.PushStyleColor(imgui.Col.WindowBg, imgui.ImVec4(0.0, 0.0, 0.0, 1.0))
        local flags = imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoScrollbar
        imgui.Begin("##ModMenuMin", gui_state.show_ui, flags)
        
        if gui_state.my_logo_texture then
            local logoSize = imgui.ImVec2(70, 80)
            local logoPos = imgui.ImVec2(5, 0)
            local winPos = imgui.GetWindowPos()
            local drawList = imgui.GetWindowDrawList()
            drawList:AddImage(gui_state.my_logo_texture, winPos + logoPos, winPos + imgui.ImVec2(logoPos.x + logoSize.x, logoPos.y + logoSize.y))
            
            local clickSize = imgui.ImVec2(40, 40)
            local clickPos = imgui.ImVec2(logoPos.x + (logoSize.x - clickSize.x) / 2, logoPos.y + (logoSize.y - clickSize.y) / 2)
            imgui.SetCursorPos(clickPos)
            imgui.InvisibleButton("logo_click", clickSize)
            
            if imgui.IsItemClicked(0) then
                gui_state.minimized[0] = false
            end
        end
        
        imgui.End()
        imgui.PopStyleColor()
        return
    end

    imgui.SetNextWindowSize(imgui.ImVec2(win_width, win_height), imgui.Cond.FirstUseEver)
    imgui.Begin("##ModMenu", gui_state.show_ui, imgui.WindowFlags.NoTitleBar)

    -- Header
    imgui.PushStyleColor(imgui.Col.ChildBg, imgui.ImVec4(0.15, 0.15, 0.15, 1.0))
    imgui.BeginChild("##header", imgui.ImVec2(-1, header_height), false, imgui.WindowFlags.NoScrollbar)

    local region = imgui.GetWindowContentRegionWidth()
    local total_button_width = (btn_w * 3) + (spacing * 2) + 15
    local text_area_width = region - total_button_width
    local text = "ZUPH PROJECT"
    local spacing_auto = text_area_width / (#text + 1)
    local y = 8
    local draw_list = imgui.GetWindowDrawList()
    local base_pos = imgui.GetCursorScreenPos()

    for i = 1, #text do
        local letter = text:sub(i, i)
        draw_list:AddText(imgui.ImVec2(base_pos.x + spacing_auto * i, base_pos.y + y), imgui.GetColorU32(1, 1, 1, 1), letter)
    end

    imgui.SetCursorPos(imgui.ImVec2(region - btn_w - 5, 5))
    if imgui.Button("X##close", imgui.ImVec2(btn_w, btn_h)) then
        gui_state.show_ui[0] = false
    end

    imgui.SetCursorPos(imgui.ImVec2(region - btn_w * 2 - spacing - 5, 5))
    if imgui.Button("UP", imgui.ImVec2(btn_w, btn_h)) then
        Core.cekUpdateOnline(state)
    end

    imgui.SetCursorPos(imgui.ImVec2(region - btn_w * 3 - spacing * 2 - 5, 5))
    if imgui.Button("-##minimize", imgui.ImVec2(btn_w, btn_h)) then
        gui_state.minimized[0] = true
    end

    imgui.EndChild()
    imgui.PopStyleColor()

    -- Popups
    if gui_state.showUpToDatePopup[0] then imgui.OpenPopup("VersiTerbaru"); gui_state.showUpToDatePopup[0] = false end
    if imgui.BeginPopupModal("VersiTerbaru", nil, imgui.WindowFlags.AlwaysAutoResize) then
        imgui.TextWrapped("✅ Script sudah versi terbaru (" .. state.updater.script_version .. ")")
        imgui.Dummy(imgui.ImVec2(0, 10))
        if imgui.Button("Tutup", imgui.ImVec2(150, 35)) then imgui.CloseCurrentPopup() end
        imgui.EndPopup()
    end
    
    if gui_state.showUpdatePrompt[0] then imgui.OpenPopup("KonfirmasiUpdate"); gui_state.showUpdatePrompt[0] = false end
    if imgui.BeginPopupModal("KonfirmasiUpdate", nil, imgui.WindowFlags.AlwaysAutoResize) then
        imgui.TextWrapped("Versi saat ini: " .. state.updater.script_version)
        imgui.TextWrapped("Versi terbaru : " .. state.updater.latest_version)
        imgui.Dummy(imgui.ImVec2(0, 10))
        imgui.TextWrapped("Apakah kamu yakin ingin memperbarui script sekarang?")
        imgui.Dummy(imgui.ImVec2(0, 10))
        if imgui.Button(" Ya ", imgui.ImVec2(100, 35)) then Core.updateScript(state); imgui.CloseCurrentPopup() end
        imgui.SameLine()
        if imgui.Button(" Batal ", imgui.ImVec2(100, 35)) then imgui.CloseCurrentPopup() end
        imgui.EndPopup()
    end

    -- Main Content
    if not gui_state.minimized[0] then
        imgui.BeginChild("LeftPanel", imgui.ImVec2(160, -45), true)
        GUI.SideButton(faicons("GEAR") .. " CHEAT MENU", 0, gui_state.active_menu_item)
        GUI.SideButton(faicons("EYE") .. " VISUAL HACK", 4, gui_state.active_menu_item)
        GUI.SideButton(faicons("CROSSHAIRS") .. " AIM HACK", 5, gui_state.active_menu_item)
        GUI.SideButton(faicons("WAND_MAGIC") .. " MISC/TROLL", 6, gui_state.active_menu_item)
        GUI.SideButton(faicons("MAP_LOCATION_DOT") .. " TELEPORT", 2, gui_state.active_menu_item)
        GUI.SideButton(faicons("CAR") .. " AUTODRIVE", 3, gui_state.active_menu_item)
        GUI.SideButton(faicons("CIRCLE_QUESTION") .. " HELPER", 1, gui_state.active_menu_item)
        GUI.SideButton(faicons("CIRCLE_INFO") .. " CREDITS", 7, gui_state.active_menu_item)
        imgui.EndChild()
        
        imgui.SameLine()

        imgui.BeginChild("RightPanel", imgui.ImVec2(0, -45), false, imgui.WindowFlags.NoScrollbar)
        imgui.BeginChild("ContentScroll", imgui.ImVec2(0,0), true)

        -- Cheat Menu
        if gui_state.active_menu_item[0] == 0 then
            imgui.Text(faicons("USER") .. " Player Hacks")
            imgui.Columns(2, "##player_hacks_cols", false)
            
            if imgui.Checkbox(faicons("SHIELD") .. " God Mode", cheats.godMode) then Core.toggle_god_mode(state, cheats.godMode[0]) end
            imgui.Checkbox(faicons("INFINITY") .. " No Reload", cheats.noReload)
            if imgui.Checkbox(faicons("STAR") .. " Anti Stun", cheats.antiStun) then Core.toggle_anti_stun(state, cheats.antiStun[0]) end
            if imgui.Checkbox(faicons("PERSON_RUNNING") .. " Infinity Run", cheats.infinityRun) then Core.toggle_infinity_run(state, cheats.infinityRun[0]) end
            
            imgui.Checkbox(faicons("HAND_POINTER") .. " C-Bug Deagle", cheats.cbugde)
            if cheats.cbugde[0] then
                imgui.SliderFloat(faicons("CLOCK") .. " Delay C-Bug", cheats.cbugsp, 1.0, 200.0, "%.0f ms")
            end
            
            imgui.Checkbox(faicons("BOLT") .. " Fast Reload", cheats.reloadspd)
            if cheats.reloadspd[0] then
                imgui.SliderFloat(faicons("GAUGE_HIGH") .. " Reload Speed", cheats.reloadspeed, 1.0, 10.0, "%.1f")
            end
            
            imgui.NextColumn()
            
            imgui.Checkbox(faicons("PARACHUTE_BOX") .. " No Fall", cheats.noFall)
            if imgui.Checkbox(faicons("GHOST") .. " Invisible", cheats.invisible) then Core.toggle_invisible(state, cheats.invisible[0]) end
            if imgui.Checkbox(faicons("USER") .. " CJ Run Style", cheats.cjRun) then Core.toggle_cj_run(state, cheats.cjRun[0]) end
            
            imgui.Checkbox(faicons("ARROW_UP") .. " Jump High", cheats.jumpBoost)
            if cheats.jumpBoost[0] then
                imgui.SliderFloat(faicons("ROCKET") .. " Jump Power", cheats.jumpPower, 0.3, 5.0, "%.2f")
            end
            
            if imgui.Checkbox(faicons("PERSON_WALKING") .. " Fast Walk", cheats.fastWalk) then Core.toggle_fast_walk(state, cheats.fastWalk[0]) end
            if cheats.fastWalk[0] then
                if imgui.SliderFloat(faicons("GAUGE_HIGH") .. " Walk Speed", cheats.fastWalkSpeed, 1.0, 10.0, "%.1f") then
                    Core.toggle_fast_walk(state, true) -- Update speed
                end
            end
            
            if imgui.Checkbox(faicons("FIRE") .. " Fast Fire", cheats.fastFire) then Core.toggle_fast_fire(state, cheats.fastFire[0]) end
            if cheats.fastFire[0] then
                if imgui.SliderFloat(faicons("GAUGE_HIGH") .. " Fire Speed", cheats.fastFireSpeed, 1.0, 10.0, "%.1f") then
                    Core.toggle_fast_fire(state, true) -- Update speed
                end
            end
            
            imgui.Columns(1)
            imgui.Dummy(imgui.ImVec2(0, 10))
            
            imgui.Text(faicons("CAR") .. " Vehicle Hacks")
            imgui.Columns(2, "##vehicle_hacks_cols", false)
            
            if imgui.Checkbox(faicons("SHIELD") .. " God Mode Car", cheats.godModeCar) then Core.toggle_god_mode_car(state, cheats.godModeCar[0]) end
            imgui.Checkbox(faicons("GAS_PUMP") .. " Infinity Fuel", cheats.infinityFuel)
            imgui.Checkbox(faicons("ROTATE_LEFT") .. " No Flip", cheats.noflip)
            imgui.Checkbox(faicons("WRENCH") .. " Repair On Key", cheats.rponce)
            
            imgui.NextColumn()
            
            imgui.Checkbox(faicons("GAUGE_HIGH") .. " Drift Mode", cheats.driftMode)
            imgui.Checkbox(faicons("FIRE") .. " Nitro Hack", cheats.nitrohack)
            imgui.Checkbox(faicons("BAN") .. " No Collision", cheats.noclipMulti)
            imgui.Checkbox(faicons("ROCKET") .. " PowerBoost Hack", cheats.speedHack)
            if cheats.speedHack[0] then
                imgui.SliderFloat(faicons("CIRCLE_PLUS") .. " Boost Power", cheats.speedValue, 1.0, 30.0, "%.1f")
            end

            imgui.Columns(1)
        
        -- Helper
        elseif gui_state.active_menu_item[0] == 1 then
            imgui.Text(faicons("GLOBE") .. u8" Pengaturan Translator")
            imgui.Separator()
            imgui.Checkbox(faicons("TOGGLE_ON") .. " Aktifkan Translator", state.runtime.enabled_translator)
            imgui.Checkbox(faicons("TERMINAL") .. " Tampilkan Jendela Log", state.runtime.show_translator_log)
            imgui.TextWrapped(u8"Jika Jendela Log aktif, terjemahan hanya akan muncul di sana (tidak di chat SA-MP).")
            imgui.Spacing()
            imgui.Text(faicons("LANGUAGE") .. " Bahasa Target (ex: en, id, ja):")
            imgui.PushItemWidth(100)
            if imgui.InputText("##Lang", state.runtime.input_lang, 8) then state.runtime.target_lang = u8:decode(state.runtime.input_lang) end
            imgui.PopItemWidth()
        
        -- Teleport
        elseif gui_state.active_menu_item[0] == 2 then
            imgui.Text(faicons("MAP_LOCATION_DOT") .. u8" Fitur Teleport")
            imgui.Separator()
            local btn_size = imgui.ImVec2(imgui.GetContentRegionAvail().x, 35)
            
            if imgui.Button(faicons("MAP_PIN") .. " Teleport ke Marker", btn_size) then lua_thread.create(function() Core.startTeleport(state, '') end) end
            if imgui.Button(faicons("FLAG_CHECKERED") .. " Teleport ke Checkpoint", btn_size) then lua_thread.create(function() Core.startTeleport(state, 'chp') end) end
            
            imgui.Separator()
            imgui.Text(faicons("GEAR") .. " Pengaturan Teleport")
            imgui.PushItemWidth(-1)

            imgui.Text(faicons("CLOCK") .. u8"ON FOOT")
            imgui.Separator()
            if imgui.SliderInt(faicons("CLOCK") .. u8(" Sleep OnFoot"), state.teleport_vars.sleep_onfoot, 0, 100) then state.ini.teleport_settings.Sleep_Onfoot = state.teleport_vars.sleep_onfoot[0] end
            
            imgui.Text(faicons("GAUGE_HIGH") .. u8"SPEED FOOT")
            imgui.Separator()
            if imgui.SliderInt(faicons("GAUGE_HIGH") .. u8(" LoopWait OnFoot"), state.teleport_vars.loopwait_onfoot, 0, 8500) then state.ini.teleport_settings.LoopWait_Onfoot = state.teleport_vars.loopwait_onfoot[0] end
            
            imgui.Text(faicons("CLOCK") .. u8"IN CAR")
            imgui.Separator()
            if imgui.SliderInt(faicons("CLOCK") .. u8(" Sleep InCar"), state.teleport_vars.sleep_incar, 0, 100) then state.ini.teleport_settings.Sleep_Incar = state.teleport_vars.sleep_incar[0] end
            
            imgui.Text(faicons("GAUGE_HIGH") .. u8"SPEED IN CAR")
            imgui.Separator()
            if imgui.SliderInt(faicons("GAUGE_HIGH") .. u8(" LoopWait InCar"), state.teleport_vars.loopwait_incar, 0, 8500) then state.ini.teleport_settings.LoopWait_Incar = state.teleport_vars.loopwait_incar[0] end
            imgui.PopItemWidth()
            
            local bar_text = state.ini.teleport_settings.RenderBar_State and (faicons("TOGGLE_ON") .. " Info Bar: ON") or (faicons("TOGGLE_OFF") .. " Info Bar: OFF")
            if imgui.Button(bar_text, imgui.ImVec2(-1, 0)) then state.ini.teleport_settings.RenderBar_State = not state.ini.teleport_settings.RenderBar_State end
        
        -- AutoDrive Pro
        elseif gui_state.active_menu_item[0] == 3 then
            imgui.Text(faicons("CAR") .. u8" Fitur AutoDrive Pro")
            imgui.Separator()
            local button_width = (imgui.GetContentRegionAvail().x - imgui.GetStyle().ItemSpacing.x) * 0.5
            
            if imgui.Button(faicons("MAP_PIN") .. " Menuju Waypoint", imgui.ImVec2(button_width, 40)) then 
                Core.getTargetBlipCoordinatesFixed(function(s, x, y, z) 
                    if s then 
                        state.ap.status.target = {x=x, y=y, z=z}
                        Core.startAutoPilot(state, 'waypoint') 
                    else 
                        sampAddChatMessage("{FF0000}[AutoDrive]: Pasang waypoint dulu!", -1) 
                    end 
                end) 
            end
            imgui.SameLine()
            if imgui.Button(faicons("CIRCLE_STOP") .. " Hentikan Autopilot", imgui.ImVec2(button_width, 40)) then Core.stopAutoPilot(state, "~y~Dihentikan manual.") end
            
            if imgui.Button(faicons("FLAG_CHECKERED") .. " Menuju Checkpoint", imgui.ImVec2(-1, 40)) then 
                if state.runtime.checkpointCoords.active then 
                    state.ap.status.target = {x=state.runtime.checkpointCoords.x, y=state.runtime.checkpointCoords.y, z=state.runtime.checkpointCoords.z}
                    Core.startAutoPilot(state, 'checkpoint') 
                else 
                    sampAddChatMessage("{FF0000}[AutoDrive]: Tidak ada checkpoint.", -1) 
                end 
            end
            if imgui.Button(faicons("ROUTE") .. " Ikuti Rute Checkpoint", imgui.ImVec2(-1, 40)) then 
                if state.runtime.checkpointCoords.active then 
                    Core.startAutoPilot(state, 'master') 
                else 
                    sampAddChatMessage("{FF0000}[AutoDrive]: Tidak ada checkpoint untuk memulai rute.", -1) 
                end 
            end
            
            imgui.Separator()
            imgui.Text(faicons("GAUGE_HIGH") .. u8" Kecepatan Maksimal:")
            imgui.PushItemWidth(-1);
            if imgui.SliderFloat("##Speed", state.ap.settings.speed, 10.0, 150.0, "%.0f") then state.ini.autodrive_settings.ap_speed = state.ap.settings.speed[0] end
            imgui.PopItemWidth()
            
            imgui.Text(faicons("ROAD") .. u8" Gaya Mengemudi:")
            if imgui.RadioButtonIntPtr(" Normal", state.ap.settings.ride_type, 0) then state.ini.autodrive_settings.ap_ride_type = 0 end; imgui.SameLine()
            if imgui.RadioButtonIntPtr(" Langsung", state.ap.settings.ride_type, 2) then state.ini.autodrive_settings.ap_ride_type = 2 end; imgui.SameLine()
            if imgui.RadioButtonIntPtr(" Agresif", state.ap.settings.ride_type, 3) then state.ini.autodrive_settings.ap_ride_type = 3 end
            
            imgui.Text(faicons("TRAFFIC_LIGHT") .. u8" Perilaku Berkendara:")
            if imgui.RadioButtonIntPtr(" Patuhi Aturan", state.ap.settings.drive_type, 0) then state.ini.autodrive_settings.ap_drive_type = 0 end; imgui.SameLine()
            if imgui.RadioButtonIntPtr(" Hindari Mobil", state.ap.settings.drive_type, 2) then state.ini.autodrive_settings.ap_drive_type = 2 end; imgui.SameLine()
            if imgui.RadioButtonIntPtr(" Ugal-ugalan", state.ap.settings.drive_type, 7) then state.ini.autodrive_settings.ap_drive_type = 7 end
        
        -- Visual Hack (ESP)
        elseif gui_state.active_menu_item[0] == 4 then
            local esp = state.esp
            imgui.Text(faicons("USER") .. u8" Player Visual ESP")
            imgui.Separator()
            if imgui.Checkbox(faicons("EYE") .. " Player Esp", esp.showEsp) then
                state.ini.esp_settings.showEsp = esp.showEsp[0]
                if not esp.showEsp[0] then
                    esp.showLine[0], esp.showBox[0], esp.showBar[0] = false, false, false
                    esp.showSkeleton[0], esp.showNametag[0], esp.showDist[0] = false, false, false
                end
            end

            if esp.showEsp[0] then
                if imgui.Checkbox(faicons("MINUS") .. " Player: Line", esp.showLine) then state.ini.esp_settings.showLine = esp.showLine[0] end
                imgui.SameLine()
                if imgui.Checkbox(faicons("SQUARE") .. " Player: Box", esp.showBox) then state.ini.esp_settings.showBox = esp.showBox[0] end
                
                if imgui.Checkbox(faicons("HEART_PULSE") .. " Player: HP/AP", esp.showBar) then state.ini.esp_settings.showBar = esp.showBar[0] end
                imgui.SameLine()
                if imgui.Checkbox(faicons("BONE") .. " Player: Skeleton", esp.showSkeleton) then state.ini.esp_settings.showSkeleton = esp.showSkeleton[0] end
                
                if imgui.Checkbox(faicons("TAG") .. " Player: Name/Dev", esp.showNametag) then state.ini.esp_settings.showNametag = esp.showNametag[0] end
                imgui.SameLine()
                if imgui.Checkbox(faicons("RULER_HORIZONTAL") .. " Player: Distance", esp.showDist) then state.ini.esp_settings.showDist = esp.showDist[0] end
            end

            imgui.Separator()
            imgui.Text(faicons("CAR") .. u8" Vehicle Visual ESP")
            imgui.Separator()

            if imgui.Checkbox(faicons("EYE") .. " Vehicle ESP", esp.vehShow) then
                state.ini.esp_vehicle_settings.show = esp.vehShow[0]
                if not esp.vehShow[0] then
                    esp.vehShowLine[0], esp.vehShowBox[0], esp.vehShowName[0] = false, false, false
                    esp.vehShowId[0], esp.vehShowHp[0], esp.vehShowDist[0] = false, false, false
                end
            end

            if esp.vehShow[0] then
                if imgui.Checkbox(faicons("MINUS") .. " Vehicle: Line", esp.vehShowLine) then state.ini.esp_vehicle_settings.showLine = esp.vehShowLine[0] end
                imgui.SameLine()
                if imgui.Checkbox(faicons("SQUARE") .. " Vehicle: Box", esp.vehShowBox) then state.ini.esp_vehicle_settings.showBox = esp.vehShowBox[0] end
                
                if imgui.Checkbox(faicons("TAG") .. " Vehicle: Name", esp.vehShowName) then state.ini.esp_vehicle_settings.showName = esp.vehShowName[0] end
                imgui.SameLine()
                if imgui.Checkbox(faicons("ID_CARD") .. " Vehicle: ID", esp.vehShowId) then state.ini.esp_vehicle_settings.showId = esp.vehShowId[0] end

                if imgui.Checkbox(faicons("HEART") .. " Vehicle: Health", esp.vehShowHp) then state.ini.esp_vehicle_settings.showHp = esp.vehShowHp[0] end
                imgui.SameLine()
                if imgui.Checkbox(faicons("RULER_HORIZONTAL") .. " Vehicle: Distance", esp.vehShowDist) then state.ini.esp_vehicle_settings.showDist = esp.vehShowDist[0] end
            end
            
            imgui.Separator()
            local screenX, screenY = getScreenResolution()
            if imgui.SliderInt(faicons("ARROWS_LEFT_RIGHT") .. " Line Start X", esp.lineStartX, 0, screenX) then state.ini.esp_settings.lineStartX = esp.lineStartX[0] end
            if imgui.SliderInt(faicons("ARROWS_UP_DOWN") .. " Line Start Y", esp.lineStartY, 0, screenY) then state.ini.esp_settings.lineStartY = esp.lineStartY[0] end
            
            imgui.Separator()
            if imgui.Checkbox(faicons("RAINBOW") .. " Rainbow Color", esp.useRainbow) then state.ini.esp_settings.useRainbow = esp.useRainbow[0] end
            if not esp.useRainbow[0] then
                if imgui.ColorEdit4(faicons("PALETTE") .. " ESP Color", esp.colorFloat) then
                    state.ini.esp_settings.colorR = esp.colorFloat[0]
                    state.ini.esp_settings.colorG = esp.colorFloat[1]
                    state.ini.esp_settings.colorB = esp.colorFloat[2]
                    state.ini.esp_settings.colorA = esp.colorFloat[3]
                end
            end
        
        -- AIM Hack
        elseif gui_state.active_menu_item[0] == 5 then
            local aimhack = state.aimhack
            imgui.Text(faicons("CROSSHAIRS") .. u8" Pengaturan AIM HACK")
            imgui.Separator()
            imgui.Text("Mode:")
            if imgui.Checkbox(faicons("CROSSHAIRS") .. " Aimbot ", aimhack.camera_enabled) then state.ini.aimhack_settings.camera_enabled = aimhack.camera_enabled[0] end
            if imgui.Checkbox(faicons("VOLUME_OFF") .. " Silent Aim ", aimhack.silent_enabled) then state.ini.aimhack_settings.silent_enabled = aimhack.silent_enabled[0] end
            if aimhack.silent_enabled[0] then
                imgui.SetCursorPosX(imgui.GetCursorPosX() + 20)
                if imgui.Checkbox(faicons("BAN") .. " ignore Wall", aimhack.antiWall) then state.ini.aimhack_settings.antiWall = aimhack.antiWall[0] end
                imgui.SameLine()
                imgui.Checkbox(faicons("ARROW_RIGHT") .. "Show Target Line", state.runtime.esp_line_enabled)
            end
            if imgui.Checkbox(faicons("CIRCLE") .. " Aktifkan FOV", aimhack.showFOV) then state.ini.aimhack_settings.showFOV = aimhack.showFOV[0] end
            
            imgui.Separator()
            imgui.Text(faicons("BONE") .. " Target Tulang (Bone):")
            if imgui.RadioButtonIntPtr(" Kepala", aimhack.selectedBoneInt, 0) then state.ini.aimhack_settings.selectedBone = 0 end
            imgui.SameLine()
            if imgui.RadioButtonIntPtr(" Dada", aimhack.selectedBoneInt, 1) then state.ini.aimhack_settings.selectedBone = 1 end
            imgui.SameLine()
            if imgui.RadioButtonIntPtr(" Perut", aimhack.selectedBoneInt, 2) then state.ini.aimhack_settings.selectedBone = 2 end
        
            imgui.Separator()
            imgui.Text(faicons("LIST_OL") .. " Prioritas Target")
            if imgui.RadioButtonIntPtr(" Paling Dekat dengan Crosshair", aimhack.targetPriority, 0) then state.ini.aimhack_settings.targetPriority = 0 end
            if imgui.RadioButtonIntPtr(" Paling Dekat dengan Anda (Terdepan)", aimhack.targetPriority, 1) then state.ini.aimhack_settings.targetPriority = 1 end
            
            imgui.Separator()
            imgui.Text(faicons("GEAR") .. " Pengaturan Umum (berlaku untuk semua mode):")
            imgui.PushItemWidth(-1)
            if imgui.SliderFloat(faicons("RULER") .. " Jarak Target Maks", aimhack.maxDistance, 10.0, 300.0, "%.0f m") then state.ini.aimhack_settings.maxDistance = aimhack.maxDistance[0] end
            if imgui.SliderFloat(faicons("EXPAND") .. " Field of View (FOV)", aimhack.maxFOV, 0.1, 2.5, "%.2f rad") then state.ini.aimhack_settings.maxFOV = aimhack.maxFOV[0] end
            imgui.PopItemWidth()
            
        -- Troll Hack
        elseif gui_state.active_menu_item[0] == 6 then
            imgui.Text(faicons("CUBE") .. " SeatVehicle")
            if imgui.Checkbox(faicons("CHAIR") .. u8' Aktifkan Fitur Seat', state.runtime.troll_seat_enabled) then end
            
            if state.runtime.troll_seat_enabled[0] then
                imgui.Separator()
                imgui.InputInt(u8'ID Kendaraan', state.runtime.troll_car_id_input, 1, 10)
                local id = state.runtime.troll_car_id_input[0]
                imgui.Spacing()
                if imgui.Button(faicons("STEERING_WHEEL") .. u8' Masuk Driver', imgui.ImVec2(-1, 0)) then if Core.troll_isValidId(id) then Core.troll_seatDriver(id) else sampAddChatMessage("[Troll] ID tidak valid.", 0xFF0000) end end
                imgui.Spacing()
                if imgui.Button(faicons("USERS") .. u8' Masuk Penumpang', imgui.ImVec2(-1, 0)) then if Core.troll_isValidId(id) then Core.troll_seatPassenger(id) else sampAddChatMessage("[Troll] ID tidak valid.", 0xFF0000) end end
                imgui.Spacing()
                if imgui.Button(faicons("DOOR_OPEN") .. u8' Buka Pintu', imgui.ImVec2(-1, 0)) then if Core.troll_isValidId(id) then Core.troll_unlockDoors(id) else sampAddChatMessage("[Troll] ID tidak valid.", 0xFF0000) end end
                imgui.Spacing()
                if imgui.Button(faicons("ARROW_DOWN") .. u8' Kubur Mobil ', imgui.ImVec2(-1, 0)) then Core.troll_buryPlayerCar(state.runtime.troll_car_id_input[0]) end
            end

            imgui.Separator()
            imgui.Text(faicons("SKULL") ..  " Player Crash")
            if imgui.Checkbox(faicons("BOLT") .. " Player Crash (Onfoot)", state.runtime.crasher_active) then end
            imgui.Separator()

            imgui.Text(faicons("FEATHER") .. " AirBrake (Fly Hack)")
            if imgui.Checkbox(faicons("POWER_OFF") .. " Aktifkan AirBrake", cheats.airBrake) then
                state.ini.cheat_settings.airBrake = cheats.airBrake[0]
                if not cheats.airBrake[0] then printStringNow('~r~AirBrake OFF', 1000) else printStringNow('~g~AirBrake ON', 1000) end
            end

            if cheats.airBrake[0] then
                if imgui.SliderFloat(faicons("GAUGE_HIGH") .. " Kecepatan AirBrake", cheats.airBrakeSpeed, 0.1, 3.5, "%.2f") then
                    state.ini.cheat_settings.airBrakeSpeed = cheats.airBrakeSpeed[0]
                end
                imgui.TextWrapped(faicons("GAMEPAD") .. " Gunakan analog untuk bergerak, tombol +/- untuk naik/turun.")
            end
            
            imgui.Separator()
            imgui.Text(faicons("HAND") .. " Car Slap Attach")
            if imgui.Checkbox(faicons("POWER_OFF") .. " Aktifkan Fitur Car Slap", state.runtime.cslap_main_enabled) then
                if not state.runtime.cslap_main_enabled[0] then state.runtime.cslap_pzdc_active[0] = false end
            end

            if state.runtime.cslap_main_enabled[0] then
                imgui.PushItemWidth(150)
                imgui.InputInt(faicons("USER") .. " Target Player ID", state.runtime.cslap_target_id)
                imgui.PopItemWidth()
                
                local targetId = state.runtime.cslap_target_id[0]
                local button_text = state.runtime.cslap_pzdc_active[0] and (faicons("TOGGLE_OFF") .. " Nonaktifkan Slap pada ID " .. targetId) or (faicons("TOGGLE_ON") .. " Aktifkan Slap pada ID " .. targetId)
                
                local r,g,b
                if state.runtime.cslap_pzdc_active[0] then r,g,b = 0.8, 0.2, 0.2 else r,g,b = 0.2, 0.7, 0.2 end
                
                imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(r, g, b, 1.0))
                imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(r+0.1, g+0.1, b+0.1, 1.0))
                imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(r-0.1, g-0.1, b-0.1, 1.0))

                if imgui.Button(button_text, imgui.ImVec2(-1, 30)) then
                    state.runtime.cslap_pzdc_active[0] = not state.runtime.cslap_pzdc_active[0]
                    if state.runtime.cslap_pzdc_active[0] then
                        if sampIsPlayerConnected(targetId) then 
                            sampAddChatMessage("[Car Slap] Diaktifkan! Menempel pada ID " .. targetId, 0x00FF00)
                        else 
                            sampAddChatMessage("[Car Slap] Peringatan: Target ID " .. targetId .. " tidak online!", 0xFFFF00) 
                        end
                    else
                        sampAddChatMessage("[Car Slap] Dinonaktifkan.", 0xFF0000)
                    end
                end
                imgui.PopStyleColor(3)
                imgui.TextWrapped(faicons("INFO") .. " Mobilmu akan menempel pada target yang sedang aktif.")
            end
            
            imgui.Separator()
            imgui.Text(faicons("ROCKET") .. " Rvanka Fly Hack (Onfoot God Mode)")
            if imgui.Checkbox(faicons("POWER_OFF") .. " Aktifkan Rvanka", state.runtime.rvanka_active) then 
                local msg = state.runtime.rvanka_active[0] and "[Rvanka] Diaktifkan!" or "[Rvanka] Dinonaktifkan."
                local color = state.runtime.rvanka_active[0] and 0x00FF00 or 0xFF0000
                sampAddChatMessage(msg, color) 
            end
            if state.runtime.rvanka_active[0] then
                imgui.PushItemWidth(-1)
                imgui.SliderFloat(faicons("GAUGE_HIGH") .. " Kecepatan Terbang", state.runtime.rvanka_speed, 1.0, 50.0, "%.0f")
                imgui.PopItemWidth()
                imgui.TextWrapped(faicons("INFO") .. " Arahkan kamera untuk bergerak. Memblokir banyak event server untuk kekebalan.")
            end

            imgui.Separator()
            imgui.Text(faicons("GUN") .. " Weapon Spawner")
            imgui.Checkbox("Tampilkan Spawner Senjata", state.weapon_manager.show_window)
        
        -- Credits
        elseif gui_state.active_menu_item[0] == 7 then
            imgui.Text(faicons("CIRCLE_INFO") .. " Developer Info & Credits")
            imgui.TextWrapped("• Developer : ZUPHPROJECT")
            imgui.TextWrapped("• YouTube : !!")
            if imgui.Button(faicons("VIDEO") .. " Open YouTube") then
                Core.openLink("https://youtube.com/@zuphprojects?si=bUKMVyApeZQysvLz")
            end
            imgui.TextWrapped("• Whatsapp : !! ")
            if imgui.Button(faicons("PHONE") .. " Open Whatsapp") then
                Core.openLink("https://whatsapp.com/channel/0029Vb5sHiz1nozBoZ6OGf0K")
            end
        end
        
        imgui.EndChild() -- End ContentScroll
        imgui.EndChild() -- End RightPanel
        
        imgui.Separator()
        if imgui.Button(faicons("FLOPPY_DISK") .. " Simpan Semua Pengaturan", imgui.ImVec2(-1, 35)) then
            inicfg.save(state.ini, state.ini_file)
            sampAddChatMessage("{00FF00}[ZuphProjects] Semua pengaturan telah disimpan!", 0xFFFFFF)
        end
    end

    imgui.End() -- End main window
end

function GUI.render_weapon_manager_window(state)
    local sw, sh = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(400, 480), imgui.Cond.FirstUseEver)

    local wm_state = state.weapon_manager
    local Core = require 'lib.Zuph.core'

    if imgui.Begin("Weapon Manager (Advanced)", wm_state.show_window, imgui.WindowFlags.NoCollapse) then
        imgui.Text("Bypass Settings")
        imgui.Separator()

        if imgui.Checkbox(faicons('SYNC') .. " Resync Bypass", wm_state.resync_bypass) then
            wm_state.WEAPON_BYPASS_STATE = wm_state.resync_bypass[0]
            wm_state.WEAPON_BYPASS_PACKET = 0
        end
        if imgui.IsItemHovered() then imgui.SetTooltip("Aktifkan bypass packet & damage spoof.") end

        imgui.Spacing()
        imgui.Text("Weapon Spawner")
        imgui.Separator()

        imgui.Text("Select a Weapon:")
        imgui.BeginChild("weapon_list", imgui.ImVec2(0, 180), true)
        for i, weapon in ipairs(Core.get_weapon_list()) do
            local is_selected = (wm_state.selected_weapon_idx[0] == i - 1)
            if imgui.Selectable(weapon.name, is_selected) then
                wm_state.selected_weapon_idx[0] = i - 1
            end
        end
        imgui.EndChild()

        imgui.Spacing()
        imgui.Text("Ammo Count:")
        imgui.PushItemWidth(-1)
        imgui.InputInt("##ammo", wm_state.ammo)
        imgui.PopItemWidth()

        imgui.Spacing()
        if imgui.Button(faicons('GUN') .. " Give Selected Weapon", imgui.ImVec2(-1, 0)) then Core.give_selected_weapon(state) end
        if imgui.Button(faicons('TRASH') .. " Remove All Weapons", imgui.ImVec2(-1, 0)) then removeAllCharWeapons(PLAYER_PED) end

        imgui.End()
    end
end

function GUI.render_translator_log(state)
    local u8 = require('encoding').UTF8
    local runtime = state.runtime

    imgui.SetNextWindowSize(imgui.ImVec2(450, 250), imgui.Cond.FirstUseEver)
    imgui.Begin("Log Terjemahan", runtime.show_translator_log)
    
    imgui.Checkbox("Tampilkan Hanya Terjemahan", runtime.log_show_only_translated)
    imgui.Separator()
    
    imgui.BeginChild("LogScrollingRegion", imgui.ImVec2(0, 0), false, imgui.WindowFlags.HorizontalScrollbar)
    for _, log_entry in ipairs(runtime.translator_log) do
        if runtime.log_show_only_translated[0] then
            imgui.PushStyleColor(imgui.Col.Text, imgui.ImVec4(0.6, 0.8, 1.0, 1.0))
            imgui.TextWrapped(u8("[T]: " .. log_entry.translated))
            imgui.PopStyleColor()
        else
            imgui.TextWrapped(u8(log_entry.original))
            imgui.PushStyleColor(imgui.Col.Text, imgui.ImVec4(0.6, 0.8, 1.0, 1.0))
            imgui.TextWrapped(u8("[T]: " .. log_entry.translated))
            imgui.PopStyleColor()
        end
        imgui.Separator()
    end
    
    if imgui.GetScrollY() >= imgui.GetScrollMaxY() then
        imgui.SetScrollHereY(1.0)
    end
    
    imgui.EndChild()
    imgui.End()
end

function GUI.render_autodrive_status(state)
    local u8 = require('encoding').UTF8
    local ap = state.ap

    local sw, sh = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sw - 160, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(240, 110), imgui.Cond.FirstUseEver)
    imgui.Begin(u8"Status Autopilot", ap.active.status_window, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoMove)
    
    if isCharInAnyCar(PLAYER_PED) then
        local car = storeCarCharIsInNoSave(PLAYER_PED)
        imgui.Text(u8(string.format("Kecepatan: %.0f", getCarSpeed(car))))
        imgui.Text(u8(string.format("Jarak: %.0f m", ap.status.target_dist)))
        imgui.Text(u8(string.format("Mode: %s", ap.status.mode)))
    end
    
    imgui.Separator()
    imgui.Text(u8("Mengemudi ke tujuan..."))
    
    imgui.End()
end

function GUI.render_fov(state)
    local aimhack = state.aimhack
    local drawList = imgui.GetBackgroundDrawList()
    local screenX, screenY = getScreenResolution()

    local crossX, crossY = screenX * 0.5, screenY * 0.425
    local radius = (screenX / 3) * (aimhack.maxFOV[0] / 2.5)
    
    drawList:AddCircleFilled(imgui.ImVec2(crossX, crossY), radius, 0x88000000, 64)
    drawList:AddCircle(imgui.ImVec2(crossX, crossY), radius, 0x8800AFFF, 64, 2.0)
end

return GUI