typstify-generator 0.1.5

Static site generation engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
//! HTML generation from parsed content.
//!
//! Converts parsed content into final HTML pages using templates.

use std::path::{Path, PathBuf};

use chrono::{Datelike, Utc};
use thiserror::Error;
use tracing::debug;
use typstify_core::{
    Config, Page,
    utils::{html_escape, slugify},
};

use crate::template::{Template, TemplateContext, TemplateError, TemplateRegistry};

/// HTML generation errors.
#[derive(Debug, Error)]
pub enum HtmlError {
    /// Template error.
    #[error("template error: {0}")]
    Template(#[from] TemplateError),

    /// IO error.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Invalid page data.
    #[error("invalid page data: {0}")]
    InvalidPage(String),
}

/// Result type for HTML generation.
pub type Result<T> = std::result::Result<T, HtmlError>;

/// HTML page generator.
#[derive(Debug)]
pub struct HtmlGenerator<'a> {
    templates: TemplateRegistry,
    config: &'a Config,
    /// Content sections for dynamic navigation (e.g., "posts", "shorts").
    sections: Vec<String>,
}

impl<'a> HtmlGenerator<'a> {
    /// Create a new HTML generator with the given configuration.
    #[must_use]
    pub fn new(config: &'a Config) -> Self {
        Self {
            templates: TemplateRegistry::new(),
            config,
            sections: Vec::new(),
        }
    }

    /// Create a generator with custom templates.
    #[must_use]
    pub fn with_templates(config: &'a Config, templates: TemplateRegistry) -> Self {
        Self {
            templates,
            config,
            sections: Vec::new(),
        }
    }

    /// Set content sections for dynamic navigation.
    #[must_use]
    pub fn with_sections(mut self, sections: Vec<String>) -> Self {
        self.sections = sections;
        self
    }

    /// Generate navigation HTML for content sections.
    fn generate_section_nav(&self, base_path: &str, lang_prefix: &str) -> String {
        if self.sections.is_empty() {
            // Default to "Posts" if no sections configured
            return format!(r#"<a href="{base_path}{lang_prefix}/posts">Posts</a>"#);
        }

        // Filter out language codes (2-3 letter codes) and standalone pages like "about"
        let excluded_sections = ["about", "index"];
        let filtered_sections: Vec<_> = self
            .sections
            .iter()
            .filter(|s| {
                // Exclude 2-3 letter sections (likely language codes like "zh", "en")
                if s.len() <= 3 && s.chars().all(|c| c.is_ascii_lowercase()) {
                    return false;
                }
                // Exclude known standalone pages
                !excluded_sections.contains(&s.as_str())
            })
            .collect();

        if filtered_sections.is_empty() {
            return format!(r#"<a href="{base_path}{lang_prefix}/posts">Posts</a>"#);
        }

        filtered_sections
            .iter()
            .map(|section| {
                // Capitalize first letter for display
                let title = section
                    .chars()
                    .next()
                    .map(|c| c.to_uppercase().collect::<String>() + &section[c.len_utf8()..])
                    .unwrap_or_else(|| (*section).clone());
                format!(
                    r#"<a href="{base_path}{lang_prefix}/{section}">{}</a>"#,
                    html_escape(&title)
                )
            })
            .collect::<Vec<_>>()
            .join("\n                    ")
    }

    /// Register a custom template.
    pub fn register_template(&mut self, template: Template) {
        self.templates.register(template);
    }

    /// Generate HTML for a page.
    pub fn generate_page(&self, page: &Page, alternates: &[(&str, &str)]) -> Result<String> {
        debug!(url = %page.url, "generating HTML for page");

        // Determine which template to use
        let template_name = page.template.as_deref().map_or_else(
            || {
                if page.date.is_some() { "post" } else { "page" }
            },
            |t| {
                // Normalize "shorts" to "short" for individual pages
                if t == "shorts" { "short" } else { t }
            },
        );

        // Build inner content context
        let inner_ctx = self.build_page_context(page)?;
        let inner_html = self.templates.render(template_name, &inner_ctx)?;

        // Build outer (base) context
        let base_ctx = self.build_base_context(page, &inner_html, alternates)?;
        Ok(self.templates.render("base", &base_ctx)?)
    }

    /// Generate redirect HTML for URL aliases.
    pub fn generate_redirect(&self, redirect_url: &str) -> Result<String> {
        let ctx = TemplateContext::new().with_var("redirect_url", redirect_url);
        self.templates
            .render("redirect", &ctx)
            .map_err(HtmlError::from)
    }

    /// Generate a list page HTML.
    pub fn generate_list_page(
        &self,
        title: &str,
        items_html: &str,
        pagination_html: Option<&str>,
    ) -> Result<String> {
        let mut ctx = TemplateContext::new()
            .with_var("title", title)
            .with_var("items", items_html);

        if let Some(pagination) = pagination_html {
            ctx.insert("pagination", pagination);
        }

        let inner_html = self.templates.render("list", &ctx)?;

        let base_url = self.config.base_url();
        let base_ctx = self.build_shared_base_ctx(
            &self.config.site.default_language,
            title,
            base_url,
            &inner_html,
            "",
        );

        Ok(self.templates.render("base", &base_ctx)?)
    }

    /// Generate a taxonomy term page HTML.
    pub fn generate_taxonomy_page(
        &self,
        taxonomy_name: &str,
        term: &str,
        items_html: &str,
        pagination_html: Option<&str>,
    ) -> Result<String> {
        let mut ctx = TemplateContext::new()
            .with_var("taxonomy_name", taxonomy_name)
            .with_var("term", term)
            .with_var("items", items_html);

        if let Some(pagination) = pagination_html {
            ctx.insert("pagination", pagination);
        }

        let inner_html = self.templates.render("taxonomy", &ctx)?;
        let title = format!("{taxonomy_name}: {term}");

        let base_url = self.config.base_url();
        let canonical_url = format!("{}/{}/{}", base_url, taxonomy_name.to_lowercase(), term);

        let base_ctx = self.build_shared_base_ctx(
            &self.config.site.default_language,
            &title,
            &canonical_url,
            &inner_html,
            "",
        );

        Ok(self.templates.render("base", &base_ctx)?)
    }

    /// Build shared base template context with common navigation variables.
    fn build_shared_base_ctx(
        &self,
        lang: &str,
        title: &str,
        canonical_url: &str,
        content: &str,
        lang_prefix: &str,
    ) -> TemplateContext {
        let base_path = self.config.base_path();
        TemplateContext::new()
            .with_var("lang", lang)
            .with_var("title", title)
            .with_var("base_path", base_path)
            .with_var(
                "site_title_suffix",
                format!(" | {}", self.config.title_for_language(lang)),
            )
            .with_var("canonical_url", canonical_url)
            .with_var("content", content)
            .with_var("site_title", self.config.title_for_language(lang))
            .with_var("year", Utc::now().year().to_string())
            .with_var("nav_home_url", format!("{base_path}{lang_prefix}/"))
            .with_var(
                "nav_archives_url",
                format!("{base_path}{lang_prefix}/archives"),
            )
            .with_var("nav_tags_url", format!("{base_path}{lang_prefix}/tags"))
            .with_var("nav_about_url", format!("{base_path}{lang_prefix}/about"))
            .with_var(
                "section_nav",
                self.generate_section_nav(base_path, lang_prefix),
            )
    }

    /// Build template context for page content.
    fn build_page_context(&self, page: &Page) -> Result<TemplateContext> {
        let mut ctx = TemplateContext::new()
            .with_var("title", &page.title)
            .with_var("content", &page.content);

        // Add date if present
        if let Some(date) = page.date {
            ctx.insert("date_iso", date.format("%Y-%m-%d").to_string());
            ctx.insert("date_formatted", date.format("%B %d, %Y").to_string());
        }

        // Add author info for short templates
        let author = self.config.site.author.as_deref().unwrap_or("Author");
        ctx.insert("author", author);
        let initials: String = author
            .split_whitespace()
            .filter_map(|w| w.chars().next())
            .take(2)
            .collect::<String>()
            .to_uppercase();
        ctx.insert("author_initials", initials);

        // Add tags HTML if present
        if !page.tags.is_empty() {
            let base_path = self.config.base_path();
            let lang_prefix = if page.is_default_lang {
                String::new()
            } else {
                format!("/{}", page.lang)
            };
            let tags_html = page
                .tags
                .iter()
                .map(|tag| {
                    format!(
                        r#"<a href="{base_path}{lang_prefix}/tags/{}" rel="tag">{}</a>"#,
                        slugify(tag),
                        tag
                    )
                })
                .collect::<Vec<_>>()
                .join(" ");
            ctx.insert(
                "tags_html",
                format!(r#"<div class="tags">{tags_html}</div>"#),
            );
        }

        Ok(ctx)
    }

    /// Build template context for base HTML wrapper.
    fn build_base_context(
        &self,
        page: &Page,
        inner_html: &str,
        alternates: &[(&str, &str)],
    ) -> Result<TemplateContext> {
        let lang_prefix = if page.is_default_lang {
            String::new()
        } else {
            format!("/{}", page.lang)
        };

        let canonical_url = format!("{}{}", self.config.base_url(), page.url);

        let mut ctx = self.build_shared_base_ctx(
            &page.lang,
            &page.title,
            &canonical_url,
            inner_html,
            &lang_prefix,
        );

        // Add description if present
        if let Some(desc) = &page.description {
            ctx.insert("description", desc);
        } else if let Some(site_desc) = self.config.description_for_language(&page.lang) {
            ctx.insert("description", site_desc);
        }

        // Add author if present
        if let Some(author) = &self.config.site.author {
            ctx.insert("author", author);
        }

        // Add custom CSS
        if !page.custom_css.is_empty() {
            let css_links = page
                .custom_css
                .iter()
                .map(|href| format!(r#"<link rel="stylesheet" href="{href}">"#))
                .collect::<Vec<_>>()
                .join("\n");
            ctx.insert("custom_css", css_links);
        }

        // Add custom JS
        if !page.custom_js.is_empty() {
            let js_scripts = page
                .custom_js
                .iter()
                .map(|src| format!(r#"<script src="{src}"></script>"#))
                .collect::<Vec<_>>()
                .join("\n");
            ctx.insert("custom_js", js_scripts);
        }

        // Generate language switcher HTML
        let lang_switcher = self.generate_lang_switcher(&page.lang, &page.canonical_id);
        if !lang_switcher.is_empty() {
            ctx.insert("lang_switcher", lang_switcher);
        }

        // Add hreflang tags
        if !alternates.is_empty() {
            let hreflang = alternates
                .iter()
                .map(|(lang, url)| {
                    format!(
                        r#"<link rel="alternate" hreflang="{}" href="{}{}" />"#,
                        lang,
                        self.config.base_url(),
                        url
                    )
                })
                .collect::<Vec<_>>()
                .join("\n");
            ctx.insert("hreflang", hreflang);
        }

        Ok(ctx)
    }

    /// Generate language switcher HTML dropdown.
    fn generate_lang_switcher(&self, current_lang: &str, canonical_id: &str) -> String {
        let all_langs = self.config.all_languages();
        if all_langs.len() <= 1 {
            return String::new();
        }

        let base_path = self.config.base_path();
        let mut options = Vec::new();

        for lang in &all_langs {
            let name = self.config.language_name(lang);
            let url = if *lang == self.config.site.default_language {
                // Default language: no prefix
                if canonical_id.is_empty() {
                    format!("{base_path}/")
                } else {
                    format!("{base_path}/{canonical_id}")
                }
            } else {
                // Non-default language: add prefix
                if canonical_id.is_empty() {
                    format!("{base_path}/{lang}/")
                } else {
                    format!("{base_path}/{lang}/{canonical_id}")
                }
            };

            let selected_class = if *lang == current_lang { " active" } else { "" };
            options.push(format!(
                r#"<a href="{url}" class="lang-option{selected_class}">{name}</a>"#,
            ));
        }

        // Get the language code for display (uppercase, max 2 chars)
        let display_code = current_lang
            .chars()
            .take(2)
            .collect::<String>()
            .to_uppercase();

        format!(
            r#"<div class="lang-switcher" tabindex="0" role="button" aria-label="Switch language" aria-haspopup="true">
    <span class="lang-code">{}</span>
    <div class="lang-dropdown">{}</div>
</div>"#,
            display_code,
            options.join("\n        ")
        )
    }

    /// Get the output path for a page.
    #[must_use]
    pub fn output_path(&self, page: &Page, output_dir: &Path) -> PathBuf {
        let relative = page.url.trim_start_matches('/');

        if relative.is_empty() {
            output_dir.join("index.html")
        } else {
            output_dir.join(relative).join("index.html")
        }
    }

    /// Generate a tags index page listing all tags with their counts.
    pub fn generate_tags_index_page(
        &self,
        tags: &std::collections::HashMap<String, Vec<String>>,
        lang: &str,
    ) -> Result<String> {
        let is_default_lang = lang == self.config.site.default_language;
        let lang_prefix = if is_default_lang {
            String::new()
        } else {
            format!("/{lang}")
        };

        // Get the base path for subdirectory deployments
        let base_path = self.config.base_path();

        let mut items: Vec<_> = tags.iter().collect();
        items.sort_by_key(|b| std::cmp::Reverse(b.1.len())); // Sort by count descending

        let items_html: String = items
            .iter()
            .map(|(tag, pages)| {
                format!(
                    r#"<a href="{base_path}{lang_prefix}/tags/{}" class="tag-item"><span class="tag-name">{}</span><span class="tag-count">{}</span></a>"#,
                    slugify(tag),
                    html_escape(tag),
                    pages.len()
                )
            })
            .collect::<Vec<_>>()
            .join("\n");

        let ctx = TemplateContext::new().with_var("items", &items_html);
        let inner_html = self.templates.render("tags_index", &ctx)?;

        let canonical_url = format!("{}{}/tags", self.config.base_url(), lang_prefix);

        let mut base_ctx =
            self.build_shared_base_ctx(lang, "Tags", &canonical_url, &inner_html, &lang_prefix);

        // Generate language switcher
        let lang_switcher = self.generate_lang_switcher(lang, "tags");
        if !lang_switcher.is_empty() {
            base_ctx.insert("lang_switcher", lang_switcher);
        }

        Ok(self.templates.render("base", &base_ctx)?)
    }

    /// Generate a categories index page listing all categories with their counts.
    pub fn generate_categories_index_page(
        &self,
        categories: &std::collections::HashMap<String, Vec<String>>,
        lang: &str,
    ) -> Result<String> {
        let is_default_lang = lang == self.config.site.default_language;
        let lang_prefix = if is_default_lang {
            String::new()
        } else {
            format!("/{lang}")
        };

        // Get the base path for subdirectory deployments
        let base_path = self.config.base_path();

        let mut items: Vec<_> = categories.iter().collect();
        items.sort_by(|a, b| a.0.cmp(b.0)); // Sort alphabetically

        let items_html: String = items
            .iter()
            .map(|(category, pages)| {
                format!(
                    r#"<li><a href="{base_path}{lang_prefix}/categories/{}">{}</a> <span class="count">({})</span></li>"#,
                    slugify(category),
                    html_escape(category),
                    pages.len()
                )
            })
            .collect::<Vec<_>>()
            .join("\n");

        let ctx = TemplateContext::new().with_var("items", &items_html);
        let inner_html = self.templates.render("categories_index", &ctx)?;

        let canonical_url = format!("{}{}/categories", self.config.base_url(), lang_prefix);

        let mut base_ctx = self.build_shared_base_ctx(
            lang,
            "Categories",
            &canonical_url,
            &inner_html,
            &lang_prefix,
        );

        // Generate language switcher
        let lang_switcher = self.generate_lang_switcher(lang, "categories");
        if !lang_switcher.is_empty() {
            base_ctx.insert("lang_switcher", lang_switcher);
        }

        Ok(self.templates.render("base", &base_ctx)?)
    }

    /// Generate an archives page listing all posts grouped by year.
    pub fn generate_archives_page(&self, pages: &[&Page], lang: &str) -> Result<String> {
        use std::collections::BTreeMap;

        let is_default_lang = lang == self.config.site.default_language;
        let lang_prefix = if is_default_lang {
            String::new()
        } else {
            format!("/{lang}")
        };

        // Group pages by year
        let mut by_year: BTreeMap<i32, Vec<&Page>> = BTreeMap::new();
        for page in pages {
            if let Some(date) = page.date {
                by_year.entry(date.year()).or_default().push(page);
            }
        }

        // Sort pages within each year by date (newest first)
        for pages in by_year.values_mut() {
            pages.sort_by_key(|b| std::cmp::Reverse(b.date));
        }

        // Generate HTML (years in descending order)
        let items_html: String = by_year
            .iter()
            .rev()
            .map(|(year, year_pages)| {
                let posts_html: String = year_pages
                    .iter()
                    .map(|p| {
                        let date_str = p
                            .date
                            .map(|d| d.format("%m-%d").to_string())
                            .unwrap_or_default();
                        // Determine template type for badge
                        let template_type = p.template.as_deref().unwrap_or("post");
                        let badge_class = match template_type {
                            "short" | "shorts" => "badge-short",
                            _ => "badge-post",
                        };
                        let badge_label = match template_type {
                            "short" | "shorts" => "short",
                            _ => "post",
                        };
                        format!(
                            r#"<li><span class="archive-date">{}</span><span class="archive-badge {}">{}</span><a href="{}">{}</a></li>"#,
                            date_str, badge_class, badge_label, html_escape(&p.url), html_escape(&p.title)
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("\n");

                format!(r#"<div class="archive-year"><h2>{year}</h2><ul>{posts_html}</ul></div>"#,)
            })
            .collect::<Vec<_>>()
            .join("\n");

        let ctx = TemplateContext::new().with_var("items", &items_html);
        let inner_html = self.templates.render("archives", &ctx)?;

        let canonical_url = format!("{}{}/archives", self.config.base_url(), lang_prefix);

        let mut base_ctx =
            self.build_shared_base_ctx(lang, "Archives", &canonical_url, &inner_html, &lang_prefix);

        // Generate language switcher
        let lang_switcher = self.generate_lang_switcher(lang, "archives");
        if !lang_switcher.is_empty() {
            base_ctx.insert("lang_switcher", lang_switcher);
        }

        Ok(self.templates.render("base", &base_ctx)?)
    }

    /// Generate a section index page (e.g., /posts/).
    pub fn generate_section_page(
        &self,
        section: &str,
        description: Option<&str>,
        items_html: &str,
        pagination_html: Option<&str>,
        lang: &str,
    ) -> Result<String> {
        let is_default_lang = lang == self.config.site.default_language;
        let lang_prefix = if is_default_lang {
            String::new()
        } else {
            format!("/{lang}")
        };

        // Convert section name to title case
        let title = section
            .chars()
            .next()
            .map(|c| c.to_uppercase().collect::<String>() + &section[1..])
            .unwrap_or_else(|| section.to_string());

        let mut ctx = TemplateContext::new()
            .with_var("title", &title)
            .with_var("items", items_html);

        if let Some(desc) = description {
            ctx.insert("description", desc);
        }

        if let Some(pagination) = pagination_html {
            ctx.insert("pagination", pagination);
        }

        let inner_html = self.templates.render("section", &ctx)?;

        let canonical_url = format!("{}{}/{}", self.config.base_url(), lang_prefix, section);

        let mut base_ctx =
            self.build_shared_base_ctx(lang, &title, &canonical_url, &inner_html, &lang_prefix);

        // Generate language switcher
        let lang_switcher = self.generate_lang_switcher(lang, section);
        if !lang_switcher.is_empty() {
            base_ctx.insert("lang_switcher", lang_switcher);
        }

        Ok(self.templates.render("base", &base_ctx)?)
    }

    /// Generate a shorts section index page (uses shorts-specific template).
    pub fn generate_shorts_page(
        &self,
        section: &str,
        description: Option<&str>,
        items_html: &str,
        pagination_html: Option<&str>,
        lang: &str,
    ) -> Result<String> {
        let is_default_lang = lang == self.config.site.default_language;
        let lang_prefix = if is_default_lang {
            String::new()
        } else {
            format!("/{lang}")
        };

        // Convert section name to title case
        let title = section
            .chars()
            .next()
            .map(|c| c.to_uppercase().collect::<String>() + &section[1..])
            .unwrap_or_else(|| section.to_string());

        let mut ctx = TemplateContext::new()
            .with_var("title", &title)
            .with_var("items", items_html);

        if let Some(desc) = description {
            ctx.insert("description", desc);
        }

        if let Some(pagination) = pagination_html {
            ctx.insert("pagination", pagination);
        }

        // Use shorts template
        let inner_html = self.templates.render("shorts", &ctx)?;

        let canonical_url = format!("{}{}/{}", self.config.base_url(), lang_prefix, section);

        let mut base_ctx =
            self.build_shared_base_ctx(lang, &title, &canonical_url, &inner_html, &lang_prefix);

        // Generate language switcher
        let lang_switcher = self.generate_lang_switcher(lang, section);
        if !lang_switcher.is_empty() {
            base_ctx.insert("lang_switcher", lang_switcher);
        }

        Ok(self.templates.render("base", &base_ctx)?)
    }
}

/// Generate HTML for a list item (used in list pages).
pub fn list_item_html(page: &Page) -> String {
    let date_html = page
        .date
        .map(|d| {
            format!(
                r#"<time datetime="{}">{}</time>"#,
                d.format("%Y-%m-%d"),
                d.format("%Y-%m-%d")
            )
        })
        .unwrap_or_default();

    let description_html = page
        .description
        .as_ref()
        .filter(|d| !d.is_empty())
        .map(|d| format!(r#"<p class="post-description">{}</p>"#, html_escape(d)))
        .unwrap_or_default();

    format!(
        r#"<li class="post-item">
    <div class="post-item-header">
        <a href="{}" class="post-title">{}</a>
        {}
    </div>
    {}
</li>"#,
        html_escape(&page.url),
        html_escape(&page.title),
        date_html,
        description_html
    )
}

/// Generate HTML for a short item (minimalist layout).
pub fn short_item_html(page: &Page, _author: &str) -> String {
    let date_html = page
        .date
        .map(|d| {
            format!(
                r#"<time class="short-date" datetime="{}">{}</time>"#,
                d.format("%Y-%m-%d"),
                d.format("%b %d, %Y")
            )
        })
        .unwrap_or_default();

    // Use actual content for shorts display
    let content_html = &page.content;

    format!(
        r#"<div class="short-item">
    {date_html}
    <div class="short-content">
        {content_html}
    </div>
</div>"#
    )
}

/// Generate HTML for shorts with date separators.
pub fn shorts_with_separators_html(pages: &[&Page], author: &str) -> String {
    let mut result = String::new();
    let mut last_date: Option<chrono::NaiveDate> = None;

    for page in pages {
        if let Some(date) = page.date {
            let current_date = date.date_naive();

            // Add separator if date changes
            if let Some(prev_date) = last_date
                && current_date != prev_date
            {
                result.push_str(r#"<hr class="date-separator">"#);
            }

            last_date = Some(current_date);
        }

        result.push_str(&short_item_html(page, author));
    }

    result
}

/// Generate pagination HTML.
pub fn pagination_html(current: usize, total: usize, base_url: &str) -> Option<String> {
    if total <= 1 {
        return None;
    }

    let mut parts = Vec::new();

    if current > 1 {
        let prev_url = if current == 2 {
            base_url.to_string()
        } else {
            format!("{}/page/{}", base_url, current - 1)
        };
        parts.push(format!(r#"<a href="{prev_url}" rel="prev">← Previous</a>"#));
    }

    parts.push(format!("Page {current} of {total}"));

    if current < total {
        parts.push(format!(
            r#"<a href="{}/page/{}" rel="next">Next →</a>"#,
            base_url,
            current + 1
        ));
    }

    Some(format!(
        r#"<nav class="pagination">{}</nav>"#,
        parts.join(" ")
    ))
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use typstify_core::test_fixtures::{test_config, test_page};

    use super::*;

    #[test]
    fn test_generate_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);
        let page = test_page();

        let html = generator.generate_page(&page, &[]).unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("<title>Test Page | Test Site</title>"));
        assert!(html.contains("<p>Hello, World!</p>"));
        assert!(html.contains("Test Site"));
    }

    #[test]
    fn test_generate_redirect() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let html = generator
            .generate_redirect("https://example.com/new-url")
            .unwrap();

        assert!(html.contains("Redirecting"));
        assert!(html.contains("https://example.com/new-url"));
        assert!(html.contains(r#"http-equiv="refresh""#));
    }

    #[test]
    fn test_list_item_html() {
        let page = test_page();
        let html = list_item_html(&page);

        assert!(html.contains(r#"<li class="post-item">"#));
        assert!(html.contains("post-title"));
        assert!(html.contains("Test Page"));
        assert!(html.contains("/test-page"));
    }

    #[test]
    fn test_pagination_html() {
        // Single page - no pagination
        assert!(pagination_html(1, 1, "/blog").is_none());

        // First page of many
        let html = pagination_html(1, 5, "/blog").unwrap();
        assert!(html.contains("Page 1 of 5"));
        assert!(html.contains("Next →"));
        assert!(!html.contains("Previous"));

        // Middle page
        let html = pagination_html(3, 5, "/blog").unwrap();
        assert!(html.contains("Page 3 of 5"));
        assert!(html.contains("Previous"));
        assert!(html.contains("Next →"));

        // Last page
        let html = pagination_html(5, 5, "/blog").unwrap();
        assert!(html.contains("Page 5 of 5"));
        assert!(html.contains("Previous"));
        assert!(!html.contains("Next →"));
    }

    #[test]
    fn test_output_path() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);
        let output_dir = Path::new("public");

        let page = test_page();
        let path = generator.output_path(&page, output_dir);
        assert_eq!(path, PathBuf::from("public/test-page/index.html"));

        // Root page
        let mut root_page = test_page();
        root_page.url = "/".to_string();
        let path = generator.output_path(&root_page, output_dir);
        assert_eq!(path, PathBuf::from("public/index.html"));
    }

    #[test]
    fn test_generate_list_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let html = generator
            .generate_list_page("My Posts", "<li>Post 1</li>", None)
            .unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("My Posts"));
        assert!(html.contains("<li>Post 1</li>"));
        assert!(html.contains("post-list"));
    }

    #[test]
    fn test_generate_list_page_with_pagination() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let pagination = r#"<nav class="pagination">Page 1 of 3</nav>"#;
        let html = generator
            .generate_list_page("Blog", "<li>Item</li>", Some(pagination))
            .unwrap();

        assert!(html.contains("Blog"));
        assert!(html.contains(r#"<nav class="pagination">"#));
        assert!(html.contains("Page 1 of 3"));
    }

    #[test]
    fn test_generate_taxonomy_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let html = generator
            .generate_taxonomy_page("Tags", "rust", "<li>Rust Post</li>", None)
            .unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Tags"));
        assert!(html.contains("rust"));
        assert!(html.contains("<li>Rust Post</li>"));
        assert!(html.contains("taxonomy"));
    }

    #[test]
    fn test_generate_taxonomy_page_with_pagination() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let pagination = r#"<nav class="pagination">Page 2 of 5</nav>"#;
        let html = generator
            .generate_taxonomy_page(
                "Categories",
                "tutorial",
                "<li>Tutorial Post</li>",
                Some(pagination),
            )
            .unwrap();

        assert!(html.contains("Categories"));
        assert!(html.contains("tutorial"));
        assert!(html.contains("Page 2 of 5"));
    }

    #[test]
    fn test_generate_tags_index_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let mut tags = HashMap::new();
        tags.insert(
            "rust".to_string(),
            vec!["page1".to_string(), "page2".to_string()],
        );
        tags.insert("web".to_string(), vec!["page3".to_string()]);

        let html = generator.generate_tags_index_page(&tags, "en").unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Tags"));
        assert!(html.contains("tag-item"));
        assert!(html.contains("rust"));
        assert!(html.contains("web"));
        assert!(html.contains("tag-count"));
        assert!(html.contains("tag-name"));
    }

    #[test]
    fn test_generate_categories_index_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let mut categories = HashMap::new();
        categories.insert(
            "programming".to_string(),
            vec!["p1".to_string(), "p2".to_string()],
        );
        categories.insert("design".to_string(), vec!["p3".to_string()]);

        let html = generator
            .generate_categories_index_page(&categories, "en")
            .unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Categories"));
        assert!(html.contains("programming"));
        assert!(html.contains("design"));
        assert!(html.contains("categories-list"));
    }

    #[test]
    fn test_generate_archives_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let mut page = test_page();
        page.date = Some(
            chrono::NaiveDateTime::parse_from_str("2024-01-15T10:00:00", "%Y-%m-%dT%H:%M:%S")
                .unwrap()
                .and_utc(),
        );
        page.title = "January Post".to_string();

        let html = generator.generate_archives_page(&[&page], "en").unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Archives"));
        assert!(html.contains("archive-year"));
        assert!(html.contains("2024"));
        assert!(html.contains("January Post"));
    }

    #[test]
    fn test_generate_archives_page_empty() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let html = generator.generate_archives_page(&[], "en").unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Archives"));
    }

    #[test]
    fn test_generate_section_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let html = generator
            .generate_section_page(
                "posts",
                Some("All blog posts"),
                "<li>Post A</li>",
                None,
                "en",
            )
            .unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Posts"));
        assert!(html.contains("All blog posts"));
        assert!(html.contains("<li>Post A</li>"));
        assert!(html.contains("section-list"));
    }

    #[test]
    fn test_generate_section_page_with_pagination() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let pagination = r#"<nav class="pagination">Page 1 of 2</nav>"#;
        let html = generator
            .generate_section_page("tutorials", None, "<li>Tut 1</li>", Some(pagination), "en")
            .unwrap();

        assert!(html.contains("Tutorials"));
        assert!(html.contains("Page 1 of 2"));
    }

    #[test]
    fn test_generate_shorts_page() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let html = generator
            .generate_shorts_page(
                "shorts",
                Some("Short-form content"),
                "<div class=\"short-item\">Short 1</div>",
                None,
                "en",
            )
            .unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Shorts"));
        assert!(html.contains("Short-form content"));
        assert!(html.contains("Short 1"));
        assert!(html.contains("shorts-section"));
    }

    #[test]
    fn test_generate_shorts_page_with_pagination() {
        let config = test_config();
        let generator = HtmlGenerator::new(&config);

        let pagination = r#"<nav class="pagination">Page 1 of 4</nav>"#;
        let html = generator
            .generate_shorts_page(
                "notes",
                None,
                "<div class=\"short-item\">Note 1</div>",
                Some(pagination),
                "en",
            )
            .unwrap();

        assert!(html.contains("Notes"));
        assert!(html.contains("Page 1 of 4"));
    }
}