EbonholdHub.WelcomeView = {}

local ST   = EbonholdHub.SiteTheme
local SW   = EbonholdHub.SiteWidgets
local C    = ST.C
local FLAT = ST.FLAT

local CONTENT_W = 640
local FOOTER_H  = 36

-- hero(86) + gap(10) + actWrap(144) + gap(10) + stepsPanel(74)
local WRAP_H = 324

local viewFrame
local statsLabel
local _stepsPanel

local ADDON_VERSION = GetAddOnMetadata and GetAddOnMetadata("EbonholdHub", "Version") or "1.9.0"

local QUICK_ACTIONS = {
    {
        title   = "New Build",
        desc    = "Start from scratch",
        icon    = "builds",
        variant = "accent",
        run = function()
            EbonholdHub.ViewRouter.Show("buildTabs", { mode = "create" })
        end,
    },
    {
        title   = "Quick Create",
        desc    = "From your character",
        icon    = "import",
        variant = "danger",
        run = function()
            if EbonholdHub.BuildList and EbonholdHub.BuildList.CreateFromCharacter then
                EbonholdHub.BuildList.CreateFromCharacter()
            end
        end,
    },
    {
        title   = "Catalog",
        desc    = "Community builds",
        icon    = "catalog",
        variant = "default",
        run = function()
            EbonholdHub.ViewRouter.Show("publicBuilds")
        end,
    },
    {
        title   = "Echo Map",
        desc    = "Drop locations",
        icon    = "media",
        variant = "default",
        run = function()
            EbonholdHub.ViewRouter.Show("echoMap")
        end,
    },
}

local STEPS = {
    "Create or import a build, then select it in the sidebar.",
    "Set echoes, affixes, and gear — Advisor can suggest tiers.",
    "Enable Auto Pick during runs.",
}

-- ─────────────────────────────────────────────────────────────────────────────
-- Action tile (2×2 grid card)
-- ─────────────────────────────────────────────────────────────────────────────
local DANGER_COLOR = { 0.9, 0.25, 0.25 }

local function TileColors(variant)
    if variant == "accent" then
        return C.accentBg10, C.accentBg18, C.accentBorder35, C.accentBorder55, C.accent
    elseif variant == "danger" then
        local bg   = ST.BlendRgb(DANGER_COLOR, ST.Base.bg, 0.10)
        local bghv = ST.BlendRgb(DANGER_COLOR, ST.Base.bg, 0.18)
        local bd   = ST.BlendRgb(DANGER_COLOR, ST.Base.border, 0.30)
        local bdhv = ST.BlendRgb(DANGER_COLOR, ST.Base.border, 0.55)
        local tc   = { 0.95, 0.50, 0.50, 1 }
        return bg, bghv, bd, bdhv, tc
    else
        return C.elementBg, C.bgElevated, C.border, C.borderHover, C.text
    end
end

local function CreateActionTile(parent, action, w, h)
    local bgNorm, bgHov, bdNorm, bdHov, textColor = TileColors(action.variant)
    local iconColor = action.variant == "default" and C.textDim or textColor

    local tile = CreateFrame("Button", nil, parent)
    tile:SetSize(w, h)

    local bg     = SW.Fill(tile, bgNorm)
    local border = SW.ThinBorder(tile, bdNorm)

    local ICON_SIZE = 18
    local PAD_L     = 16
    local TEXT_OFF  = PAD_L + ICON_SIZE + 10

    if action.icon and EbonholdHub.SiteIcons and EbonholdHub.SiteIcons.Exists(action.icon) then
        local ic = SW.CreateIcon(tile, action.icon, ICON_SIZE, iconColor)
        ic:SetPoint("LEFT", tile, "LEFT", PAD_L, 3)
        tile._icon = ic
    end

    local titleLbl = SW.Label(tile, action.title, 13, textColor, false, "semibold")
    titleLbl:SetPoint("TOPLEFT", tile, "TOPLEFT", TEXT_OFF, -12)
    titleLbl:SetJustifyH("LEFT")

    local descLbl = SW.Label(tile, action.desc, 10, C.textDim)
    descLbl:SetPoint("TOPLEFT", titleLbl, "BOTTOMLEFT", 0, -3)
    descLbl:SetJustifyH("LEFT")

    tile:SetScript("OnEnter", function()
        bg:SetVertexColor(unpack(bgHov))
        SW.SetBorderColor(border, bdHov)
        titleLbl:SetTextColor(unpack(action.variant == "default" and C.accent or textColor))
        if tile._icon then tile._icon:SetColor(action.variant == "default" and C.accent or textColor) end
    end)
    tile:SetScript("OnLeave", function()
        bg:SetVertexColor(unpack(bgNorm))
        SW.SetBorderColor(border, bdNorm)
        titleLbl:SetTextColor(unpack(textColor))
        if tile._icon then tile._icon:SetColor(iconColor) end
    end)
    tile:SetScript("OnClick", action.run)
    return tile
end

-- ─────────────────────────────────────────────────────────────────────────────
-- Stats / recent
-- ─────────────────────────────────────────────────────────────────────────────
local function FormatStats()
    local myCount = #(EbonholdHub.Build.List and EbonholdHub.Build.List() or {})
    local catCount = 0
    if EbonholdHub.Catalog and EbonholdHub.Catalog.List then
        catCount = #(EbonholdHub.Catalog.List())
    end
    return string.format("%d saved build%s  ·  %d in catalog",
        myCount, myCount == 1 and "" or "s", catCount)
end

local function RefreshContent()
    if statsLabel then statsLabel:SetText(FormatStats()) end
end

-- ─────────────────────────────────────────────────────────────────────────────
-- Footer
-- ─────────────────────────────────────────────────────────────────────────────
local function BuildFooter(parent)
    local footer = CreateFrame("Frame", nil, parent)
    footer:SetPoint("BOTTOMLEFT",  parent, "BOTTOMLEFT",  0, 0)
    footer:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", 0, 0)
    footer:SetHeight(FOOTER_H)
    SW.Fill(footer, C.navBg)

    local topLine = footer:CreateTexture(nil, "ARTWORK")
    topLine:SetTexture(FLAT)
    topLine:SetVertexColor(unpack(C.border))
    topLine:SetPoint("TOPLEFT",  footer, "TOPLEFT",  0, 0)
    topLine:SetPoint("TOPRIGHT", footer, "TOPRIGHT", 0, 0)
    topLine:SetHeight(1)

    local versionLbl = SW.Label(footer, "v" .. ADDON_VERSION, 10, C.textMuted)
    versionLbl:SetPoint("LEFT", footer, "LEFT", 16, 0)

    local bugBtn = SW.CreateNavActionButton(footer, {
        label   = "Report bug",
        icon    = "report",
        variant = "default",
        onClick = function()
            if EbonholdHub.BugReport and EbonholdHub.BugReport.OpenWebsite then
                EbonholdHub.BugReport.OpenWebsite()
            end
        end,
    })
    bugBtn:SetPoint("LEFT", versionLbl, "RIGHT", 12, 0)

    local siteBtn = SW.CreateNavActionButton(footer, {
        label   = "Download ready build",
        icon    = "download",
        variant = "accent",
        onClick = function()
            if EbonholdHub.Catalog and EbonholdHub.Catalog.ShowWebsiteLink then
                EbonholdHub.Catalog.ShowWebsiteLink()
            end
        end,
    })
    siteBtn:SetPoint("RIGHT", footer, "RIGHT", -16, 0)

    return footer
end

-- ─────────────────────────────────────────────────────────────────────────────
-- Main layout
-- ─────────────────────────────────────────────────────────────────────────────
local function BuildViewFrame(parent)
    local f = CreateFrame("Frame", nil, parent)

    BuildFooter(f)

    local body = CreateFrame("Frame", nil, f)
    body:SetPoint("TOPLEFT",     f, "TOPLEFT",     0,  0)
    body:SetPoint("TOPRIGHT",    f, "TOPRIGHT",    0,  0)
    body:SetPoint("BOTTOMLEFT",  f, "BOTTOMLEFT",  0,  FOOTER_H)
    body:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 0,  FOOTER_H)

    local wrap = CreateFrame("Frame", nil, body)
    wrap:SetSize(CONTENT_W, WRAP_H)
    wrap:SetPoint("CENTER", body, "CENTER", 0, 0)

    -- ── Hero ─────────────────────────────────────────────────────────────────
    local hero = CreateFrame("Frame", nil, wrap)
    hero:SetSize(CONTENT_W, 86)
    hero:SetPoint("TOP", wrap, "TOP", 0, 0)
    SW.Fill(hero, C.bgElevated)
    SW.ThinBorder(hero, C.border)

    -- accent left stripe (3 px)
    local stripe = hero:CreateTexture(nil, "OVERLAY")
    stripe:SetTexture(FLAT)
    stripe:SetVertexColor(unpack(C.accent))
    stripe:SetPoint("TOPLEFT",    hero, "TOPLEFT",    0, 0)
    stripe:SetPoint("BOTTOMLEFT", hero, "BOTTOMLEFT", 0, 0)
    stripe:SetWidth(3)

    -- subtle glow wash behind icon
    local glow = hero:CreateTexture(nil, "BACKGROUND")
    glow:SetTexture(FLAT)
    glow:SetVertexColor(unpack(C.accentBg10))
    glow:SetPoint("TOPLEFT",    hero, "TOPLEFT",    3, 0)
    glow:SetPoint("BOTTOMLEFT", hero, "BOTTOMLEFT", 3, 0)
    glow:SetWidth(90)

    local addonIcon = hero:CreateTexture(nil, "ARTWORK")
    addonIcon:SetSize(44, 44)
    addonIcon:SetPoint("LEFT", hero, "LEFT", 22, 0)
    addonIcon:SetTexture(EbonholdHub.UI and EbonholdHub.UI.AddonIcon)
    addonIcon:SetTexCoord(0, 1, 0, 1)

    local titleLbl = SW.Label(hero, "EbonholdHub", 17, C.text, false, "semibold")
    titleLbl:SetPoint("TOPLEFT", addonIcon, "TOPRIGHT", 14, 0)
    titleLbl:SetJustifyH("LEFT")

    local taglineLbl = SW.Label(hero, "Echo builds, affix loadouts & gear for Project Ebonhold", 11, C.textDim)
    taglineLbl:SetPoint("TOPLEFT", titleLbl, "BOTTOMLEFT", 0, -4)
    taglineLbl:SetWidth(420)
    taglineLbl:SetJustifyH("LEFT")

    statsLabel = SW.Label(hero, "", 10, C.accent)
    statsLabel:SetPoint("TOPLEFT", taglineLbl, "BOTTOMLEFT", 0, -4)
    statsLabel:SetJustifyH("LEFT")

    -- ── Quick actions 2×2 ────────────────────────────────────────────────────
    local TILE_GAP = 8
    local TILE_W   = math.floor((CONTENT_W - TILE_GAP) / 2)
    local TILE_H   = 58
    local ACT_PAD  = 10
    local actWrap  = CreateFrame("Frame", nil, wrap)
    actWrap:SetPoint("TOP", hero, "BOTTOM", 0, -10)
    actWrap:SetSize(CONTENT_W, ACT_PAD + TILE_H + TILE_GAP + TILE_H + ACT_PAD)

    for i, action in ipairs(QUICK_ACTIONS) do
        local col = (i % 2 == 1) and 0 or (TILE_W + TILE_GAP)
        local row = (i <= 2) and -ACT_PAD or -(ACT_PAD + TILE_H + TILE_GAP)
        local tile = CreateActionTile(actWrap, action, TILE_W, TILE_H)
        tile:SetPoint("TOPLEFT", actWrap, "TOPLEFT", col, row)
    end

    -- ── Getting started ───────────────────────────────────────────────────────
    _stepsPanel = CreateFrame("Frame", nil, wrap)
    _stepsPanel:SetPoint("TOP", actWrap, "BOTTOM", 0, -10)
    _stepsPanel:SetSize(CONTENT_W, 74)
    SW.Fill(_stepsPanel, C.bgElevated)
    SW.ThinBorder(_stepsPanel, C.border)

    local stepTitle = SW.Label(_stepsPanel, "GETTING STARTED", 9, C.textMuted, false, "medium")
    stepTitle:SetPoint("TOPLEFT", _stepsPanel, "TOPLEFT", 14, -9)

    local ROW_H = 16
    for i, text in ipairs(STEPS) do
        local y = -24 - (i - 1) * (ROW_H + 2)
        local num = SW.Label(_stepsPanel, tostring(i) .. ".", 11, C.accent, false, "semibold")
        num:SetPoint("TOPLEFT", _stepsPanel, "TOPLEFT", 14, y)
        num:SetWidth(14)
        num:SetJustifyH("RIGHT")

        local line = SW.Label(_stepsPanel, text, 11, C.textDim)
        line:SetPoint("TOPLEFT", _stepsPanel, "TOPLEFT", 32, y)
        line:SetWidth(CONTENT_W - 46)
        line:SetJustifyH("LEFT")
        line:SetWordWrap(false)
    end

    return f
end

-- ─────────────────────────────────────────────────────────────────────────────
-- Mount / lifecycle
-- ─────────────────────────────────────────────────────────────────────────────
local function EnsureBuilt(container)
    if viewFrame and viewFrame._welcomeV21 then return end
    if viewFrame then
        viewFrame:Hide()
        viewFrame:SetParent(nil)
        viewFrame = nil
    end
    viewFrame = BuildViewFrame(container)
    viewFrame._welcomeV21 = true
end

function EbonholdHub.WelcomeView.Mount(container)
    EnsureBuilt(container)
    viewFrame:SetParent(container)
    viewFrame:ClearAllPoints()
    viewFrame:SetAllPoints(container)
    RefreshContent()
    viewFrame:Show()
end

function EbonholdHub.WelcomeView.Unmount()
    if not viewFrame then return end
    viewFrame:Hide()
end

function EbonholdHub.WelcomeView.Refresh()
    RefreshContent()
end

function EbonholdHub.WelcomeView.Init()
end
