//! Comprehensive integration tests for cleaner and picture features.
//!
//! This test suite exercises both features in complex, realistic scenarios
//! to ensure they work correctly together in all situations.

#[cfg(all(feature = "cleaner", feature = "picture"))]
mod tests {
    use microformats::extensions::CleanedDocument;
    use microformats_types::{Class, Document, KnownClass, PropertyValue};
    use std::time::Instant;
    use url::Url;

    fn parse_html_to_document(html: &str, base_url: &Url) -> Result<Document, microformats::Error> {
        microformats::from_html(html, base_url)
    }

    #[test]
    fn test_complete_travel_blog_integration() -> Result<(), microformats::Error> {
        let html = include_str!("../../../../../test_travel_blog_with_pictures.html");

        let base_url = Url::parse("https://travel-blog.example.com/").unwrap();
        let document = parse_html_to_document(html, &base_url)?;

        // Check original document state
        let original_items_count = document.items.len();
        let unrecognized_items = document.unrecognized_items();
        println!(
            "Original items: {}, Unrecognized: {}",
            original_items_count,
            unrecognized_items.len()
        );

        // Clean the document
        let cleaned = document.with_only_known_classes();

        // Verify expected structure
        assert!(cleaned.items.len() > 0);

        // Should preserve main blog feed and valid entries
        let main_feed = cleaned.items.iter().find(|item| {
            item.r#type
                .iter()
                .any(|c| matches!(c, Class::Known(KnownClass::Feed)))
        });

        assert!(main_feed.is_some(), "Should preserve h-feed");

        let h_feed = main_feed.unwrap();

        // Should have multiple h-entry children
        assert!(
            h_feed.children.len() >= 3,
            "Should have multiple feed entries"
        );

        // Each entry should have picture-based photos
        for entry in &h_feed.children {
            assert!(matches!(&entry.r#type[0], Class::Known(KnownClass::Entry)));

            // Most entries should have photos from picture elements
            if entry.properties.contains_key("photo") {
                let photos = entry.properties.get("photo").unwrap();
                for photo in photos {
                    match photo {
                        PropertyValue::Image(image) => {
                            // Verify URLs are properly resolved
                            assert!(image.value.as_str().starts_with("https://"));
                            println!("✓ Found image: {} (alt: {:?})", image.value, image.alt);
                        }
                        PropertyValue::Url(url) => {
                            assert!(url.value().starts_with("https://"));
                            println!("✓ Found URL: {}", url.value());
                        }
                        _ => println!("Unexpected photo type: {:?}", photo),
                    }
                }
            }
        }

        Ok(())
    }

    #[test]
    fn test_news_website_with_responsive_images() -> Result<(), microformats::Error> {
        let html = r#"
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <title>Tech News - Latest Articles</title>
            <link rel="author" href="https://news.example.com/editor">
            <link rel="me" href="https://social.example.com/technews">
        </head>
        <body>
            <header class="h-card">
                <picture class="u-logo">
                    <source srcset="/logo/tech-news-2x.svg 2x, /logo/tech-news-1x.svg 1x" type="image/svg+xml">
                    <source srcset="/logo/tech-news-2x.png 2x, /logo/tech-news-1x.png 1x" type="image/png">
                    <img src="/logo/tech-news.png" alt="Tech News">
                </picture>
                <h1 class="p-name">Tech News</h1>
            </header>
            
            <main class="h-feed">
                <article class="h-entry" id="article-1">
                    <h2 class="p-name">Breaking: New Technology Released</h2>
                    
                    <picture class="u-photo">
                        <source srcset="/articles/2024/breaking-tech-1200w.jpg 1200w, /articles/2024/breaking-tech-800w.jpg 800w, /articles/2024/breaking-tech-400w.jpg 400w"
                                media="(min-width: 800px)" type="image/jpeg">
                        <source srcset="/articles/2024/breaking-tech-tablet.webp" media="(min-width: 768px)" type="image/webp">
                        <source srcset="/articles/2024/breaking-tech-mobile.jpg" media="(min-width: 320px)" type="image/jpeg">
                        <img src="/articles/2024/breaking-tech-fallback.jpg" alt="New technology device">
                    </picture>
                    
                    <div class="p-author h-card">
                        <picture class="u-photo">
                            <source srcset="/authors/jane-2x.jpg 2x, /authors/jane-1x.jpg 1x" type="image/jpeg">
                            <img src="/authors/jane.jpg" alt="Jane Doe">
                        </picture>
                        <span class="p-name">Jane Doe</span>
                        <a href="/authors/jane" class="u-url">Profile</a>
                    </div>
                    
                    <div class="e-content">
                        <p>Breaking news about the latest technology release.</p>
                        
                        <picture class="u-photo">
                            <source srcset="/articles/2024/breaking-tech-detail-600w.jpg 600w" type="image/jpeg">
                            <img src="/articles/2024/breaking-tech-detail.jpg" alt="Technology detail view">
                        </picture>
                    </div>
                    
                    <div class="p-location h-card">
                        <picture class="u-photo">
                            <img src="/locations/silicon-valley.jpg" alt="Silicon Valley">
                        </picture>
                        <span class="p-name">Silicon Valley, CA</span>
                    </div>
                </article>
                
                <article class="h-entry" id="article-2">
                    <h2 class="p-name">Industry Analysis: Market Trends</h2>
                    
                    <picture class="u-photo">
                        <source srcset="/articles/2024/trends-800w.jpg 800w, /articles/2024/trends-400w.jpg 400w" type="image/jpeg">
                        <img src="/articles/2024/trends.jpg" alt="Market trends chart">
                    </picture>
                    
                    <div class="p-author h-card">
                        <picture class="u-photo">
                            <source srcset="/authors/john-2x.jpg 2x" type="image/jpeg">
                            <img src="/authors/john.jpg" alt="John Smith">
                        </picture>
                        <span class="p-name">John Smith</span>
                    </div>
                </article>
                
                <!-- Custom content that should be filtered -->
                <div class="h-sponsored-article">
                    <picture class="u-photo">
                        <source srcset="/ads/sponsor-800w.jpg 800w" type="image/jpeg">
                        <img src="/ads/sponsor.jpg" alt="Sponsored content">
                    </picture>
                    <h3 class="p-custom-title">Sponsored Content</h3>
                </div>
                
                <!-- Another custom item -->
                <div class="h-promo-content h-custom-layout">
                    <picture class="u-photo">
                        <img src="/promo/featured.jpg" alt="Promotional content">
                    </picture>
                </div>
            </main>
        </body>
        </html>
        "#;

        let base_url = Url::parse("https://news.example.com/").unwrap();
        let start = Instant::now();

        let document = parse_html_to_document(html, &base_url)?;
        let parse_time = start.elapsed();

        let cleaning_start = Instant::now();
        let cleaned = document.with_only_known_classes();
        let cleaning_time = cleaning_start.elapsed();

        println!(
            "Parse time: {:?}, Cleaning time: {:?}",
            parse_time, cleaning_time
        );

        // Should filter out custom content
        assert_eq!(cleaned.items.len(), 1); // Just the h-feed

        let h_feed = &cleaned.items[0];
        assert!(matches!(&h_feed.r#type[0], Class::Known(KnownClass::Feed)));

        // Should have header h-card and h-entry children
        assert_eq!(h_feed.children.len(), 3); // header + 2 articles

        // Verify header h-card
        let header = &h_feed.children[0];
        assert!(matches!(&header.r#type[0], Class::Known(KnownClass::Card)));
        assert!(header.properties.contains_key("name"));
        assert!(header.properties.contains_key("logo"));

        // Verify articles have all expected properties
        for (i, entry) in h_feed.children.iter().enumerate().skip(1) {
            assert!(matches!(&entry.r#type[0], Class::Known(KnownClass::Entry)));

            assert!(entry.properties.contains_key("name"));
            assert!(entry.properties.contains_key("author"));
            assert!(entry.properties.contains_key("photo"));

            println!(
                "Entry {} has {} photos",
                i,
                entry.properties.get("photo").unwrap().len()
            );

            // Check author nested structure
            if let Some(PropertyValue::Item(author)) =
                entry.properties.get("author").unwrap().first()
            {
                assert!(matches!(&author.r#type[0], Class::Known(KnownClass::Card)));
                assert!(author.properties.contains_key("photo"));
                assert!(author.properties.contains_key("name"));
            }
        }

        // First article should have location
        let first_article = &h_feed.children[1];
        assert!(first_article.properties.contains_key("location"));

        Ok(())
    }

    #[test]
    fn test_ecommerce_product_gallery() -> Result<(), microformats::Error> {
        let html = r#"
        <div class="h-product" id="product-123">
            <h1 class="p-name">Premium Wireless Headphones</h1>
            
            <!-- Main product image gallery -->
            <div class="product-gallery">
                <picture class="u-photo">
                    <source srcset="/products/headphones/main-1200w.jpg 1200w, /products/headphones/main-800w.jpg 800w, /products/headphones/main-400w.jpg 400w"
                            media="(min-width: 800px)" type="image/jpeg">
                    <source srcset="/products/headphones/main.webp" media="(min-width: 768px)" type="image/webp">
                    <img src="/products/headphones/main.jpg" alt="Premium wireless headphones front view">
                </picture>
                
                <picture class="u-photo">
                    <source srcset="/products/headphones/side-800w.jpg 800w, /products/headphones/side-400w.jpg 400w" type="image/jpeg">
                    <img src="/products/headphones/side.jpg" alt="Headphones side view">
                </picture>
                
                <picture class="u-photo">
                    <source srcset="/products/headphones/detail-600w.jpg 600w" type="image/jpeg">
                    <img src="/products/headphones/detail.jpg" alt="Headphones detail shot">
                </picture>
            </div>
            
            <!-- Brand information -->
            <div class="p-brand h-card">
                <picture class="u-logo">
                    <source srcset="/brands/techco-2x.svg 2x, /brands/techco-1x.svg 1x" type="image/svg+xml">
                    <img src="/brands/techco.png" alt="TechCo Logo">
                </picture>
                <span class="p-name">TechCo</span>
            </div>
            
            <!-- Review with reviewer photo -->
            <div class="p-review h-review">
                <div class="h-reviewer h-card">
                    <picture class="u-photo">
                        <source srcset="/reviewers/alex-2x.jpg 2x" type="image/jpeg">
                        <img src="/reviewers/alex.jpg" alt="Alex Reviewer">
                    </picture>
                    <span class="p-name">Alex Johnson</span>
                </div>
                <span class="p-rating">5</span>
                <div class="e-description">Excellent product with great sound quality!</div>
            </div>
            
            <!-- Custom promotional content (should be filtered) -->
            <div class="h-custom-promo">
                <picture class="u-photo">
                    <source srcset="/promo/special-offer-800w.jpg 800w" type="image/jpeg">
                    <img src="/promo/special-offer.jpg" alt="Special promotion">
                </picture>
                <div class="p-custom-offer">Limited time offer!</div>
            </div>
        </div>
        "#;

        let base_url = Url::parse("https://store.example.com/products/headphones").unwrap();
        let document = parse_html_to_document(html, &base_url)?;
        let cleaned = document.with_only_known_classes();

        // Should keep the h-product
        assert_eq!(cleaned.items.len(), 1);

        let product = &cleaned.items[0];
        assert!(matches!(
            &product.r#type[0],
            Class::Known(KnownClass::Product)
        ));
        assert_eq!(product.id, Some("product-123".to_string()));

        // Should have all product photos (3 from gallery)
        assert_eq!(product.properties.get("photo").unwrap().len(), 3);

        // Should have brand as nested h-card
        assert!(product.properties.contains_key("brand"));
        if let Some(PropertyValue::Item(brand)) = product.properties.get("brand").unwrap().first() {
            assert!(matches!(&brand.r#type[0], Class::Known(KnownClass::Card)));
            assert!(brand.properties.contains_key("logo"));
            assert!(brand.properties.contains_key("name"));
        }

        // Should have review as nested structure
        assert!(product.properties.contains_key("review"));

        Ok(())
    }

    #[test]
    fn test_social_media_profile() -> Result<(), microformats::Error> {
        let html = r#"
        <div class="h-card" id="user-profile">
            <div class="profile-header">
                <picture class="u-photo">
                    <source srcset="/avatars/user-512.jpg 512w, /avatars/user-256.jpg 256w, /avatars/user-128.jpg 128w"
                            media="(min-width: 512px)" type="image/jpeg">
                    <source srcset="/avatars/user.webp" media="(min-width: 256px)" type="image/webp">
                    <img src="/avatars/user.jpg" alt="Jane Smith's profile picture">
                </picture>
                
                <div class="profile-info">
                    <h1 class="p-name">Jane Smith</h1>
                    <p class="p-org h-card">
                        <picture class="u-logo">
                            <source srcset="/companies/acme-2x.png 2x" type="image/png">
                            <img src="/companies/acme.png" alt="ACME Inc Logo">
                        </picture>
                        <span class="p-name">ACME Inc</span>
                    </p>
                </div>
            </div>
            
            <div class="profile-bio">
                <p class="p-note">Software developer and tech enthusiast.</p>
            </div>
            
            <div class="recent-posts h-feed">
                <h2 class="p-name">Recent Posts</h2>
                
                <article class="h-entry">
                    <picture class="u-photo">
                        <source srcset="/posts/post1-800w.jpg 800w, /posts/post1-400w.jpg 400w" type="image/jpeg">
                        <img src="/posts/post1.jpg" alt="Post about new technology">
                    </picture>
                    <h3 class="p-name">Exciting New Technology Trends</h3>
                    <div class="e-content">Just discovered some amazing new tech...</div>
                </article>
                
                <article class="h-entry">
                    <picture class="u-photo">
                        <source srcset="/posts/post2-600w.jpg 600w" type="image/jpeg">
                        <img src="/posts/post2.jpg" alt="Development workflow">
                    </picture>
                    <h3 class="p-name">My Development Setup</h3>
                    <div class="e-content">Here's how I organize my workspace...</div>
                </article>
                
                <!-- Custom post type (should be filtered) -->
                <div class="h-custom-post">
                    <picture class="u-photo">
                        <img src="/posts/custom.jpg" alt="Custom post content">
                    </picture>
                    <h3 class="p-custom-title">Custom Content</h3>
                </div>
            </div>
            
            <!-- Custom sidebar content (should be filtered) -->
            <aside class="h-custom-sidebar">
                <picture class="u-photo">
                    <img src="/ads/sidebar-300x250.jpg" alt="Advertisement">
                </picture>
            </aside>
        </div>
        "#;

        let base_url = Url::parse("https://social.example.com/janesmith").unwrap();
        let document = parse_html_to_document(html, &base_url)?;
        let cleaned = document.with_only_known_classes();

        // Should keep the main h-card
        assert_eq!(cleaned.items.len(), 1);

        let profile = &cleaned.items[0];
        assert!(matches!(&profile.r#type[0], Class::Known(KnownClass::Card)));

        // Should have profile photo
        assert!(profile.properties.contains_key("photo"));

        // Should have org as nested h-card
        assert!(profile.properties.contains_key("org"));
        if let Some(PropertyValue::Item(org)) = profile.properties.get("org").unwrap().first() {
            assert!(matches!(&org.r#type[0], Class::Known(KnownClass::Card)));
            assert!(org.properties.contains_key("logo"));
        }

        // Should have feed as child (but feed items should be siblings, not children)
        // In this HTML structure, the h-feed is actually nested, so check children
        assert!(!profile.children.is_empty());

        Ok(())
    }

    #[test]
    fn test_event_with_multiple_organizers() -> Result<(), microformats::Error> {
        let html = r#"
        <div class="h-event" id="conference-2024">
            <h1 class="p-name">Tech Conference 2024</h1>
            
            <picture class="u-photo">
                <source srcset="/events/conference-banner-1200w.jpg 1200w, /events/conference-banner-800w.jpg 800w, /events/conference-banner-400w.jpg 400w"
                        media="(min-width: 800px)" type="image/jpeg">
                <source srcset="/events/conference-banner.webp" media="(min-width: 768px)" type="image/webp">
                <img src="/events/conference-banner.jpg" alt="Tech Conference 2024 Banner">
            </picture>
            
            <div class="event-details">
                <time class="dt-start" datetime="2024-06-15T09:00:00-07:00">June 15, 2024 at 9:00 AM</time>
                <span class="p-location h-card">
                    <picture class="u-photo">
                        <source srcset="/venues/tech-center-800w.jpg 800w" type="image/jpeg">
                        <img src="/venues/tech-center.jpg" alt="Tech Convention Center">
                    </picture>
                    <span class="p-name">Tech Convention Center</span>
                </span>
            </div>
            
            <div class="organizers">
                <h2>Organizers</h2>
                
                <div class="p-organizer h-card">
                    <picture class="u-photo">
                        <source srcset="/people/organizer1-2x.jpg 2x" type="image/jpeg">
                        <img src="/people/organizer1.jpg" alt="John Organizer">
                    </picture>
                    <span class="p-name">John Organizer</span>
                    <span class="p-org">Tech Events Inc</span>
                </div>
                
                <div class="p-organizer h-card">
                    <picture class="u-photo">
                        <source srcset="/people/organizer2-2x.jpg 2x" type="image/jpeg">
                        <img src="/people/organizer2.jpg" alt="Jane Coordinator">
                    </picture>
                    <span class="p-name">Jane Coordinator</span>
                    <span class="p-org">Conference Pros</span>
                </div>
                
                <!-- Custom organizer (should be filtered) -->
                <div class="p-organizer h-custom-organizer">
                    <picture class="u-photo">
                        <img src="/people/sponsor.jpg" alt="Sponsor contact">
                    </picture>
                    <span class="p-name">Sponsor Rep</span>
                </div>
            </div>
            
            <div class="attendees">
                <h2>Attendees</h2>
                
                <div class="p-attendee h-card">
                    <picture class="u-photo">
                        <source srcset="/attendees/user1-150w.jpg 150w" type="image/jpeg">
                        <img src="/attendees/user1.jpg" alt="Attendee 1">
                    </picture>
                    <span class="p-name">Alice Attendee</span>
                </div>
                
                <div class="p-attendee h-card">
                    <picture class="u-photo">
                        <source srcset="/attendees/user2-150w.jpg 150w" type="image/jpeg">
                        <img src="/attendees/user2.jpg" alt="Attendee 2">
                    </picture>
                    <span class="p-name">Bob Attendee</span>
                </div>
            </div>
        </div>
        "#;

        let base_url = Url::parse("https://events.example.com/conference-2024").unwrap();
        let document = parse_html_to_document(html, &base_url)?;
        let cleaned = document.with_only_known_classes();

        assert_eq!(cleaned.items.len(), 1);

        let event = &cleaned.items[0];
        assert!(matches!(&event.r#type[0], Class::Known(KnownClass::Event)));

        // Should have event photo
        assert!(event.properties.contains_key("photo"));

        // Should have location as nested h-card
        assert!(event.properties.contains_key("location"));

        // Should have organizers (2 valid ones, 1 filtered)
        let organizers = event.properties.get("organizer").unwrap();
        assert_eq!(organizers.len(), 2); // Custom one filtered

        for organizer in organizers {
            if let PropertyValue::Item(org) = organizer {
                assert!(matches!(&org.r#type[0], Class::Known(KnownClass::Card)));
                assert!(org.properties.contains_key("photo"));
                assert!(org.properties.contains_key("name"));
            }
        }

        // Should have attendees
        assert!(event.properties.contains_key("attendee"));
        let attendees = event.properties.get("attendee").unwrap();
        assert_eq!(attendees.len(), 2);

        Ok(())
    }

    #[test]
    fn test_extreme_performance_large_document() -> Result<(), microformats::Error> {
        // Generate a large document with many picture elements
        let mut html = String::from(
            r#"
        <!DOCTYPE html>
        <html>
        <body>
            <div class="h-feed">
                <h1 class="p-name">Large Feed Test</h1>
        "#,
        );

        // Add 50 entries with multiple pictures each
        for i in 0..50 {
            html.push_str(&format!(r#"
            <article class="h-entry" id="entry-{}">
                <h2 class="p-name">Entry {}</h2>
                
                <picture class="u-photo">
                    <source srcset="/images/{}-main-800w.jpg 800w, /images/{}-main-400w.jpg 400w" type="image/jpeg">
                    <img src="/images/{}-main.jpg" alt="Main image for entry {}">
                </picture>
                
                <div class="p-author h-card">
                    <picture class="u-photo">
                        <source srcset="/authors/author{}-2x.jpg 2x" type="image/jpeg">
                        <img src="/authors/author{}.jpg" alt="Author {}">
                    </picture>
                    <span class="p-name">Author {}</span>
                </div>
                
                {}
                <picture class="u-photo">
                    <source srcset="/images/{}-secondary-600w.jpg 600w" type="image/jpeg">
                    <img src="/images/{}-secondary.jpg" alt="Secondary image for entry {}">
                </picture>
                
                <div class="e-content">
                    <p>Content for entry {} with inline image:</p>
                    <picture class="u-photo">
                        <source srcset="/images/{}-content-400w.jpg 400w" type="image/jpeg">
                        <img src="/images/{}-content.jpg" alt="Content image {}">
                    </picture>
                </div>
                
                {}
            </article>
            "#, i, i, i, i, i, i, i, i, i, 
                if i % 10 == 9 { r#"<div class="h-custom-content"><picture class="u-photo"><img src="/custom.jpg" alt="Custom"></picture></div>"# } else { "" },
                i, i, i, i, i, i, i, i,
                if i % 10 == 9 { r#"<div class="h-another-custom"><picture class="u-photo"><img src="/custom2.jpg" alt="Custom 2"></picture></div>"# } else { "" }));
        }

        // Close the document
        html.push_str(r#"</div></body></html>"#);

        let base_url = Url::parse("https://large.example.com/").unwrap();

        // Time the parsing and cleaning
        let start = Instant::now();
        let document = parse_html_to_document(&html, &base_url)?;
        let parse_duration = start.elapsed();

        let cleaning_start = Instant::now();
        let cleaned = document.with_only_known_classes();
        let cleaning_duration = cleaning_start.elapsed();

        println!("Performance test with {} picture elements:", 50 * 3);
        println!("  Parsing: {:?}", parse_duration);
        println!("  Cleaning: {:?}", cleaning_duration);
        println!("  Total: {:?}", parse_duration + cleaning_duration);

        // Should have completed within reasonable time
        assert!(
            (parse_duration + cleaning_duration).as_secs() < 10,
            "Processing took too long"
        );

        // Should have filtered out some items (every 10th has custom content)
        println!("Original items: {}", document.items.len());
        println!("Cleaned items: {}", cleaned.items.len());
        println!("Unrecognized: {}", document.unrecognized_items().len());

        // The feed should be preserved
        assert_eq!(cleaned.items.len(), 1);
        let feed = &cleaned.items[0];
        assert!(matches!(&feed.r#type[0], Class::Known(KnownClass::Feed)));

        // Should have all valid entries (50)
        assert_eq!(feed.children.len(), 50);

        // Each entry should have photos
        for entry in &feed.children {
            let photos = entry.properties.get("photo").unwrap();
            assert_eq!(photos.len(), 3); // 3 pictures per entry
        }

        Ok(())
    }

    #[test]
    fn test_malformed_html_recovery() -> Result<(), microformats::Error> {
        let html = r#"
        <div class="h-entry"
            <h1 class="p-name">Malformed HTML Test</h1>
            
            <!-- Malformed picture elements -->
            <picture class="u-photo"
                <source srcset="/images/malformed1.jpg 400w
                <img src="/images/malformed1.jpg" alt="Malformed 1"
            </picture>
            
            <picture class="u-photo">
                <source srcset="/images/malformed2.jpg 800w, /images/malformed2.jpg 400w" type="image/jpeg"
                <img src="/images/malformed2.jpg" alt="Malformed 2"
            </picture
            
            <picture class="u-photo">
                <source srcset="/images/malformed3.jpg" type="image/jpeg">
                <img src="/images/malformed3.jpg" alt="Malformed 3">
            <!-- Missing closing picture tag -->
            
            <div class="p-author h-card"
                <picture class="u-photo">
                    <img src="/authors/malformed.jpg" alt="Malformed author"
                </picture>
                <span class="p-name">Malformed Author</span>
            </div>
            
            <div class="h-custom-malformed"
                <picture class="u-photo">
                    <img src="/custom/malformed.jpg" alt="Custom malformed"
                </picture>
            </div
        </div>
        "#;

        let base_url = Url::parse("https://malformed.example.com/").unwrap();

        // Should either parse successfully or fail gracefully
        let result = parse_html_to_document(html, &base_url);

        match result {
            Ok(document) => {
                let cleaned = document.with_only_known_classes();

                // Should have filtered out the malformed custom item
                assert_eq!(cleaned.items.len(), 0);

                // Original should have recognized the malformed items
                assert!(!document.items.is_empty());

                println!(
                    "Successfully parsed malformed HTML with {} items",
                    document.items.len()
                );
            }
            Err(e) => {
                // If it fails, it should be a parsing error, not a panic
                println!("Failed to parse malformed HTML: {:?}", e);
                // This is acceptable for severely malformed HTML
            }
        }

        Ok(())
    }
}
