-- ============================================================================
-- Vamoose's Companion - Settings: Companion Tab
-- Model preview, companion info, model variant grid
-- ============================================================================

VC = VC or {}
-- Methods are added to VC.Settings (defined in VC_Settings.lua)

local WHITE = "Interface\\Buttons\\WHITE8x8"

-- ============================================================================
-- COMPANION PAGE (two-column: preview left, info right; grid below)
-- ============================================================================

function VC.Settings:BuildCompanionPage(parent, W, pageH)
    local c = VC.Theme:GetScheme()
    local TB = VC.Constants.SETTINGS.TAB_BAR_H

    local page = CreateFrame("Frame", nil, parent)
    page:SetPoint("TOPLEFT", 0, -TB)
    page:SetPoint("TOPRIGHT", 0, -TB)
    page:SetHeight(pageH)
    page:Hide()
    self.pages["companion"] = page

    local INSET = 16
    local LEFT_COL_W = 220
    local GAP = 16
    local RIGHT_COL_X = INSET + LEFT_COL_W + GAP

    -- =========================================================================
    -- Left column: 3D model preview (220x260)
    -- =========================================================================
    local preview = CreateFrame("Frame", nil, page, "BackdropTemplate")
    preview:SetSize(LEFT_COL_W, 260)
    preview:SetPoint("TOPLEFT", INSET, -INSET)
    preview:SetBackdrop(VC.Theme.BACKDROP_PANEL)
    preview:SetBackdropColor(c.bg.r, c.bg.g, c.bg.b, 1)
    preview:SetBackdropBorderColor(c.border.r, c.border.g, c.border.b, 1)
    self.previewFrame = preview

    -- Mood ring: 4px bar at top of preview
    local moodRingBar = preview:CreateTexture(nil, "OVERLAY")
    moodRingBar:SetSize(LEFT_COL_W - 4, 4)
    moodRingBar:SetPoint("TOPLEFT", 2, -2)
    moodRingBar:SetTexture(WHITE)
    moodRingBar:SetVertexColor(0.6, 0.6, 0.6, 0.8)
    self.previewMoodRing = moodRingBar

    -- ModelScene inside preview
    local previewScene = VC.UI:CreateModelScene(preview)
    previewScene:SetPoint("TOPLEFT", 5, -5)
    previewScene:SetSize(LEFT_COL_W - 10, 250)
    previewScene:SetFrameLevel(preview:GetFrameLevel() + 1)
    self.previewScene = previewScene
    VC.Theme:Register(preview, "Frame")

    -- Companion name (below preview)
    local nameLabel = page:CreateFontString(nil, "OVERLAY")
    nameLabel:SetPoint("TOPLEFT", INSET, -(INSET + 260 + 8))
    nameLabel:SetWidth(LEFT_COL_W)
    nameLabel:SetJustifyH("CENTER")
    nameLabel:SetFont("Fonts\\MORPHEUS.ttf", 13, "")
    nameLabel:SetTextColor(c.text_header.r, c.text_header.g, c.text_header.b, 1)
    nameLabel:SetShadowOffset(1, -1); nameLabel:SetShadowColor(0, 0, 0, 1)
    self.companionNameLabel = nameLabel

    -- Title label (below name)
    local titleLabel = page:CreateFontString(nil, "OVERLAY")
    titleLabel:SetPoint("TOPLEFT", nameLabel, "BOTTOMLEFT", 0, -3)
    titleLabel:SetWidth(LEFT_COL_W)
    titleLabel:SetJustifyH("CENTER")
    titleLabel:SetFont("Fonts\\ARIALN.TTF", 10, "")
    titleLabel:SetTextColor(c.text_dim.r, c.text_dim.g, c.text_dim.b, 1)
    self.companionTitleLabel = titleLabel

    -- =========================================================================
    -- Right column: Companion info (bond, mood, description)
    -- =========================================================================
    local RIGHT_COL_W = W - RIGHT_COL_X - INSET

    -- Description (1-2 lines)
    local descLabel = page:CreateFontString(nil, "OVERLAY")
    descLabel:SetPoint("TOPLEFT", RIGHT_COL_X, -INSET)
    descLabel:SetWidth(RIGHT_COL_W)
    descLabel:SetJustifyH("LEFT")
    descLabel:SetFont("Fonts\\ARIALN.TTF", 11, "")
    descLabel:SetTextColor(c.text_dim.r, c.text_dim.g, c.text_dim.b, 1)
    descLabel:SetWordWrap(true)
    descLabel:SetMaxLines(2)
    self.companionDescLabel = descLabel

    -- Bond label
    local bondLabel = page:CreateFontString(nil, "OVERLAY")
    bondLabel:SetPoint("TOPLEFT", RIGHT_COL_X, -(INSET + 44))
    bondLabel:SetFont("Fonts\\ARIALN.TTF", 10, "")
    bondLabel:SetText("Bond:")
    bondLabel:SetTextColor(c.text_dim.r, c.text_dim.g, c.text_dim.b, 1)

    -- Bond progress bar
    local BOND_BAR_W = 160
    local bondBarBg = page:CreateTexture(nil, "ARTWORK")
    bondBarBg:SetSize(BOND_BAR_W, 10)
    bondBarBg:SetPoint("LEFT", bondLabel, "RIGHT", 6, 0)
    bondBarBg:SetTexture(WHITE)
    bondBarBg:SetVertexColor(c.bg.r, c.bg.g, c.bg.b, 1)

    local bondBarFill = page:CreateTexture(nil, "OVERLAY")
    bondBarFill:SetSize(1, 10)
    bondBarFill:SetPoint("LEFT", bondBarBg, "LEFT", 0, 0)
    bondBarFill:SetTexture(WHITE)
    bondBarFill:SetVertexColor(0.302, 0.788, 0.965, 0.8)
    self.bondBarFill = bondBarFill
    self.bondBarW = BOND_BAR_W

    local bondValueLabel = page:CreateFontString(nil, "OVERLAY")
    bondValueLabel:SetPoint("LEFT", bondBarBg, "RIGHT", 6, 0)
    bondValueLabel:SetFont("Fonts\\ARIALN.TTF", 10, "")
    bondValueLabel:SetTextColor(0.302, 0.788, 0.965, 1)
    self.bondValueLabel = bondValueLabel

    -- Mood indicator
    local moodDot = page:CreateTexture(nil, "OVERLAY")
    moodDot:SetSize(8, 8)
    moodDot:SetPoint("TOPLEFT", RIGHT_COL_X + 34, -(INSET + 62))
    moodDot:SetTexture(WHITE)
    moodDot:SetVertexColor(0.6, 0.6, 0.6, 1)
    self.moodDot = moodDot

    local moodLabel = page:CreateFontString(nil, "OVERLAY")
    moodLabel:SetPoint("TOPLEFT", RIGHT_COL_X, -(INSET + 58))
    moodLabel:SetFont("Fonts\\ARIALN.TTF", 10, "")
    moodLabel:SetText("Mood:")
    moodLabel:SetTextColor(c.text_dim.r, c.text_dim.g, c.text_dim.b, 1)

    local moodStateLabel = page:CreateFontString(nil, "OVERLAY")
    moodStateLabel:SetPoint("LEFT", moodDot, "RIGHT", 4, 0)
    moodStateLabel:SetFont("Fonts\\ARIALN.TTF", 10, "")
    moodStateLabel:SetTextColor(0.6, 0.6, 0.6, 1)
    self.moodStateLabel = moodStateLabel

    -- =========================================================================
    -- Model variant grid (full-width below both columns)
    -- =========================================================================
    local GRID_SEP_Y = -310
    local gridSep = page:CreateTexture(nil, "ARTWORK")
    gridSep:SetHeight(1)
    gridSep:SetPoint("TOPLEFT", 0, GRID_SEP_Y)
    gridSep:SetPoint("TOPRIGHT", 0, GRID_SEP_Y)
    gridSep:SetTexture(WHITE)
    gridSep:SetVertexColor(c.border.r, c.border.g, c.border.b, 0.4)

    local modelLabel = page:CreateFontString(nil, "OVERLAY")
    modelLabel:SetPoint("TOPLEFT", INSET, GRID_SEP_Y - 12)
    modelLabel:SetFont("Fonts\\ARIALN.TTF", 9, "")
    modelLabel:SetText("MODEL VARIANTS")
    modelLabel:SetTextColor(c.text_dim.r, c.text_dim.g, c.text_dim.b, 1)
    self._modelLabel = modelLabel

    local CARD_SIZE = 64
    local CARD_PAD = 5
    local COLS = math.floor((W - INSET * 2) / (CARD_SIZE + CARD_PAD))

    local modelScroll = CreateFrame("ScrollFrame", nil, page, "UIPanelScrollFrameTemplate")
    modelScroll:SetPoint("TOPLEFT", INSET, GRID_SEP_Y - 28)
    modelScroll:SetPoint("BOTTOMRIGHT", -INSET, 4)
    local modelContent = CreateFrame("Frame", nil, modelScroll)
    modelContent:SetWidth(W - INSET * 2 - 20)
    modelContent:SetHeight(1)
    modelScroll:SetScrollChild(modelContent)
    modelScroll:EnableMouseWheel(true)
    modelScroll:SetScript("OnMouseWheel", function(self, delta)
        local cur = self:GetVerticalScroll()
        local maxS = math.max(0, modelContent:GetHeight() - self:GetHeight())
        self:SetVerticalScroll(math.max(0, math.min(maxS, cur - delta * 40)))
    end)
    VC.UI.StyleScrollBar(modelScroll)

    self._modelScroll = modelScroll
    self._modelContent = modelContent
    self._modelCards = {}
    self._CARD_SIZE = CARD_SIZE
    self._CARD_PAD = CARD_PAD
    self._CARD_COLS = COLS
end

-- ============================================================================
-- REFRESH COMPANION PAGE
-- ============================================================================

function VC.Settings:RefreshCompanionPage(companionKey)
    local c = VC.Theme:GetScheme()
    local profile = VC_CompanionProfiles and VC_CompanionProfiles[companionKey]
    if not profile then return end

    -- Preview model
    if self.previewScene then
        local state = VC.Store:GetState()
        local override = state.config.modelOverrides and state.config.modelOverrides[companionKey]
        local displayID = override or profile.displayID or 19598
        VC.UI:SetCreatureOnScene(self.previewScene, displayID, { scale = 0.8 })
    end

    -- Preview mood ring
    if self.previewMoodRing and VC.Mood then
        local mood = VC.Mood:GetMood()
        local mc = VC.Constants.MOOD_COLORS[mood] or VC.Constants.MOOD_COLORS.NEUTRAL
        self.previewMoodRing:SetVertexColor(mc.r, mc.g, mc.b, 0.8)
    end

    -- Update preview frame border to companion themeColor
    if self.previewFrame and profile.themeColor then
        local tc = profile.themeColor
        self.previewFrame:SetBackdropBorderColor(tc.r, tc.g, tc.b, 0.7)
    end

    -- Name + title + description
    if self.companionNameLabel then self.companionNameLabel:SetText(profile.name) end
    if self.companionTitleLabel then self.companionTitleLabel:SetText(profile.title or "") end
    if self.companionDescLabel then self.companionDescLabel:SetText(profile.description or "") end

    -- Bond bar
    if self.bondBarFill and VC.Bonding then
        local info = VC.Bonding:GetLevelInfo(companionKey)
        if info then
            local pct = 0
            if info.nextThreshold and info.nextThreshold > 0 then
                local levels = VC.Constants.BONDING.LEVELS
                local prevThresh = 0
                for _, lvl in ipairs(levels) do
                    if lvl.name == info.name then break end
                    prevThresh = lvl.threshold
                end
                local span = info.nextThreshold - prevThresh
                if span > 0 then pct = math.max(0, math.min(1, (info.rapport - prevThresh) / span)) end
            else
                pct = 1
            end
            local fillW = math.max(1, math.floor((self.bondBarW or 160) * pct))
            self.bondBarFill:SetWidth(fillW)
            local next = info.nextThreshold and tostring(info.nextThreshold) or "Max"
            if self.bondValueLabel then
                self.bondValueLabel:SetText(info.name .. " " .. info.rapport .. "/" .. next)
            end
        end
    end

    -- Mood dot + state name
    if self.moodDot and VC.Mood then
        local mood = VC.Mood:GetMood()
        local mc = VC.Constants.MOOD_COLORS[mood] or VC.Constants.MOOD_COLORS.NEUTRAL
        self.moodDot:SetVertexColor(mc.r, mc.g, mc.b, 1)
        if self.moodStateLabel then
            self.moodStateLabel:SetText(mood:sub(1,1) .. mood:sub(2):lower())
            self.moodStateLabel:SetTextColor(mc.r, mc.g, mc.b, 1)
        end
    end

    -- Model variant grid (only rebuild when companion changes)
    if self._lastGridKey ~= companionKey then
        self:RefreshModelGrid(companionKey)
        self._lastGridKey = companionKey
    end
end

-- ============================================================================
-- MODEL GRID REFRESH
-- ============================================================================

function VC.Settings:RefreshModelGrid(companionKey, highlightOnly)
    local content = self._modelContent
    if not content then return end
    local c = VC.Theme:GetScheme()
    local profile = VC_CompanionProfiles and VC_CompanionProfiles[companionKey]
    local models = profile and profile.models

    if not highlightOnly then
        for _, card in ipairs(self._modelCards or {}) do
            card:Hide()
        end
    end

    if not models or #models == 0 then
        if self._modelLabel then self._modelLabel:SetText("MODEL VARIANTS") end
        content:SetHeight(1)
        return
    end

    if not highlightOnly and self._modelLabel then
        self._modelLabel:SetText("MODEL VARIANTS (" .. #models .. ")")
    end

    local state = VC.Store:GetState()
    local currentOverride = state.config.modelOverrides[companionKey]
    local activeDisplayID = currentOverride or profile.displayID

    local CARD_SIZE = self._CARD_SIZE
    local PAD = self._CARD_PAD
    local COLS = self._CARD_COLS

    for i, displayID in ipairs(models) do
        local card = self._modelCards[i]

        if not highlightOnly then
            if not card then
                card = CreateFrame("Frame", nil, content, "BackdropTemplate")
                card:SetSize(CARD_SIZE, CARD_SIZE)
                card:SetBackdrop(VC.Theme.BACKDROP_INSET)
                card:EnableMouse(true)

                local cardScene = VC.UI:CreateModelScene(card)
                cardScene:SetPoint("TOPLEFT", 2, -2)
                cardScene:SetPoint("BOTTOMRIGHT", -2, 2)
                cardScene:EnableMouse(false)  -- pass clicks through to card
                card._scene = cardScene

                self._modelCards[i] = card
            end

            local col = (i - 1) % COLS
            local row = math.floor((i - 1) / COLS)
            card:ClearAllPoints()
            card:SetPoint("TOPLEFT", col * (CARD_SIZE + PAD), -(row * (CARD_SIZE + PAD)))

            VC.UI:SetCreatureOnScene(card._scene, displayID, { scale = 0.9 })

            local did = displayID
            local cKey = companionKey
            card:SetScript("OnMouseDown", function()
                if InCombatLockdown() then return end
                VC.Store:Dispatch("SET_MODEL_OVERRIDE", { companionKey = cKey, displayID = did })
                if VC.Portrait and VC.Portrait.UpdateModel then VC.Portrait:UpdateModel() end
                if self.previewScene then
                    VC.UI:SetCreatureOnScene(self.previewScene, did, { scale = 0.8 })
                end
                self:RefreshModelGrid(cKey, true)
            end)

            card:Show()
        end

        -- Always update highlight
        if card then
            if displayID == activeDisplayID then
                card:SetBackdropColor(c.accent.r, c.accent.g, c.accent.b, 0.2)
                card:SetBackdropBorderColor(c.accent.r, c.accent.g, c.accent.b, 1)
            else
                card:SetBackdropColor(c.panel.r, c.panel.g, c.panel.b, 1)
                card:SetBackdropBorderColor(c.border.r, c.border.g, c.border.b, 1)
            end
        end
    end

    local totalRows = math.ceil(#models / COLS)
    content:SetHeight(totalRows * (CARD_SIZE + PAD) + PAD)
end
