<?php 
function dacdb_areas($atts)
{
    // Enqueue the specific stylesheet needed for this shortcode.
    // This ensures it's loaded only when the shortcode is actually processed.
    wp_enqueue_style('dacdb-areas-style');

    global $fDebug, $data_path, $file_path, $options;
    $options = get_mmp_options();
    
    $output = '';

    $account_id = isset($atts['account']) ? $atts['account'] : $options['dacdb_district'];
    $club_id = $options['dacdb_club'];
    $thumbnail_width = isset($options['thumbnail_width']) && $options['thumbnail_width'] > 0 ? $options['thumbnail_width'] : (isset($atts['imgwidth']) && $atts['imgwidth'] > 0 ? $atts['imgwidth'] : 150);
    $rolekeys = isset($atts['rolekeys']) ? $atts['rolekeys'] : 'AG';
    $region = isset($atts['region']) ? $atts['region'] : '0';
    $style = (isset($atts['style']) && !empty($atts['style'])) ? $atts['style'] : '1';

    $debug_info = '';
    if ($fDebug && dacdb_is_admin()) {
        $debug_info = sprintf(
            '<div class="dacdb-debug-info"><strong>Debug Info:</strong><br>AccountID=%s<br>ClubID=%s<br>imgWidth=%s<br>RoleKeys=%s<br>Style=%s<br>Thumbnail Width=%s<br>URL=%s</div>',
            esc_html($account_id),
            esc_html($options['dacdb_club']),
            esc_html($thumbnail_width),
            esc_html($rolekeys),
            esc_html($style),
            esc_html($options['thumbnail_width']),
            esc_html($data_path . 'wp_areav2.cfm?AccountID=' . $account_id . '&rolekeys=' . $rolekeys . '&Region=' . $region)
        );
    }

    $api_url = $data_path . 'wp_areav2.cfm?AccountID=' . $account_id . '&rolekeys=' . $rolekeys . '&Region=' . $region . '&R=' . rand();
    $xml = simplexml_load_file($api_url);

    if (!$xml || count($xml->area) === 0) {
        $output .= $debug_info;
        $output .= '<p class="dacdb-areas__no-results">There are no areas/regions to display at this time.</p>';
        return $output;
    }

    // Add debug info if enabled
    $output .= $debug_info;

    // Add a container div with style-specific class
    $output .= sprintf('<div class="dacdb-areas-container dacdb-areas--style-%s">', esc_attr($style));

    $counter = 1;

    // Helper function to generate image HTML
    $generate_image_html = function($officer, $thumbnail_width) {
        $image_html = '';
        if (!empty($officer->image)) {
            $image_url = esc_url($officer->imgpath . $officer->image);
            // Set width attribute directly for potential AMP compatibility or non-CSS scenarios
            $image_html = sprintf(
                '<img src="%s" alt="%s" class="dacdb-area__officer-image" width="%d">',
                $image_url,
                esc_attr('Photo of ' . $officer->membername),
                intval($thumbnail_width) // Keep width attribute for specific sizing if needed
            );
        } else {
            $placeholder_url = MMPDB_PLUGIN_URL . 'img/avatar.svg';
            $image_html = sprintf(
                '<img src="%s" alt="Placeholder Avatar" class="dacdb-area__officer-image dacdb-area__officer-image--placeholder" width="%d">',
                 esc_url($placeholder_url),
                 intval($thumbnail_width) // Keep width attribute
            );
        }
        // Add style attribute for width here if needed, or rely solely on CSS
         $image_html = str_replace('>', sprintf(' style="width: %dpx;">', intval($thumbnail_width)), $image_html);
        return $image_html;
    };

    foreach ($xml->area as $area) {
        $area_label = esc_html($area->regionlabel) . ' ' . esc_html($area->area);
        $area_clubs_raw = isset($area->areaclubs) ? (string)$area->areaclubs : '';


        // --- Style 0 & 1: Linear List ---
        if ($style == '0' || $style == '1') {
             if (isset($area->officers) && count($area->officers->officer) > 0) {
                foreach ($area->officers->officer as $officer) {
                    $image_html = $generate_image_html($officer, $thumbnail_width);
                    $contact_url = esc_url($data_path . 'R_Emailer.cfm?UserID=' . intval($officer->userid));

                    $output .= '<div class="dacdb-area__officer dacdb-area__officer--linear">';
                    $output .= sprintf('<figure class="dacdb-area__officer-figure">%s</figure>', $image_html);
                    $output .= '<div class="dacdb-area__officer-details">';
                    $output .= sprintf('<strong>%s %s</strong><br>', esc_html($officer->areaposition), $area_label);
                    $output .= esc_html($officer->membername) . '<br>';
                    $output .= sprintf('<strong>Club:</strong> %s<br>', esc_html($officer->clubname));
                    $output .= sprintf('<strong>Area %s Clubs:</strong> %s<br>', esc_html($area->area), esc_html($area_clubs_raw));
                    $output .= sprintf(
                        '<a href="%s" name="dlc-inline-link-%d" class="modal-link dacdb-area__contact-link">Contact</a>',
                        $contact_url,
                        $counter++
                    );
                    $output .= '</div>'; // end officer-details
                    $output .= '</div>'; // end officer
                }
            }
        }
        // --- Style 2: Areas Grouped ---
        elseif ($style == '2') {
            $output .= sprintf('<section class="dacdb-area dacdb-area--grouped">');
            $output .= sprintf('<h3 class="dacdb-area__title">%s</h3>', $area_label);
            $output .= '<div class="dacdb-area__content">'; // Flex container for officer(s) and clubs

            // Officer(s) Section
            $output .= '<div class="dacdb-area__officers-column">';
            if (isset($area->officers) && count($area->officers->officer) > 0) {
                foreach ($area->officers->officer as $officer) {
                     $image_html = $generate_image_html($officer, $thumbnail_width);
                     $contact_url = esc_url($data_path . 'R_Emailer.cfm?UserID=' . intval($officer->userid));

                     $output .= '<div class="dacdb-area__officer">';
                     $output .= sprintf('<figure class="dacdb-area__officer-figure">%s</figure>', $image_html);
                     $output .= '<div class="dacdb-area__officer-details">';
                     $output .= sprintf('<strong>%s</strong><br>', esc_html($officer->areaposition));
                     $output .= esc_html($officer->membername) . '<br>';
                     $output .= sprintf('<strong>Club:</strong> %s<br>', esc_html($officer->clubname));
                     $output .= sprintf(
                         '<a href="%s" name="dlc-inline-link-%d" class="modal-link dacdb-area__contact-link">Contact</a>',
                         $contact_url,
                         $counter++
                     );
                     $output .= '</div>'; // end officer-details
                     $output .= '</div>'; // end officer
                }
            } else {
                 $output .= '<p>No officers assigned.</p>';
            }
            $output .= '</div>'; // end officers-column

            // Clubs Section
            $output .= '<div class="dacdb-area__clubs-column">';
            $output .= sprintf('<strong>Area %s Clubs:</strong><br>', esc_html($area->area));
            $output .= esc_html($area_clubs_raw);
            $output .= '</div>'; // end clubs-column

            $output .= '</div>'; // end area__content
            $output .= '</section>'; // end area
        }
         // --- Style 3: Areas Grouped with Club List ---
        elseif ($style == '3') {
             $output .= sprintf('<section class="dacdb-area dacdb-area--grouped-list">');
             $output .= sprintf('<h3 class="dacdb-area__title">%s</h3>', $area_label);
             $output .= '<div class="dacdb-area__content">'; // Flex container

             // Officer(s) Section
             $output .= '<div class="dacdb-area__officers-column">';
             if (isset($area->officers) && count($area->officers->officer) > 0) {
                 foreach ($area->officers->officer as $officer) {
                     $image_html = $generate_image_html($officer, $thumbnail_width);
                     $contact_url = esc_url($data_path . 'R_Emailer.cfm?UserID=' . intval($officer->userid));

                     $output .= '<div class="dacdb-area__officer">';
                     $output .= sprintf('<figure class="dacdb-area__officer-figure">%s</figure>', $image_html);
                     $output .= '<div class="dacdb-area__officer-details">';
                     $output .= sprintf('<strong>%s</strong><br>', esc_html($officer->areaposition));
                     $output .= esc_html($officer->membername) . '<br>';
                     $output .= sprintf('<strong>Club:</strong> %s<br>', esc_html($officer->clubname));
                     $output .= sprintf(
                         '<a href="%s" name="dlc-inline-link-%d" class="modal-link dacdb-area__contact-link">Contact</a>',
                         $contact_url,
                         $counter++
                     );
                     $output .= '</div>'; // end officer-details
                     $output .= '</div>'; // end officer
                 }
             } else {
                 $output .= '<p>No officers assigned.</p>';
             }
             $output .= '</div>'; // end officers-column

             // Clubs Section (List)
             $output .= '<div class="dacdb-area__clubs-column dacdb-area__clubs-column--list">';
             $output .= sprintf('<strong>Area %s Clubs:</strong><br>', esc_html($area->area));
             $clubs = !empty($area_clubs_raw) ? explode(', ', $area_clubs_raw) : [];
             if (!empty($clubs)) {
                 $output .= '<ul class="dacdb-area__club-list">';
                 foreach ($clubs as $club) {
                     $output .= sprintf('<li>%s</li>', esc_html(trim($club)));
                 }
                 $output .= '</ul>';
             } else {
                 $output .= '<p>No clubs listed for this area.</p>';
             }
             $output .= '</div>'; // end clubs-column

             $output .= '</div>'; // end area__content
             $output .= '</section>'; // end area
        }
    }

     // --- Invalid Style ---
    if (!in_array($style, ['0', '1', '2', '3'])) {
         $output .= sprintf('<div class="dacdb-error">Invalid style selected [%s]</div>', esc_html($style));
    }

    $output .= '</div>'; // end dacdb-areas-container

    return $output;
}
