# Italian SuperLega Volleyball Standings Handler
# Uses Chromium headless to render JavaScript and extract standings
# Usage: processDocument( volleyball_standings, output.txt );

sub volleyball_standings
{
    my $ignored = shift;  # URL content is ignored - we fetch with chromium
    my @rValue = ();

    my $url = "https://www.legavolley.it/classifica/";

    # Use chromium to render the JS-heavy page
    my $html = `timeout 30 chromium --headless --no-sandbox --disable-gpu --dump-dom "$url" 2>/dev/null`;

    if (!$html || length($html) < 1000) {
        return @rValue;
    }

    # Extract rows with standings
    # Pattern: <span class="pos">N</span>&nbsp;&nbsp; Team Name ... <b>POINTS</b>
    my $rank = 0;

    while ($html =~ m{<span class="pos">(\d+)</span>\s*(?:&nbsp;)*\s*([^<]+?)\s*</td>.*?<b>\s*(\d+)\s*</b>}sig) {
        my $pos = $1;
        my $team = $2;
        my $pts = $3;

        # Clean up team name
        $team =~ s/^\s+|\s+$//g;
        $team =~ s/&nbsp;/ /g;

        # Skip if we already have this position (avoid duplicates)
        next if $pos <= $rank;
        $rank = $pos;

        push @rValue, {
            'rank' => $pos,
            'team' => $team,
            'stat' => $pts,
        };

        last if $rank >= 12;
    }

    return @rValue;
}

return 1;
