local _, WN = ...

local function ToggleRow(page, panel, x, y, width, key, labelKey)
    local row = CreateFrame("Button", nil, panel, "BackdropTemplate")
    row:SetPoint("TOPLEFT", x, y); row:SetSize(width, 26)
    WN.ApplyBackdrop(row, WN.colors.panel, WN.colors.borderSoft)
    row.label = WN:CreateText(row, 9, WN.colors.text, "LEFT"); row.label:SetPoint("LEFT", 8, 0); row.label:SetPoint("RIGHT", -52, 0)
    row.state = WN:CreateText(row, 9, WN.colors.accent, "RIGHT"); row.state:SetPoint("RIGHT", -8, 0); row.state:SetWidth(44)
    row.key = key; row.labelKey = labelKey
    row:SetScript("OnClick", function(self) WN:ToggleSetting(self.key) end)
    row:SetScript("OnEnter", function(self) self:SetBackdropColor(unpack(WN.colors.panelHover)) end)
    row:SetScript("OnLeave", function(self) self:SetBackdropColor(unpack(WN.colors.panel)) end)
    page.toggles[key] = row
    return row
end

local function Selector(panel, x, y, width, captionKey, onClick)
    local b = WN:CreateButton(panel, width, 32, "", onClick)
    b:SetPoint("TOPLEFT", x, y)
    b.caption = WN:CreateText(panel, 9, WN.colors.muted, "LEFT"); b.caption:SetPoint("BOTTOMLEFT", b, "TOPLEFT", 0, 3); b.captionKey = captionKey
    return b
end

function WN:CreateSettingsSection(parent)
    local page=CreateFrame("Frame",nil,parent); page:SetAllPoints(); self.sections.settings=page; self:CreateSectionHeader(page); page.toggles={}

    page.appearance=self:CreatePanel(page,self:T("THEME"),280,202); page.appearance:SetPoint("TOPLEFT",0,-48)
    page.language=Selector(page.appearance,10,-50,124,"LANGUAGE",function() WN:CycleLanguage() end)
    page.scale=Selector(page.appearance,146,-50,124,"UI_SCALE",function() WN:CycleScale() end)
    page.opacity=Selector(page.appearance,10,-112,124,"OPACITY",function() WN:CycleOpacity() end)
    page.theme=Selector(page.appearance,146,-112,124,"THEME",function() WN:CycleTheme() end)
    ToggleRow(page,page.appearance,10,-164,260,"showSearch","SHOW_SEARCH")

    page.behavior=self:CreatePanel(page,self:T("SETTINGS_SUB"),280,202); page.behavior:SetPoint("TOPLEFT",290,-48)
    local behavior={{"showTracker","SHOW_TRACKER"},{"lockTracker","LOCK_TRACKER"},{"lockWindow","LOCK_WINDOW"},{"showMinimap","SHOW_MINIMAP"},{"autoRefresh","AUTO_REFRESH"},{"smartNotifications","ENABLE_NOTIFICATIONS"}}
    for i,d in ipairs(behavior) do ToggleRow(page,page.behavior,10,-40-(i-1)*27,260,d[1],d[2]) end

    page.hud=self:CreatePanel(page,self:T("HUD_WIDGETS"),282,202); page.hud:SetPoint("TOPLEFT",580,-48)
    local hud={{"widgetPerformance","WIDGET_PERFORMANCE"},{"widgetCharacter","WIDGET_CHARACTER"},{"widgetCurrency","WIDGET_CURRENCY"},{"widgetWeekly","WIDGET_WEEKLY"},{"widgetBags","WIDGET_BAGS"}}
    for i,d in ipairs(hud) do ToggleRow(page,page.hud,10,-40-(i-1)*27,262,d[1],d[2]) end

    page.profile=self:CreatePanel(page,self:T("PROFILE"),280,218); page.profile:SetPoint("TOPLEFT",0,-260)
    page.export=self:CreateButton(page.profile,124,32,self:T("EXPORT_PROFILE"),function() WN:OpenProfileDialog("export") end); page.export:SetPoint("TOPLEFT",10,-44)
    page.import=self:CreateButton(page.profile,124,32,self:T("IMPORT_PROFILE"),function() WN:OpenProfileDialog("import") end); page.import:SetPoint("TOPLEFT",146,-44)
    ToggleRow(page,page.profile,10,-88,260,"showFavorites","SHOW_FAVORITES")
    ToggleRow(page,page.profile,10,-116,260,"autoSnapshot","AUTO_SNAPSHOT")
    ToggleRow(page,page.profile,10,-144,260,"notifyLogin","NOTIFY_LOGIN")
    page.profile.note=self:CreateText(page.profile,8,self.colors.faint,"LEFT"); page.profile.note:SetPoint("BOTTOMLEFT",10,10); page.profile.note:SetPoint("RIGHT",-10,0); page.profile.note:SetHeight(36)

    page.safety=self:CreatePanel(page,self:T("DIAGNOSTICS"),280,218); page.safety:SetPoint("TOPLEFT",290,-260)
    ToggleRow(page,page.safety,10,-40,260,"privateTooltips","PRIVATE_TOOLTIPS")
    ToggleRow(page,page.safety,10,-68,260,"checkEnchants","CHECK_ENCHANTS")
    ToggleRow(page,page.safety,10,-96,260,"enableIntegrations","ENABLE_INTEGRATIONS")
    ToggleRow(page,page.safety,10,-124,260,"safeMode","SAFE_MODE")
    page.safety.info=self:CreateText(page.safety,8,self.colors.faint,"LEFT"); page.safety.info:SetPoint("TOPLEFT",10,-160); page.safety.info:SetPoint("RIGHT",-10,0); page.safety.info:SetHeight(44)

    page.actions=self:CreatePanel(page,self:T("UI_EDITOR"),282,218); page.actions:SetPoint("TOPLEFT",580,-260)
    page.editor=self:CreateButton(page.actions,124,30,self:T("EDIT_MODE"),function() WN:ToggleEditorMode() end); page.editor:SetPoint("TOPLEFT",10,-44)
    page.reload=self:CreateButton(page.actions,124,30,self:T("RELOAD_UI"),function() if not (InCombatLockdown and InCombatLockdown()) and type(ReloadUI)=="function" then ReloadUI() end end); page.reload:SetPoint("TOPLEFT",146,-44)
    page.resetPositions=self:CreateButton(page.actions,124,30,self:T("RESET_POSITIONS"),function() WN:ResetPositions(); WN:ApplySettings() end); page.resetPositions:SetPoint("TOPLEFT",10,-82)
    page.resetHUD=self:CreateButton(page.actions,124,30,self:T("RESET_HUD"),function() WN:ResetHUDPositions() end); page.resetHUD:SetPoint("TOPLEFT",146,-82)
    page.clearLog=self:CreateButton(page.actions,124,30,self:T("CLEAR_LOG"),function() WN:ClearDiagnostics() end); page.clearLog:SetPoint("TOPLEFT",10,-120)
    page.resetAll=self:CreateButton(page.actions,124,30,self:T("RESET_SETTINGS"),function() WN:RequestResetSettings() end); page.resetAll:SetPoint("TOPLEFT",146,-120)
    page.log=self:CreateButton(page.actions,82,28,self:T("OPEN_LOG"),function() WN:OpenDiagnosticDialog() end); page.log:SetPoint("TOPLEFT",10,-158)
    page.actions.info=self:CreateText(page.actions,8,self.colors.faint,"LEFT"); page.actions.info:SetPoint("TOPLEFT",100,-158); page.actions.info:SetPoint("RIGHT",-10,0); page.actions.info:SetHeight(48)
end

function WN:ToggleSetting(key)
    if not self.db or not self.db.settings then return end
    if key=="safeMode" then self:SetSafeMode(not self.db.settings.safeMode); return end
    self.db.settings[key]=not self.db.settings[key]
    self:ApplySettings(); self:UpdateSettingsSection(); self:RefreshAll()
end

function WN:CycleLanguage()
    local current=self.db.settings.language or "auto"; local nextIndex=1
    for i,locale in ipairs(self.localeOrder) do if locale==current then nextIndex=i+1; break end end
    if nextIndex>#self.localeOrder then nextIndex=1 end
    self.db.settings.language=self.localeOrder[nextIndex]; self:ApplyLocale(); self:UpdateStaticTexts(); self:RefreshAll()
end

function WN:CycleScale()
    local values={80,90,100,110,120}; local current=self.db.settings.uiScale or 100; local nextValue=values[1]
    for i,value in ipairs(values) do if value==current then nextValue=values[(i%#values)+1]; break end end
    self.db.settings.uiScale=nextValue; self:ApplySettings(); self:UpdateSettingsSection()
end

function WN:CycleOpacity()
    local values={60,70,80,90,100}; local current=self.db.settings.opacity or 100; local nextValue=values[1]
    for i,value in ipairs(values) do if value==current then nextValue=values[(i%#values)+1]; break end end
    self.db.settings.opacity=nextValue; self:ApplySettings(); self:UpdateSettingsSection()
end

function WN:RequestResetSettings()
    local now=GetTime and GetTime() or 0
    if self.resetConfirmAt and now-self.resetConfirmAt<4 then self.resetConfirmAt=nil; self:ResetAllSettings()
    else
        self.resetConfirmAt=now
        if self.sections.settings and self.sections.settings.resetAll then self.sections.settings.resetAll.label:SetText(self:T("CHECK").."?") end
        C_Timer.After(4,function() if WN.resetConfirmAt then WN.resetConfirmAt=nil; if WN.sections.settings then WN.sections.settings.resetAll.label:SetText(WN:T("RESET_SETTINGS")) end end end)
    end
end

function WN:UpdateSettingsSection()
    local page=self.sections.settings; if not page or not self.db then return end
    page.headerTitle:SetText(self:T("SETTINGS_TITLE")); page.headerSub:SetText(self:T("SETTINGS_SUB"))
    page.appearance.title:SetText(self:T("THEME")); page.behavior.title:SetText(self:T("SETTINGS_SUB")); page.hud.title:SetText(self:T("HUD_WIDGETS")); page.profile.title:SetText(self:T("PROFILE")); page.safety.title:SetText(self:T("DIAGNOSTICS")); page.actions.title:SetText(self:T("UI_EDITOR"))
    page.language.label:SetText(self.localeNames[self.db.settings.language] or self.db.settings.language); page.scale.label:SetText((self.db.settings.uiScale or 100).."%"); page.opacity.label:SetText((self.db.settings.opacity or 100).."%"); page.theme.label:SetText(self:GetThemeName())
    for _,b in ipairs({page.language,page.scale,page.opacity,page.theme}) do b.caption:SetText(self:T(b.captionKey)) end
    for key,row in pairs(page.toggles) do row.label:SetText(self:T(row.labelKey)); row.state:SetText(self.db.settings[key] and self:T("ON") or self:T("OFF")); row.state:SetTextColor(unpack(self.db.settings[key] and self.colors.green or self.colors.muted)) end
    page.export.label:SetText(self:T("EXPORT_PROFILE")); page.import.label:SetText(self:T("IMPORT_PROFILE")); page.profile.note:SetText(self:T("PROFILE_RELOAD_NOTE")); page.safety.info:SetText(self:T("TAINT_GUARD_DESC")); page.editor.label:SetText(self:T("EDIT_MODE")..": "..self:T(self.editorMode and "ON" or "OFF")); page.reload.label:SetText(self:T("RELOAD_UI")); page.resetPositions.label:SetText(self:T("RESET_POSITIONS")); page.resetHUD.label:SetText(self:T("RESET_HUD")); page.clearLog.label:SetText(self:T("CLEAR_LOG")); page.resetAll.label:SetText(self:T("RESET_SETTINGS")); page.log.label:SetText(self:T("OPEN_LOG"))
    self:InitDiagnostics()
    local diagText=string.format("%s: %d   •   %s: %d",self:T("ERRORS"),#self.diagnostics.errors,self:T("BLOCKED_ACTIONS"),#self.diagnostics.blocked)
    local lastError=self.diagnostics.errors[#self.diagnostics.errors]
    if lastError then
        local clean=string.gsub(tostring(lastError.text or ""), "[\r\n]+", " ")
        if #clean>82 then clean=string.sub(clean,1,82).."…" end
        diagText=diagText.."\n"..tostring(lastError.time or "").."  "..tostring(lastError.module or "?")..": "..clean
    end
    page.actions.info:SetText(diagText)
end

function WN:UpdateStaticTexts()
    if not self.frame then return end
    local navKeys={overview="OVERVIEW",planner="PLANNER",character="CHARACTER",gear="GEAR",activities="ACTIVITIES",endgame="ENDGAME",alts="ALTS",collections="COLLECTIONS",tools="TOOLS",settings="SETTINGS"}
    for id,button in pairs(self.frame.nav.buttons) do button.label:SetText(self:T(navKeys[id] or id)) end
    for key,metric in pairs(self.frame.profile.metrics) do metric.label:SetText(self:T(key)) end
    if self.frame.top and self.frame.top.search and (self.frame.top.search:GetText()=="" or self.frame.top.search:GetText()=="Search section, tool or addon..." or self.frame.top.search:GetText()=="Bereich, Werkzeug oder Addon suchen...") then self.frame.top.search:SetText(self:T("SEARCH_HINT")) end
    local o=self.sections.overview
    if o then
        o.weekly.title:SetText(self:T("WEEKLY_PROGRESS")); o.upgrades.title:SetText(self:T("NEXT_UPGRADE")); o.currencies.title:SetText(self:T("CURRENCIES")); o.instances.title:SetText(self:T("INSTANCES")); o.professions.title:SetText(self:T("PROFESSIONS")); o.collection.title:SetText(self:T("COLLECTION")); o.quick.title:SetText(self:T("QUICK_ACCESS")); o.upgrades.note:SetText(self:T("UPGRADE_NOTE")); for key,row in pairs(o.weekly.rows) do if key~="REPUTATION" then row.label:SetText(self:T(key)) end end
        for _,b in ipairs(o.quick.buttons or {}) do if b.textKey then b.label:SetText((self:IsFavorite(b.action) and self.db.settings.showFavorites~=false and "★ " or "")..self:T(b.textKey)) end end
    end
    if self.tracker then self:UpdateTrackerStaticTexts() end
    if self.widgets then for id,w in pairs(self.widgets) do local d={performance="WIDGET_PERFORMANCE",character="WIDGET_CHARACTER",currency="WIDGET_CURRENCY",weekly="WIDGET_WEEKLY",bags="WIDGET_BAGS"}; w.title:SetText(self:T(d[id])) end end
    if self.minimapDashboard then self.minimapDashboard.title:SetText(self:T("MINIMAP_DASHBOARD")); for _,b in ipairs(self.minimapDashboard.buttons or {}) do b.label:SetText(self:T(b.textKey)) end end
    self:UpdateSettingsSection()
end
