use clap::builder::StyledStr;
use xilem_html::{elements as el, ViewSequence};

fn empty_string(text: &String) -> bool {
    let empty = text.chars().all(|c| c.is_whitespace());

    if empty {
        tracing::debug!("Rejecting empty string of length {:?}", text.len());
    }

    empty
}

pub fn collapsible_docs<T>(
    short_help: Option<&StyledStr>,
    long_help: Option<&StyledStr>,
) -> impl ViewSequence<T> {
    let short_help = short_help.map(|s| s.to_string());
    let long_help = long_help.map(|s| s.to_string());

    if short_help.is_none() && long_help.is_none() {
        None
    } else {
        // When both help messages are set, short_help is sometimes a prefix
        // of long_help
        let long_help = 'prefix: {
            if let Some(ref short_help) = short_help {
                if let Some(ref long_help) = long_help {
                    // Check if it's a valid prefix
                    if let Some(stripped_help) = long_help.strip_prefix(short_help.as_str()) {
                        let stripped_help = stripped_help.to_string();
                        if empty_string(&stripped_help) {
                            break 'prefix None;
                        } else {
                            break 'prefix Some(stripped_help);
                        }
                    }
                }
            }

            long_help
        };

        Some(el::details((
            short_help
                .filter(|text| !empty_string(text))
                .map(el::summary),
            long_help
                .filter(|text| !empty_string(text))
                .map(el::blockquote),
        )))
    }
}