use crate::model::PageSize;

pub(super) fn auto_watermark_font_size_with(text: &str, angle: f32, page_size: &PageSize, measure_fn: &dyn Fn(f32) -> f32) -> f32 {
    let diagonal = (page_size.width.powi(2) + page_size.height.powi(2)).sqrt();
    let char_count = text.chars().count() as f32;
    if char_count == 0.0 {
        return 10.0;
    }

    let mut low = 0.0;
    let mut high = 1000.0;
    let target_width = diagonal * 0.55;

    for _ in 0..50 {
        let mid = (low + high) / 2.0;
        let tw = measure_fn(mid);
        let angle_rad = angle * std::f32::consts::PI / 180.0;
        let text_height = mid * 0.8;
        let rotated_extent = tw * angle_rad.cos().abs() + text_height * angle_rad.sin().abs();

        if rotated_extent < target_width {
            low = mid;
        } else {
            high = mid;
        }
    }

    (low + high) / 2.0
}

#[allow(dead_code)]
pub(super) fn estimate_text_width(text: &str, font_size: f32) -> f32 {
    // Helvetica average char width ratio is ~0.65; use 0.65 to avoid clipping
    text.chars().count() as f32 * font_size * 0.65
}
