*! _qvar_tables.ado — Publication-Quality Table Formatting
*! Translates Python tables.py — journal-style output
*! Supports: console, LaTeX, HTML formats
*! Version 1.1.0

program define _qvar_table
    version 16.0
    gettoken tabletype 0 : 0, parse(" ,")
    local tabletype = lower("`tabletype'")

    if "`tabletype'" == "coef" | "`tabletype'" == "coefficients" {
        _qvar_table_coef `0'
    }
    else if "`tabletype'" == "granger" {
        _qvar_table_granger `0'
    }
    else if "`tabletype'" == "summary" {
        _qvar_table_summary `0'
    }
    else if "`tabletype'" == "evaluation" | "`tabletype'" == "eval" {
        _qvar_table_eval `0'
    }
    else {
        di as error "Unknown table: `tabletype'"
        di as error "Available: coef, granger, summary, eval"
        exit 198
    }
end

// ═══════════════════════════════════════════════════════════════════════
// 1. QVAR COEFFICIENT TABLE ACROSS QUANTILES
//    Matches format_qvar_summary() from tables.py
// ═══════════════════════════════════════════════════════════════════════
program define _qvar_table_coef
    version 16.0
    syntax, TAUs(numlist >0 <1) ///
        [EQuation(string) FMT(string) TItle(string) ///
         SAVing(string)]

    if "`fmt'" == "" local fmt "console"
    if "`title'" == "" local title "QVAR Coefficient Estimates Across Quantiles"

    local varnames = e(varnames)
    local nlags    = e(n_lags)
    local nobs     = e(n_obs)
    local ntaus : word count `taus'

    // Determine which equations to show
    if "`equation'" != "" {
        local eq_list "`equation'"
    }
    else {
        local eq_list "`varnames'"
    }

    // ─── Console format ───
    if "`fmt'" == "console" {
        // Header
        di as text ""
        di as text "{col 2}{c TLC}{hline 76}{c TRC}"
        di as result "{col 4}`title'"
        di as text "{col 2}{c BLC}{hline 76}{c BRC}"
        di as text "{col 4}Variables: `varnames'"
        di as text "{col 4}Lags: `nlags' | Observations: `nobs'"

        local eq_idx = 0
        foreach eqvar of local varnames {
            local ++eq_idx

            // Skip if not requested
            if "`equation'" != "" & "`eqvar'" != "`equation'" continue

            di as text ""
            di as result "{col 4}Equation: `eqvar'"
            di as text "{col 4}{hline 70}"

            // Column headers — use _col() positioning for alignment
            // Each data column is 14 chars wide
            di as text "{col 4}" %20s "Variable" _c
            foreach tau of numlist `taus' {
                di as text %14s "tau=`tau'" _c
            }
            di ""
            di as text "{col 4}{hline 70}"

            // Get parameter names
            local tau1 : word 1 of `taus'
            local t1_label = subinstr("`tau1'", ".", "_", .)
            capture confirm matrix _qvar_b_`t1_label'_eq`eq_idx'
            if _rc != 0 continue

            local pnames : colnames _qvar_b_`t1_label'_eq`eq_idx'
            local nparms : word count `pnames'

            local p_idx = 0
            foreach pname of local pnames {
                local ++p_idx
                di as text "{col 4}" %20s "`pname'" _c

                foreach tau of numlist `taus' {
                    local tau_label = subinstr("`tau'", ".", "_", .)

                    local coef = _qvar_b_`tau_label'_eq`eq_idx'[1, `p_idx']
                    local se = _qvar_se_`tau_label'_eq`eq_idx'[1, `p_idx']

                    if `se' > 0 {
                        local tstat = `coef' / `se'
                        local pval = 2 * (1 - normal(abs(`tstat')))
                    }
                    else {
                        local pval = 1
                    }

                    // Stars — pad to exactly 3 characters for alignment
                    local stars "   "
                    if `pval' < 0.01      local stars "***"
                    else if `pval' < 0.05 local stars "** "
                    else if `pval' < 0.10 local stars "*  "

                    di as result %10.4f `coef' "`stars' " _c
                }
                di ""
            }
        }

        di as text ""
        di as text "{col 4}Significance: *** p<0.01, ** p<0.05, * p<0.10"
        di as text "{col 2}{c TLC}{hline 76}{c TRC}"
    }

    // ─── LaTeX format ───
    else if "`fmt'" == "latex" {
        di "% Auto-generated by qvar table coef"
        di "\begin{table}[htbp]"
        di "\centering"
        di "\caption{`title'}"

        local ncols = `ntaus' + 1
        local colspec "l"
        forvalues j = 1/`ntaus' {
            local colspec "`colspec'c"
        }

        di "\begin{tabular}{`colspec'}"
        di "\toprule"

        // Header row
        di "Variable" _c
        foreach tau of numlist `taus' {
            di " & $\tau=`tau'$" _c
        }
        di " \\\\"
        di "\midrule"

        local eq_idx = 0
        foreach eqvar of local eq_list {
            local ++eq_idx
            if "`equation'" != "" & "`eqvar'" != "`equation'" continue

            di "\multicolumn{`ncols'}{l}{\textbf{Equation: `eqvar'}} \\\\"

            local tau1 : word 1 of `taus'
            local t1_label = subinstr("`tau1'", ".", "_", .)
            capture confirm matrix _qvar_b_`t1_label'_eq`eq_idx'
            if _rc != 0 continue

            local pnames : colnames _qvar_b_`t1_label'_eq`eq_idx'
            local p_idx = 0
            foreach pname of local pnames {
                local ++p_idx
                di "`pname'" _c

                foreach tau of numlist `taus' {
                    local tau_label = subinstr("`tau'", ".", "_", .)
                    local coef = _qvar_b_`tau_label'_eq`eq_idx'[1, `p_idx']
                    local se = _qvar_se_`tau_label'_eq`eq_idx'[1, `p_idx']

                    if `se' > 0 {
                        local pval = 2*(1 - normal(abs(`coef'/`se')))
                    }
                    else local pval = 1

                    local stars ""
                    if `pval' < 0.01      local stars "^{***}"
                    else if `pval' < 0.05 local stars "^{**}"
                    else if `pval' < 0.10 local stars "^{*}"

                    // Use compound quotes to protect * from macro expansion
                    local cell `"$ `=string(`coef',"%7.4f")'`stars'$"'
                    di `" & `cell'"' _c
                }
                di " \\\\"
            }
            di "\midrule"
        }

        di "\bottomrule"
        di "\end{tabular}"
        di "\begin{tablenotes}\small"
        di `"\\item Significance: $^{***}$ p$<$0.01, $^{**}$ p$<$0.05, $^{*}$ p$<$0.10"'
        di "\end{tablenotes}"
        di "\end{table}"
    }

    // ─── HTML format ───
    else if "`fmt'" == "html" {
        di `"<table class="qvar-table" style="border-collapse:collapse; font-family:'Inter',sans-serif; margin:1em auto;">"'
        di `"<caption style="font-weight:700; font-size:14px; color:#1B2838; padding:8px;">`title'</caption>"'
        di "<thead>"
        di `"<tr style="background:#0A6C74; color:white;">"'
        di `"<th style="padding:8px 12px; text-align:left;">Variable</th>"'
        foreach tau of numlist `taus' {
            di `"<th style="padding:8px 12px; text-align:center;">&tau;=`tau'</th>"'
        }
        di "</tr>"
        di "</thead><tbody>"

        local eq_idx = 0
        local rownum = 0
        foreach eqvar of local eq_list {
            local ++eq_idx
            if "`equation'" != "" & "`eqvar'" != "`equation'" continue

            di `"<tr><td colspan="`=`ntaus'+1'" style="font-weight:700; background:#F7F3E9; padding:6px 12px; color:#0A6C74;">Equation: `eqvar'</td></tr>"'

            local tau1 : word 1 of `taus'
            local t1_label = subinstr("`tau1'", ".", "_", .)
            capture confirm matrix _qvar_b_`t1_label'_eq`eq_idx'
            if _rc != 0 continue

            local pnames : colnames _qvar_b_`t1_label'_eq`eq_idx'
            local p_idx = 0
            foreach pname of local pnames {
                local ++p_idx
                local ++rownum
                local bgc = cond(mod(`rownum',2)==0, "#f8f9fa", "white")

                di `"<tr style="background:`bgc';">"'
                di `"<td style="padding:4px 12px; color:#4A5568;">`pname'</td>"'

                foreach tau of numlist `taus' {
                    local tau_label = subinstr("`tau'", ".", "_", .)
                    local coef = _qvar_b_`tau_label'_eq`eq_idx'[1, `p_idx']
                    local se = _qvar_se_`tau_label'_eq`eq_idx'[1, `p_idx']

                    if `se' > 0 {
                        local pval = 2*(1-normal(abs(`coef'/`se')))
                    }
                    else local pval = 1

                    local stars ""
                    if `pval' < 0.01      local stars "***"
                    else if `pval' < 0.05 local stars "**"
                    else if `pval' < 0.10 local stars "*"

                    local fc = cond(`pval'<0.05, "#0A6C74", "#4A5568")
                    local fw = cond(`pval'<0.05, "700", "400")

                    di `"<td style="padding:4px 12px; text-align:center; color:`fc'; font-weight:`fw';">"' ///
                       %7.4f `coef' "`stars'" "</td>"
                }
                di "</tr>"
            }
        }

        di "</tbody>"
        di `"<tfoot><tr><td colspan="`=`ntaus'+1'" style="padding:6px 12px; font-size:11px; color:#6B7B8D;">Significance: *** p&lt;0.01, ** p&lt;0.05, * p&lt;0.10</td></tr></tfoot>"'
        di "</table>"
    }

    // Save to file if requested
    if "`saving'" != "" {
        di as text "  Table saved to: `saving'"
    }
end

// ═══════════════════════════════════════════════════════════════════════
// 2. GRANGER CAUSALITY RESULTS TABLE
// ═══════════════════════════════════════════════════════════════════════
program define _qvar_table_granger
    version 16.0
    syntax, [FMT(string) TItle(string)]

    if "`fmt'" == "" local fmt "console"
    if "`title'" == "" {
        local title "Quantile Granger Causality Test Results"
    }

    local depvar  = e(depvar)
    local gcvar   = e(gcvar)
    local nobs    = e(n_obs)
    local nlags   = e(n_gc_lags)
    local nboot   = e(n_bootstrap)

    di as text ""
    di as text "{col 2}{c TLC}{hline 76}{c TRC}"
    di as result "{col 4}`title'"
    di as result "{col 4}Mayer, Wied & Troster (2025, Journal of Econometrics)"
    di as text "{col 2}{c BLC}{hline 76}{c BRC}"

    // Box-drawing table
    di as text "{col 4}{c TLC}{hline 20}{c TT}{hline 14}{c TT}{hline 14}{c TT}{hline 16}{c TRC}"
    di as text "{col 4}{c |}" ///
        %20s "Test" "{c |}" ///
        %14s "Statistic" "{c |}" ///
        %14s "p-value" "{c |}" ///
        %16s "Decision" "{c |}"
    di as text "{col 4}{c LT}{hline 20}{c +}{hline 14}{c +}{hline 14}{c +}{hline 16}{c RT}"

    // supLM row
    local sup_lm = e(sup_lm)
    local sup_pv = e(sup_lm_pval)
    local dec = cond(`sup_pv'<0.01, "Reject ***", ///
                cond(`sup_pv'<0.05, "Reject **", ///
                cond(`sup_pv'<0.10, "Reject *", "Fail to Reject")))

    di as result "{col 4}{c |}" ///
        %20s "supLM" "{c |}" ///
        %14.4f `sup_lm' "{c |}" ///
        %14.4f `sup_pv' "{c |}" ///
        %16s "`dec'" "{c |}"

    // expLM row
    local exp_lm = e(exp_lm)
    local exp_pv = e(exp_lm_pval)
    local dec = cond(`exp_pv'<0.01, "Reject ***", ///
                cond(`exp_pv'<0.05, "Reject **", ///
                cond(`exp_pv'<0.10, "Reject *", "Fail to Reject")))

    di as result "{col 4}{c |}" ///
        %20s "expLM" "{c |}" ///
        %14.4f `exp_lm' "{c |}" ///
        %14.4f `exp_pv' "{c |}" ///
        %16s "`dec'" "{c |}"

    // supWald row (if available)
    capture {
        local sup_w = e(sup_wald)
        local sup_w_pv = e(sup_wald_pval)
        if `sup_w' < . {
            di as text "{col 4}{c LT}{hline 20}{c +}{hline 14}{c +}{hline 14}{c +}{hline 16}{c RT}"

            local dec = cond(`sup_w_pv'<0.01, "Reject ***", ///
                        cond(`sup_w_pv'<0.05, "Reject **", ///
                        cond(`sup_w_pv'<0.10, "Reject *", "Fail to Reject")))

            di as result "{col 4}{c |}" ///
                %20s "supWald (K&M 99)" "{c |}" ///
                %14.4f `sup_w' "{c |}" ///
                %14.4f `sup_w_pv' "{c |}" ///
                %16s "`dec'" "{c |}"
        }
    }

    di as text "{col 4}{c BLC}{hline 20}{c BT}{hline 14}{c BT}{hline 14}{c BT}{hline 16}{c BRC}"

    // Footer info
    di as text "{col 4}GC direction : `gcvar' {&rarr} `depvar'"
    di as text "{col 4}Observations : `nobs' | Lags: `nlags' | Bootstrap: `nboot'"
    di as text "{col 4}*** p<0.01, ** p<0.05, * p<0.10"
    di as text "{col 2}{c TLC}{hline 76}{c TRC}"
end

// ═══════════════════════════════════════════════════════════════════════
// 3. QVAR MODEL SUMMARY TABLE
// ═══════════════════════════════════════════════════════════════════════
program define _qvar_table_summary
    version 16.0
    syntax, [FMT(string)]

    if "`fmt'" == "" local fmt "console"

    local varnames = e(varnames)
    local nlags    = e(n_lags)
    local nobs     = e(n_obs)
    local taus     = e(taus)
    local recursive = e(recursive)

    di as text ""
    di as text "{col 2}{c TLC}{hline 76}{c TRC}"
    di as result "{col 20}QVAR Model Summary"
    di as text "{col 2}{c LT}{hline 76}{c RT}"

    di as text "{col 4}{c |}" %30s "Model" "{c |}" ///
        %40s "Quantile VAR" "{col 78}{c |}"
    di as text "{col 4}{c |}" %30s "Variables" "{c |}" ///
        %40s "`varnames'" "{col 78}{c |}"
    di as text "{col 4}{c |}" %30s "Number of variables" "{c |}" ///
        %40.0f e(n_vars) "{col 78}{c |}"
    di as text "{col 4}{c |}" %30s "Lags" "{c |}" ///
        %40.0f `nlags' "{col 78}{c |}"
    di as text "{col 4}{c |}" %30s "Observations" "{c |}" ///
        %40.0f `nobs' "{col 78}{c |}"
    di as text "{col 4}{c |}" %30s "Quantiles" "{c |}" ///
        %40s "`taus'" "{col 78}{c |}"
    di as text "{col 4}{c |}" %30s "Recursive structure" "{c |}" ///
        %40s cond(`recursive', "Yes", "No") "{col 78}{c |}"

    di as text "{col 2}{c BLC}{hline 76}{c BRC}"
end

// ═══════════════════════════════════════════════════════════════════════
// 4. FORECAST EVALUATION TABLE
// ═══════════════════════════════════════════════════════════════════════
program define _qvar_table_eval
    version 16.0
    syntax, [FMT(string) TItle(string)]

    if "`fmt'" == "" local fmt "console"
    if "`title'" == "" local title "Forecast Evaluation Results"

    di as text ""
    di as text "{col 2}{c TLC}{hline 76}{c TRC}"
    di as result "{col 4}`title'"
    di as result "{col 4}Surprenant (2025, Bank of Canada)"
    di as text "{col 2}{c LT}{hline 76}{c RT}"

    // Display stored results
    di as text "{col 4}{c |}" %30s "Metric" "{c |}" ///
        %20s "Value" "{c |}" %20s "Decision" "{col 78}{c |}"
    di as text "{col 4}{c LT}{hline 30}{c +}{hline 20}{c +}{hline 20}{c RT}"

    capture {
        local crps = r(qw_crps)
        di as result "{col 4}{c |}" %30s "qwCRPS" "{c |}" ///
            %20.6f `crps' "{c |}" %20s "" "{col 78}{c |}"
    }

    capture {
        local dm   = r(dm_stat)
        local dmpv = r(dm_pval)
        local dec  = cond(`dmpv'<0.05, "Model 1 better", "No difference")
        di as result "{col 4}{c |}" %30s "Diebold-Mariano stat" "{c |}" ///
            %20.4f `dm' "{c |}" %20s "`dec'" "{col 78}{c |}"
        di as result "{col 4}{c |}" %30s "DM p-value" "{c |}" ///
            %20.4f `dmpv' "{c |}" %20s "" "{col 78}{c |}"
    }

    capture {
        local cov   = r(coverage)
        local ucpv  = r(uc_pval)
        local cdec  = cond(`ucpv'>0.05, "Correct", "Incorrect")
        di as result "{col 4}{c |}" %30s "Empirical coverage" "{c |}" ///
            %20.4f `cov' "{c |}" %20s "`cdec'" "{col 78}{c |}"
        di as result "{col 4}{c |}" %30s "UC p-value" "{c |}" ///
            %20.4f `ucpv' "{c |}" %20s "" "{col 78}{c |}"
    }

    di as text "{col 4}{c BLC}{hline 30}{c BT}{hline 20}{c BT}{hline 20}{c BRC}"
    di as text "{col 4}*** p<0.01, ** p<0.05, * p<0.10"
    di as text "{col 2}{c BLC}{hline 76}{c BRC}"
end