#!/bin/bash

###############################################################################
# Frontend Accessibility (a11y) Audit Script
#
# WCAG 2.1 Level AA compliance testing for Global Gala frontend applications
# Tests: Color contrast, keyboard navigation, ARIA attributes, screen reader
#        compatibility, form accessibility, focus management
#
# Usage: ./scripts/frontend-a11y-audit.sh
###############################################################################

set -eo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Counters
PASS=0
FAIL=0
WARN=0
VIOLATIONS=0

# Configuration
TICKETING_URL="http://localhost:3002"
ADMIN_URL="http://localhost:3001"
FRONTEND_PATH="/Users/charlie/code/showprima-frontend"

# Check if apps are running
check_app_running() {
    local URL=$1
    local NAME=$2

    if curl -s -o /dev/null -w "%{http_code}" "$URL" | grep -q "200"; then
        return 0
    else
        echo -e "${YELLOW}[WARN]${NC} $NAME not running at $URL"
        echo "      Start with: cd $FRONTEND_PATH && npm run dev"
        return 1
    fi
}

# Logging
info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

pass() {
    echo -e "${GREEN}[PASS]${NC} $1"
    ((PASS++))
}

fail() {
    echo -e "${RED}[FAIL]${NC} $1"
    ((FAIL++))
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
    ((WARN++))
}

header() {
    echo ""
    echo -e "${BLUE}===================================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}===================================================${NC}"
    echo ""
}

###############################################################################
# Prerequisite Checks
###############################################################################

header "Accessibility Audit - Prerequisites"

info "Checking if frontend apps are running..."

TICKETING_RUNNING=false
ADMIN_RUNNING=false

if check_app_running "$TICKETING_URL" "Ticketing App"; then
    TICKETING_RUNNING=true
    pass "Ticketing app is running at $TICKETING_URL"
fi

if check_app_running "$ADMIN_URL" "Admin App"; then
    ADMIN_RUNNING=true
    pass "Admin app is running at $ADMIN_URL"
fi

if [ "$TICKETING_RUNNING" = false ] && [ "$ADMIN_RUNNING" = false ]; then
    echo ""
    echo -e "${RED}ERROR: No frontend apps are running${NC}"
    echo "Start apps with: cd $FRONTEND_PATH && npm run dev"
    exit 1
fi

# Check for Node.js and npm
if ! command -v node &> /dev/null; then
    fail "Node.js not installed"
    exit 1
else
    pass "Node.js installed: $(node --version)"
fi

# Check for axe-core (optional, will install if needed)
info "Checking for axe-core CLI..."
if ! command -v axe &> /dev/null; then
    warn "axe-core CLI not installed (will use alternative methods)"
else
    pass "axe-core CLI available"
fi

###############################################################################
# 1. HTML Semantic Structure
###############################################################################

header "1. HTML Semantic Structure & Landmarks"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Analyzing HTML structure of ticketing app..."

    # Fetch page HTML
    HTML=$(curl -s "$TICKETING_URL/booking/1")

    # Check for semantic HTML5 elements
    if echo "$HTML" | grep -q "<main"; then
        pass "Main landmark present"
    else
        fail "Missing <main> landmark - required for screen readers"
    fi

    if echo "$HTML" | grep -q "<nav"; then
        pass "Navigation landmark present"
    else
        warn "Missing <nav> landmark"
    fi

    if echo "$HTML" | grep -q "<header"; then
        pass "Header landmark present"
    else
        warn "Missing <header> landmark"
    fi

    if echo "$HTML" | grep -q "<footer"; then
        pass "Footer landmark present"
    else
        warn "Missing <footer> landmark"
    fi

    # Check for skip navigation link
    if echo "$HTML" | grep -qi "skip to content\|skip navigation"; then
        pass "Skip navigation link present"
    else
        fail "Missing skip navigation link - required for keyboard users"
    fi
fi

###############################################################################
# 2. Page Title & Language
###############################################################################

header "2. Page Title & Language Attributes"

if [ "$TICKETING_RUNNING" = true ]; then
    # Check for page title
    TITLE=$(echo "$HTML" | grep -o "<title>[^<]*</title>" || echo "")

    if [ -n "$TITLE" ]; then
        pass "Page title present: $TITLE"
    else
        fail "Missing page <title> element"
    fi

    # Check for lang attribute
    if echo "$HTML" | grep -q 'html lang='; then
        LANG=$(echo "$HTML" | grep -o 'html lang="[^"]*"' || echo "unknown")
        pass "Language attribute present: $LANG"
    else
        fail "Missing lang attribute on <html> element"
    fi
fi

###############################################################################
# 3. Form Accessibility
###############################################################################

header "3. Form Accessibility & Labels"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking form element accessibility..."

    # Check for input labels
    INPUT_COUNT=$(echo "$HTML" | grep -o "<input" | wc -l)
    LABEL_COUNT=$(echo "$HTML" | grep -o "<label" | wc -l)

    info "Found $INPUT_COUNT input fields and $LABEL_COUNT labels"

    if [ "$INPUT_COUNT" -gt 0 ]; then
        if [ "$LABEL_COUNT" -ge "$INPUT_COUNT" ]; then
            pass "Sufficient labels for input fields"
        else
            fail "Missing labels - found $LABEL_COUNT labels for $INPUT_COUNT inputs"
        fi
    fi

    # Check for aria-label or aria-labelledby on inputs without labels
    ARIA_LABELS=$(echo "$HTML" | grep -c "aria-label\|aria-labelledby" || echo "0")
    if [ "$ARIA_LABELS" -gt 0 ]; then
        pass "ARIA labels present for some inputs"
    fi

    # Check for fieldset/legend in forms
    if echo "$HTML" | grep -q "<fieldset"; then
        pass "Fieldset elements used for grouping form controls"
    else
        info "No fieldsets found (ok if forms are simple)"
    fi
fi

###############################################################################
# 4. Image Accessibility
###############################################################################

header "4. Image Alt Text & Accessibility"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Analyzing image accessibility..."

    # Count images
    IMG_COUNT=$(echo "$HTML" | grep -o "<img" | wc -l)

    if [ "$IMG_COUNT" -eq 0 ]; then
        info "No images found on page"
    else
        info "Found $IMG_COUNT images"

        # Check for alt attributes
        ALT_COUNT=$(echo "$HTML" | grep -c '<img[^>]*alt=' || echo "0")

        if [ "$ALT_COUNT" -eq "$IMG_COUNT" ]; then
            pass "All images have alt attributes"
        else
            MISSING_ALT=$((IMG_COUNT - ALT_COUNT))
            fail "$MISSING_ALT images missing alt attributes"
        fi

        # Check for empty alt on decorative images
        EMPTY_ALT=$(echo "$HTML" | grep -c 'alt=""' || echo "0")
        if [ "$EMPTY_ALT" -gt 0 ]; then
            info "$EMPTY_ALT images with empty alt (ok if decorative)"
        fi
    fi
fi

###############################################################################
# 5. Button & Link Accessibility
###############################################################################

header "5. Button & Link Accessibility"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking interactive elements..."

    # Check for buttons with accessible text
    BUTTON_COUNT=$(echo "$HTML" | grep -o "<button" | wc -l)
    info "Found $BUTTON_COUNT button elements"

    # Check for links with descriptive text
    LINK_COUNT=$(echo "$HTML" | grep -o "<a " | wc -l)
    info "Found $LINK_COUNT link elements"

    # Check for "click here" or "read more" (bad practices)
    if echo "$HTML" | grep -qi "click here\|click this\|read more"; then
        warn "Found generic link text like 'click here' - use descriptive text"
    else
        pass "No generic link text detected"
    fi

    # Check for disabled buttons with proper ARIA
    DISABLED_BUTTONS=$(echo "$HTML" | grep -c 'disabled\|aria-disabled' || echo "0")
    if [ "$DISABLED_BUTTONS" -gt 0 ]; then
        info "$DISABLED_BUTTONS disabled buttons found (ensure aria-disabled is set)"
    fi
fi

###############################################################################
# 6. ARIA Attributes
###############################################################################

header "6. ARIA Attributes & Roles"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Validating ARIA implementation..."

    # Check for ARIA roles
    ARIA_ROLES=$(echo "$HTML" | grep -c 'role=' || echo "0")
    if [ "$ARIA_ROLES" -gt 0 ]; then
        pass "ARIA roles present: $ARIA_ROLES occurrences"
    else
        warn "No ARIA roles found (may not be needed if using semantic HTML)"
    fi

    # Check for ARIA labels
    ARIA_LABELS=$(echo "$HTML" | grep -c 'aria-label=' || echo "0")
    if [ "$ARIA_LABELS" -gt 0 ]; then
        pass "ARIA labels present: $ARIA_LABELS occurrences"
    fi

    # Check for ARIA live regions (for dynamic content)
    if echo "$HTML" | grep -q 'aria-live'; then
        pass "ARIA live regions implemented (good for dynamic updates)"
    else
        info "No ARIA live regions (implement for real-time seat updates)"
    fi

    # Check for aria-hidden misuse
    ARIA_HIDDEN=$(echo "$HTML" | grep -c 'aria-hidden="true"' || echo "0")
    if [ "$ARIA_HIDDEN" -gt 5 ]; then
        warn "Excessive aria-hidden usage ($ARIA_HIDDEN) - ensure important content isn't hidden"
    fi
fi

###############################################################################
# 7. Heading Hierarchy
###############################################################################

header "7. Heading Structure & Hierarchy"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Analyzing heading structure..."

    H1_COUNT=$(echo "$HTML" | grep -o "<h1" | wc -l)
    H2_COUNT=$(echo "$HTML" | grep -o "<h2" | wc -l)
    H3_COUNT=$(echo "$HTML" | grep -o "<h3" | wc -l)

    info "Heading counts: H1=$H1_COUNT, H2=$H2_COUNT, H3=$H3_COUNT"

    if [ "$H1_COUNT" -eq 1 ]; then
        pass "Exactly one H1 heading (best practice)"
    elif [ "$H1_COUNT" -eq 0 ]; then
        fail "Missing H1 heading - required for page structure"
    else
        warn "Multiple H1 headings ($H1_COUNT) - should have only one per page"
    fi

    # Check if H2s exist before H3s (proper hierarchy)
    if [ "$H3_COUNT" -gt 0 ] && [ "$H2_COUNT" -eq 0 ]; then
        fail "H3 headings without H2 - breaks heading hierarchy"
    else
        if [ "$H2_COUNT" -gt 0 ]; then
            pass "Proper heading hierarchy present"
        fi
    fi
fi

###############################################################################
# 8. Keyboard Navigation
###############################################################################

header "8. Keyboard Navigation Support"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking keyboard accessibility features..."

    # Check for focus indicators (CSS)
    if echo "$HTML" | grep -qi "focus\|outline"; then
        pass "Focus styles likely implemented (verify visually)"
    else
        warn "No focus styles detected - ensure focus indicators are visible"
    fi

    # Check for tabindex usage
    TABINDEX_COUNT=$(echo "$HTML" | grep -c 'tabindex=' || echo "0")
    if [ "$TABINDEX_COUNT" -gt 0 ]; then
        info "tabindex attribute used: $TABINDEX_COUNT times"

        # Check for tabindex > 0 (bad practice)
        POSITIVE_TABINDEX=$(echo "$HTML" | grep -c 'tabindex="[1-9]' || echo "0")
        if [ "$POSITIVE_TABINDEX" -gt 0 ]; then
            warn "Positive tabindex values ($POSITIVE_TABINDEX) - avoid using tabindex > 0"
        else
            pass "No positive tabindex values (good practice)"
        fi
    fi

    # Check for access keys
    if echo "$HTML" | grep -q 'accesskey='; then
        info "Access keys implemented for keyboard shortcuts"
    fi
fi

###############################################################################
# 9. Color Contrast (Basic Check)
###############################################################################

header "9. Color Contrast & Visual Accessibility"

info "Checking for color-only indicators..."

if [ "$TICKETING_RUNNING" = true ]; then
    # This is a basic check - full contrast testing requires visual analysis
    info "Note: Full color contrast testing requires manual verification"
    info "Required: 4.5:1 for normal text, 3:1 for large text (WCAG AA)"

    # Check for red/green only indicators (common accessibility issue)
    warn "Manually verify seat colors are not red/green only (colorblind users)"
    warn "Ensure seat status uses icons/patterns in addition to color"

    pass "Automated color checks complete (manual verification recommended)"
fi

###############################################################################
# 10. Responsive Text & Zoom
###############################################################################

header "10. Responsive Text & Zoom Support"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking viewport and zoom configuration..."

    # Check for viewport meta tag
    if echo "$HTML" | grep -q '<meta name="viewport"'; then
        VIEWPORT=$(echo "$HTML" | grep -o '<meta name="viewport"[^>]*>' || echo "")

        # Check if user-scalable is disabled (bad!)
        if echo "$VIEWPORT" | grep -qi "user-scalable=no"; then
            fail "Viewport prevents zooming (user-scalable=no) - accessibility violation"
        else
            pass "Viewport allows user zooming"
        fi

        # Check maximum-scale
        if echo "$VIEWPORT" | grep -qi "maximum-scale=1"; then
            warn "Viewport restricts zoom to 1x - users may need to zoom"
        fi
    else
        fail "Missing viewport meta tag"
    fi

    # Check for relative font sizes (rem/em vs px)
    info "Recommend using rem/em for font sizes (better for zoom/accessibility)"
fi

###############################################################################
# 11. Error Handling & Feedback
###############################################################################

header "11. Error Messages & User Feedback"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking for accessible error handling..."

    # Check for aria-live for error announcements
    if echo "$HTML" | grep -q 'role="alert"\|aria-live="assertive"'; then
        pass "ARIA alert regions implemented for error announcements"
    else
        warn "No ARIA alert regions - screen readers may miss error messages"
    fi

    # Check for aria-invalid on form fields
    if echo "$HTML" | grep -q 'aria-invalid'; then
        pass "aria-invalid attribute used for form validation"
    else
        info "aria-invalid not detected (implement for form error states)"
    fi

    # Check for aria-describedby for error messages
    if echo "$HTML" | grep -q 'aria-describedby'; then
        pass "aria-describedby used to associate errors with fields"
    else
        warn "Missing aria-describedby - link error messages to form fields"
    fi
fi

###############################################################################
# 12. Dynamic Content Updates
###############################################################################

header "12. Dynamic Content & Live Regions"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking for accessible dynamic content updates..."

    # Check for aria-live regions
    if echo "$HTML" | grep -q 'aria-live="polite"\|aria-live="assertive"'; then
        pass "ARIA live regions present for dynamic updates"
    else
        fail "Missing ARIA live regions - seat availability changes won't be announced"
    fi

    # Check for aria-atomic
    if echo "$HTML" | grep -q 'aria-atomic'; then
        pass "aria-atomic attribute used for complete message announcements"
    fi

    # Check for loading states
    if echo "$HTML" | grep -qi 'loading\|spinner\|aria-busy'; then
        pass "Loading state indicators present"
    else
        warn "Missing loading state indicators (use aria-busy during API calls)"
    fi
fi

###############################################################################
# 13. SVG & Canvas Accessibility
###############################################################################

header "13. SVG & Canvas Accessibility"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking venue canvas accessibility..."

    # Check for canvas element (venue visualization)
    if echo "$HTML" | grep -q "<canvas"; then
        info "Canvas element detected (venue visualization)"

        # Check for accessible fallback
        if echo "$HTML" | grep -A5 "<canvas" | grep -q "aria-label\|role"; then
            pass "Canvas has ARIA attributes for accessibility"
        else
            fail "Canvas missing accessibility attributes - add aria-label and role"
        fi

        warn "Ensure keyboard navigation is available for seat selection (not mouse-only)"
    fi

    # Check for SVG accessibility
    SVG_COUNT=$(echo "$HTML" | grep -c "<svg" || echo "0")
    if [ "$SVG_COUNT" -gt 0 ]; then
        info "Found $SVG_COUNT SVG elements"

        # Check for title/desc in SVGs
        if echo "$HTML" | grep -A10 "<svg" | grep -q "<title>\|<desc>"; then
            pass "SVG elements have title/description tags"
        else
            warn "SVG elements missing <title> and <desc> tags for screen readers"
        fi
    fi
fi

###############################################################################
# 14. Tables (if any)
###############################################################################

header "14. Table Accessibility"

if [ "$TICKETING_RUNNING" = true ]; then
    TABLE_COUNT=$(echo "$HTML" | grep -c "<table" || echo "0")

    if [ "$TABLE_COUNT" -gt 0 ]; then
        info "Found $TABLE_COUNT table elements"

        # Check for table headers
        if echo "$HTML" | grep -q "<th"; then
            pass "Table headers (<th>) present"
        else
            warn "Tables missing header cells - use <th> for column/row headers"
        fi

        # Check for table captions
        if echo "$HTML" | grep -q "<caption"; then
            pass "Table captions present for context"
        else
            warn "Tables missing <caption> elements - add for screen reader context"
        fi

        # Check for scope attributes
        if echo "$HTML" | grep -q 'scope="col"\|scope="row"'; then
            pass "Table headers use scope attributes"
        else
            warn "Table headers missing scope attributes (col/row)"
        fi
    else
        info "No data tables found"
    fi
fi

###############################################################################
# 15. Time-Based Content
###############################################################################

header "15. Time-Based Content & Animations"

if [ "$TICKETING_RUNNING" = true ]; then
    info "Checking for time-sensitive content..."

    # Check for countdown timers (hold expiration)
    if echo "$HTML" | grep -qi "countdown\|timer\|expires"; then
        warn "Time-based content detected - ensure users can:"
        echo "      1. Disable time limits (accessibility requirement)"
        echo "      2. Extend time limits before expiration"
        echo "      3. Be warned before time expires"
    fi

    # Check for auto-play media
    if echo "$HTML" | grep -qi "autoplay"; then
        fail "Autoplay detected - violates WCAG (users must control media)"
    fi

    # Check for prefers-reduced-motion
    info "Implement prefers-reduced-motion media query for users with motion sensitivity"
fi

###############################################################################
# Summary
###############################################################################

header "Accessibility Audit Summary"

echo ""
echo -e "${GREEN}Passed:${NC}      $PASS tests"
echo -e "${YELLOW}Warnings:${NC}    $WARN tests"
echo -e "${RED}Failed:${NC}      $FAIL tests"
echo ""

# Calculate score
TOTAL=$((PASS + WARN + FAIL))
if [ $TOTAL -eq 0 ]; then
    SCORE=0
else
    SCORE=$(( (PASS * 100) / TOTAL ))
fi

echo "Accessibility Score: $SCORE/100"

# Grade based on WCAG compliance
if [ $FAIL -eq 0 ] && [ $WARN -eq 0 ]; then
    echo -e "${GREEN}WCAG 2.1 Level AA: PASS${NC}"
    EXIT_CODE=0
elif [ $FAIL -eq 0 ]; then
    echo -e "${YELLOW}WCAG 2.1 Level AA: PASS (with warnings)${NC}"
    EXIT_CODE=0
elif [ $FAIL -le 3 ]; then
    echo -e "${YELLOW}WCAG 2.1 Level AA: PARTIAL (minor issues)${NC}"
    EXIT_CODE=1
else
    echo -e "${RED}WCAG 2.1 Level AA: FAIL (major issues)${NC}"
    EXIT_CODE=1
fi

echo ""
echo "Critical Accessibility Recommendations:"
echo "========================================"

if [ $FAIL -gt 0 ]; then
    echo "⚠️  Fix failed tests before production deployment"
fi

echo "✅ Test with real screen readers (NVDA, JAWS, VoiceOver)"
echo "✅ Perform keyboard-only navigation testing"
echo "✅ Test with browser zoom at 200%"
echo "✅ Use axe DevTools browser extension for detailed analysis"
echo "✅ Test with users who have disabilities (if possible)"
echo "✅ Implement automated a11y testing in CI/CD pipeline"

echo ""
echo "Manual Testing Checklist:"
echo "========================="
echo "[ ] Navigate entire booking flow using only keyboard (Tab, Enter, Esc)"
echo "[ ] Test with screen reader (ensure all information is announced)"
echo "[ ] Zoom to 200% and verify all functionality still works"
echo "[ ] Test color contrast with online tools (WebAIM, Contrast Checker)"
echo "[ ] Test with vision simulator (colorblind, low vision)"
echo "[ ] Disable JavaScript and verify critical content is accessible"
echo "[ ] Test form validation with assistive technology"
echo "[ ] Ensure error messages are clearly announced to screen readers"

echo ""
echo "Additional Tools:"
echo "================="
echo "• axe DevTools: https://www.deque.com/axe/devtools/"
echo "• WAVE: https://wave.webaim.org/"
echo "• Lighthouse (Chrome DevTools): Run accessibility audit"
echo "• Color Contrast Checker: https://webaim.org/resources/contrastchecker/"
echo "• NVDA (Screen Reader): https://www.nvaccess.org/"

echo ""
echo "Report generated: $(date)"
echo ""

exit $EXIT_CODE
