EbonholdHub.BugReport = {}

EbonholdHub.BugReport.WEBSITE_URL = "https://ebonholdhub.vercel.app/report-bug"

local linkDialog

local function AddonVersion()
    return (GetAddOnMetadata and GetAddOnMetadata("EbonholdHub", "Version")) or "1.0.0"
end

local function ReportUrl()
    local base = EbonholdHub.BugReport.WEBSITE_URL or ""
    local version = AddonVersion()
    if version and version ~= "" then
        return base .. "?v=" .. version
    end
    return base
end

local function EnsureLinkDialog()
    if linkDialog then return end
    local UI = EbonholdHub.UI
    local C = UI.Colors

    local f = UI.CreateWindow("EbonholdHubBugReportLinkDialog", 520, 130, "Report a bug", {
        strata = "FULLSCREEN_DIALOG",
        toplevel = true,
    })
    local content = f.content

    local hint = UI.CreateLabel(content,
        "Sign in on the website to submit a bug report:",
        UI.FONT_SIZE_SMALL, C.textDim)
    hint:SetPoint("TOPLEFT", content, "TOPLEFT", 0, 0)
    f._hint = hint

    local editHolder = UI.CreateEditBox(content, 480, 28, false)
    editHolder:SetPoint("TOPLEFT", hint, "BOTTOMLEFT", 0, -8)
    local box = editHolder.editBox
    box:SetMaxLetters(256)
    box:SetScript("OnEscapePressed", function() f:Hide() end)

    local close = UI.CreateButton(content, 80, 26, "Close")
    close:SetPoint("BOTTOMRIGHT", content, "BOTTOMRIGHT", 0, 0)
    close:SetScript("OnClick", function() f:Hide() end)

    f._editBox = box
    linkDialog = f
end

local function PositionDialog(f)
    local main = EbonholdHub.MainWindow and EbonholdHub.MainWindow._frame
    if main and main:IsShown() then
        f:SetFrameStrata("FULLSCREEN_DIALOG")
        f:SetFrameLevel(main:GetFrameLevel() + 20)
        f:ClearAllPoints()
        f:SetPoint("CENTER", main, "CENTER", 0, 0)
    else
        f:ClearAllPoints()
        f:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
    end
end

function EbonholdHub.BugReport.OpenWebsite()
    EnsureLinkDialog()
    local url = ReportUrl()
    local opened = EbonholdHub.OpenExternalURL and EbonholdHub.OpenExternalURL(url)
    if linkDialog._hint then
        if opened then
            linkDialog._hint:SetText("Opened in your browser. Log in, then fill out the bug report form:")
        else
            linkDialog._hint:SetText("Sign in on the website to submit a bug report:")
        end
    end
    linkDialog._editBox:SetText(url)
    linkDialog._editBox:HighlightText()
    PositionDialog(linkDialog)
    linkDialog:Show()
    linkDialog._editBox:SetFocus()

    if not opened then
        EbonholdHub.Toast.Show("Copy the link and open it in your browser.")
    end
end
