cookcli 0.28.0

A command-line interface for managing and working with Cooklang recipes
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
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
use crate::server::{templates::*, AppState};
use axum::{
    extract::{Extension, Host, Path, Query, State},
    http::{header, HeaderMap, StatusCode},
    response::IntoResponse,
    routing::get,
    Form, Router,
};
use camino::{Utf8Component, Utf8Path, Utf8PathBuf};
use fluent_templates::Loader;
use serde::Deserialize;
use std::sync::Arc;
use unic_langid::LanguageIdentifier;

fn error_page(
    lang: LanguageIdentifier,
    prefix: &str,
    msg: impl std::fmt::Display,
) -> axum::response::Response {
    let template = ErrorTemplate {
        active: String::new(),
        error_message: msg.to_string(),
        tr: Tr::new(lang),
        prefix: prefix.to_string(),
    };
    template.into_response()
}

pub fn ui() -> Router<Arc<AppState>> {
    Router::new()
        .route("/", get(recipes_page))
        .route("/directory/*path", get(recipes_directory))
        .route("/recipe/*path", get(recipe_page))
        .route("/edit/*path", get(edit_page))
        .route("/new", get(new_page).post(create_recipe))
        .route("/shopping-list", get(shopping_list_page))
        .route("/pantry", get(pantry_page))
        .route("/preferences", get(preferences_page))
}

async fn recipes_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> axum::response::Response {
    recipes_handler(state, None, lang).await
}

async fn recipes_directory(
    Path(path): Path<String>,
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> axum::response::Response {
    recipes_handler(state, Some(path), lang).await
}

async fn recipes_handler(
    state: Arc<AppState>,
    path: Option<String>,
    lang: LanguageIdentifier,
) -> axum::response::Response {
    let base = &state.base_path;
    let search_path = if let Some(p) = &path {
        base.join(p)
    } else {
        base.clone()
    };

    let tree = match cooklang_find::build_tree(&search_path) {
        Ok(tree) => tree,
        Err(e) => {
            tracing::error!("Failed to build recipe tree: {:?}", e);
            return error_page(lang, &state.url_prefix, &e);
        }
    };

    let mut items = Vec::new();

    for (name, child) in &tree.children {
        let is_dir = !child.children.is_empty();
        let item_path = {
            let url_path = child
                .recipe
                .as_ref()
                .and_then(|recipe| recipe.file_name())
                .unwrap_or_else(|| name.to_string());

            match &path {
                Some(p) => format!("{p}/{url_path}"),
                None => url_path.to_string(),
            }
        };

        // Extract tags, image, and is_menu if this is a recipe
        let (tags, image_path, is_menu) = if let Some(ref recipe) = child.recipe {
            // Get image path similar to how we do it in recipe_page
            let prefix = &state.url_prefix;
            let img_path = recipe.title_image().clone().and_then(|img| {
                if img.starts_with("http://") || img.starts_with("https://") {
                    Some(img)
                } else {
                    // Make path relative to base and accessible via /api/static
                    let img_path = camino::Utf8Path::new(&img);
                    if let Ok(relative) = img_path.strip_prefix(base) {
                        Some(format!("{prefix}/api/static/{relative}"))
                    } else if !img_path.is_absolute() {
                        Some(format!("{prefix}/api/static/{img_path}"))
                    } else {
                        img_path
                            .file_name()
                            .map(|name| format!("{prefix}/api/static/{name}"))
                    }
                }
            });
            (recipe.tags(), img_path, recipe.is_menu())
        } else {
            (Vec::new(), None, false)
        };

        items.push(RecipeItem {
            name: name.to_string(),
            path: item_path,
            is_directory: is_dir,
            count: if is_dir {
                count_recipes_tree(child)
            } else {
                None
            },
            description: None,
            tags,
            image_path,
            is_menu,
        });
    }

    items.sort_by(|a, b| match (a.is_directory, b.is_directory) {
        (true, false) => std::cmp::Ordering::Less,
        (false, true) => std::cmp::Ordering::Greater,
        _ => a.name.cmp(&b.name),
    });

    let todays_menu = if path.is_none() {
        crate::server::handlers::find_todays_menu(base, &tree)
    } else {
        None
    };

    let breadcrumbs = if let Some(p) = &path {
        p.split('/')
            .scan(String::new(), |acc, segment| {
                if !acc.is_empty() {
                    acc.push('/');
                }
                acc.push_str(segment);
                Some(Breadcrumb {
                    name: segment.to_string(),
                    path: acc.clone(),
                })
            })
            .collect()
    } else {
        vec![]
    };

    let current_name = if let Some(ref p) = path {
        p.split('/').next_back().unwrap_or("Recipes").to_string()
    } else {
        crate::server::i18n::LOCALES.lookup(&lang, "recipes-title")
    };

    let template = RecipesTemplate {
        active: "recipes".to_string(),
        current_name,
        breadcrumbs,
        items,
        todays_menu,
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
    };

    template.into_response()
}

fn count_recipes_tree(tree: &cooklang_find::RecipeTree) -> Option<usize> {
    let mut count = 0;

    for child in tree.children.values() {
        if !child.children.is_empty() {
            count += count_recipes_tree(child).unwrap_or(0);
        } else {
            count += 1;
        }
    }

    Some(count)
}

#[derive(Deserialize)]
struct RecipeQuery {
    scale: Option<f64>,
}

async fn recipe_page(
    Path(path): Path<String>,
    Query(query): Query<RecipeQuery>,
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> axum::response::Response {
    let scale = query.scale.unwrap_or(1.0);

    let recipe_path = Utf8PathBuf::from(&path);
    tracing::info!(
        "Looking for recipe at path: {}, extension: {:?}",
        path,
        recipe_path.extension()
    );

    let entry = match cooklang_find::get_recipe(vec![&state.base_path], &recipe_path) {
        Ok(entry) => entry,
        Err(e) => {
            tracing::error!("Recipe not found: {path}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Recipe not found: {path}: {e}"),
            );
        }
    };

    // Check if this is a menu file
    let actual_path = entry.path();
    tracing::info!(
        "Recipe path: {}, actual_path: {:?}, is_menu: {}",
        path,
        actual_path,
        entry.is_menu()
    );
    if entry.is_menu() {
        let prefix = state.url_prefix.clone();
        return match menu_page_handler(path, scale, entry, state, lang.clone()).await {
            Ok(template) => template.into_response(),
            Err(e) => error_page(lang, &prefix, &e),
        };
    }

    let recipe = match crate::util::parse_recipe_from_entry(&entry, scale) {
        Ok(recipe) => recipe,
        Err(e) => {
            tracing::error!("Failed to parse recipe: {e}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Failed to parse recipe: {e}"),
            );
        }
    };

    // Load aisle config for cooking mode ingredient sorting
    let aisle_content = if let Some(path) = &state.aisle_path {
        match tokio::fs::read_to_string(path).await {
            Ok(content) => content,
            Err(e) => {
                tracing::warn!("Failed to read aisle file from {:?}: {}", path, e);
                String::new()
            }
        }
    } else {
        String::new()
    };
    let aisle = cooklang::aisle::parse_lenient(&aisle_content)
        .into_output()
        .unwrap_or_default();

    let tags = entry.tags();

    // Get the image path if available
    let image_path = entry
        .title_image()
        .clone()
        .and_then(|img_path| get_image_path(&state.base_path, &state.url_prefix, img_path));

    let mut ingredients = Vec::new();
    let mut cookware = Vec::new();
    let mut sections = Vec::new();

    // Group ingredients by display name and merge quantities
    let mut grouped_ingredients: std::collections::HashMap<
        String,
        (
            cooklang::quantity::GroupedQuantity,
            Vec<&cooklang::model::Ingredient>,
        ),
    > = std::collections::HashMap::new();

    for entry in recipe.group_ingredients(crate::util::PARSER.converter()) {
        let ingredient = entry.ingredient;
        let display_name = ingredient.display_name().to_string();

        grouped_ingredients
            .entry(display_name)
            .and_modify(|(merged_qty, igrs)| {
                merged_qty.merge(&entry.quantity, crate::util::PARSER.converter());
                igrs.push(ingredient);
            })
            .or_insert_with(|| (entry.quantity.clone(), vec![ingredient]));
    }

    // Sort by name for consistent display
    let mut sorted_ingredients: Vec<_> = grouped_ingredients.into_iter().collect();
    sorted_ingredients.sort_by(|a, b| a.0.cmp(&b.0));

    for (display_name, (quantity, ingredient_list)) in sorted_ingredients {
        // Use the first ingredient's data for reference path and notes
        let first_ingredient = ingredient_list[0];
        let reference_path = first_ingredient.reference.as_ref().map(|r| {
            // For web URLs - always use forward slash
            if r.components.is_empty() {
                r.name.clone()
            } else {
                format!("{}/{}", r.components.join("/"), r.name)
            }
        });

        // Combine notes from all ingredients
        let combined_note = if ingredient_list.len() > 1 {
            let notes: Vec<_> = ingredient_list
                .iter()
                .filter_map(|i| i.note.as_ref())
                .collect();
            if notes.is_empty() {
                None
            } else {
                Some(
                    notes
                        .iter()
                        .map(|n| n.as_str())
                        .collect::<Vec<_>>()
                        .join(", "),
                )
            }
        } else {
            first_ingredient.note.clone()
        };

        // Format the merged quantity - show all quantities comma-separated
        let (formatted_quantity, formatted_unit) = if quantity.is_empty() {
            (None, None)
        } else {
            let quantities: Vec<_> = quantity
                .iter()
                .map(|q| {
                    let qty_str =
                        crate::util::format::format_quantity(q.value()).unwrap_or_default();
                    let unit_str = q.unit().as_ref().map(|u| u.to_string()).unwrap_or_default();
                    if unit_str.is_empty() {
                        qty_str
                    } else {
                        format!("{} {}", qty_str, unit_str)
                    }
                })
                .collect();
            (Some(quantities.join(", ")), None)
        };

        ingredients.push(IngredientData {
            name: display_name,
            quantity: formatted_quantity,
            unit: formatted_unit,
            note: combined_note,
            reference_path,
        });
    }

    for item in &recipe.group_cookware(crate::util::PARSER.converter()) {
        cookware.push(CookwareData {
            name: item.cookware.name.to_string(),
        });
    }

    let mut total_steps = 0;
    for section in &recipe.sections {
        let mut section_items = Vec::new();
        let mut section_ingredient_indices = std::collections::HashSet::new();
        let mut cooking_mode_ingredient_indices: Vec<usize> = Vec::new();
        let mut step_count = 0;

        for content in &section.content {
            use cooklang::Content;
            match content {
                Content::Step(step) => {
                    let mut step_items = Vec::new();
                    let mut step_ingredients = Vec::new();

                    for item in &step.items {
                        use crate::server::templates::{StepIngredient, StepItem};
                        use cooklang::Item;

                        match item {
                            Item::Text { value } => {
                                let parts: Vec<&str> = value.split('\n').collect();
                                for (i, part) in parts.iter().enumerate() {
                                    if i > 0 {
                                        step_items.push(StepItem::LineBreak);
                                    }
                                    if !part.is_empty() {
                                        step_items.push(StepItem::Text(part.to_string()));
                                    }
                                }
                            }
                            Item::Ingredient { index } => {
                                section_ingredient_indices.insert(*index);
                                cooking_mode_ingredient_indices.push(*index);
                                if let Some(ing) = recipe.ingredients.get(*index) {
                                    let reference_path = ing.reference.as_ref().map(|r| {
                                        // For web URLs - always use forward slash
                                        if r.components.is_empty() {
                                            r.name.clone()
                                        } else {
                                            format!("{}/{}", r.components.join("/"), r.name)
                                        }
                                    });

                                    step_items.push(StepItem::Ingredient {
                                        name: ing.name.to_string(),
                                        reference_path,
                                    });

                                    // Also add to step ingredients list
                                    step_ingredients.push(StepIngredient {
                                        name: ing.name.to_string(),
                                        quantity: ing.quantity.as_ref().and_then(|q| {
                                            crate::util::format::format_quantity(q.value())
                                        }),
                                        unit: ing
                                            .quantity
                                            .as_ref()
                                            .and_then(|q| q.unit().as_ref().map(|u| u.to_string())),
                                        note: ing.note.clone(),
                                    });
                                }
                            }
                            Item::Cookware { index } => {
                                if let Some(cw) = recipe.cookware.get(*index) {
                                    step_items.push(StepItem::Cookware(cw.name.to_string()));
                                }
                            }
                            Item::Timer { index } => {
                                if let Some(timer) = recipe.timers.get(*index) {
                                    let mut timer_text = String::new();

                                    // Add timer quantity and unit
                                    if let Some(quantity) = &timer.quantity {
                                        if let Some(formatted) =
                                            crate::util::format::format_quantity(quantity.value())
                                        {
                                            timer_text.push_str(&formatted);
                                        }
                                        if let Some(unit) = quantity.unit() {
                                            if !timer_text.is_empty() {
                                                timer_text.push(' ');
                                            }
                                            timer_text.push_str(unit);
                                        }
                                    }

                                    // If no duration info, just show "timer"
                                    if timer_text.is_empty() {
                                        timer_text = "timer".to_string();
                                    }

                                    step_items.push(StepItem::Timer(timer_text));
                                }
                            }
                            Item::InlineQuantity { index } => {
                                if let Some(q) = recipe.inline_quantities.get(*index) {
                                    let mut qty = crate::util::format::format_quantity(q.value())
                                        .unwrap_or_default();
                                    if let Some(unit) = q.unit() {
                                        if !qty.is_empty() {
                                            qty.push_str(&format!(" {unit}"));
                                        } else {
                                            qty = unit.to_string();
                                        }
                                    }
                                    step_items.push(StepItem::Quantity(qty));
                                }
                            }
                        }
                    }

                    let section_image_path = entry
                        .step_images()
                        .get(0, total_steps + step_count + 1)
                        .and_then(|img_path| {
                            get_image_path(
                                &state.base_path,
                                &state.url_prefix,
                                img_path.to_string(),
                            )
                        });

                    section_items.push(RecipeSectionItem::Step(StepData {
                        number: step_count + 1,
                        items: step_items,
                        ingredients: step_ingredients,
                        image_path: section_image_path,
                    }));
                    step_count += 1;
                }
                Content::Text(text) => {
                    // Skip list bullet items
                    if text.trim() != "-" {
                        section_items.push(RecipeSectionItem::Note(text.trim().to_string()));
                    }
                }
            }
        }

        // Only add sections that have items (steps or notes)
        if !section_items.is_empty() {
            use crate::server::templates::RecipeSection;

            // Collect and group ingredients used in this section
            let mut section_grouped_ingredients: std::collections::HashMap<
                String,
                (
                    cooklang::quantity::GroupedQuantity,
                    Vec<&cooklang::model::Ingredient>,
                ),
            > = std::collections::HashMap::new();

            for idx in section_ingredient_indices {
                if let Some(ingredient) = recipe.ingredients.get(idx) {
                    let display_name = ingredient.display_name().to_string();
                    let qty = if let Some(q) = &ingredient.quantity {
                        let mut grouped_qty = cooklang::quantity::GroupedQuantity::empty();
                        grouped_qty.add(q, crate::util::PARSER.converter());
                        grouped_qty
                    } else {
                        cooklang::quantity::GroupedQuantity::empty()
                    };

                    section_grouped_ingredients
                        .entry(display_name)
                        .and_modify(|(merged_qty, igrs)| {
                            if let Some(q) = &ingredient.quantity {
                                merged_qty.add(q, crate::util::PARSER.converter());
                            }
                            igrs.push(ingredient);
                        })
                        .or_insert_with(|| (qty, vec![ingredient]));
                }
            }

            // Sort section ingredients by name
            let mut sorted_section_ingredients: Vec<_> =
                section_grouped_ingredients.into_iter().collect();
            sorted_section_ingredients.sort_by(|a, b| a.0.cmp(&b.0));

            let mut section_ingredients = Vec::new();
            for (display_name, (quantity, ingredient_list)) in sorted_section_ingredients {
                let first_ingredient = ingredient_list[0];
                let reference_path = first_ingredient.reference.as_ref().map(|r| {
                    // For web URLs - always use forward slash
                    if r.components.is_empty() {
                        r.name.clone()
                    } else {
                        format!("{}/{}", r.components.join("/"), r.name)
                    }
                });

                // Combine notes from all ingredients in the section
                let combined_note = if ingredient_list.len() > 1 {
                    let notes: Vec<_> = ingredient_list
                        .iter()
                        .filter_map(|i| i.note.as_ref())
                        .collect();
                    if notes.is_empty() {
                        None
                    } else {
                        Some(
                            notes
                                .iter()
                                .map(|n| n.as_str())
                                .collect::<Vec<_>>()
                                .join(", "),
                        )
                    }
                } else {
                    first_ingredient.note.clone()
                };

                // Format the merged quantity
                let (formatted_quantity, formatted_unit) = if quantity.is_empty() {
                    (None, None)
                } else {
                    let quantities: Vec<_> = quantity
                        .iter()
                        .map(|q| {
                            let qty_str =
                                crate::util::format::format_quantity(q.value()).unwrap_or_default();
                            let unit_str =
                                q.unit().as_ref().map(|u| u.to_string()).unwrap_or_default();
                            if unit_str.is_empty() {
                                qty_str
                            } else {
                                format!("{} {}", qty_str, unit_str)
                            }
                        })
                        .collect();
                    (Some(quantities.join(", ")), None)
                };

                section_ingredients.push(IngredientData {
                    name: display_name,
                    quantity: formatted_quantity,
                    unit: formatted_unit,
                    note: combined_note,
                    reference_path,
                });
            }

            // Build uncombined ingredients for cooking mode, sorted by aisle order
            let mut cooking_mode_ingredients_with_key: Vec<(
                Option<(usize, usize)>,
                IngredientData,
            )> = Vec::new();
            for idx in &cooking_mode_ingredient_indices {
                if let Some(ingredient) = recipe.ingredients.get(*idx) {
                    if !ingredient.modifiers().should_be_listed() {
                        continue;
                    }
                    let sort_key = aisle.ingredient_sort_key(&ingredient.name);

                    let (formatted_quantity, formatted_unit) = if let Some(q) = &ingredient.quantity
                    {
                        let qty_str = crate::util::format::format_quantity(q.value());
                        let unit_str = q.unit().as_ref().map(|u| u.to_string());
                        (qty_str, unit_str)
                    } else {
                        (None, None)
                    };

                    cooking_mode_ingredients_with_key.push((
                        sort_key,
                        IngredientData {
                            name: ingredient.name.to_string(),
                            quantity: formatted_quantity,
                            unit: formatted_unit,
                            note: ingredient.note.clone(),
                            reference_path: None,
                        },
                    ));
                }
            }

            // Sort: aisle items first (by category_index, ingredient_index), then uncategorized at end
            cooking_mode_ingredients_with_key.sort_by(|a, b| match (&a.0, &b.0) {
                (Some(ka), Some(kb)) => ka.cmp(kb),
                (Some(_), None) => std::cmp::Ordering::Less,
                (None, Some(_)) => std::cmp::Ordering::Greater,
                (None, None) => a.1.name.cmp(&b.1.name),
            });

            let cooking_mode_ingredients: Vec<IngredientData> = cooking_mode_ingredients_with_key
                .into_iter()
                .map(|(_, data)| data)
                .collect();

            sections.push(RecipeSection {
                name: section.name.clone(),
                items: section_items.clone(),
                step_offset: total_steps,
                ingredients: section_ingredients,
                cooking_mode_ingredients,
            });
            total_steps += step_count;
        }
    }

    let breadcrumbs: Vec<String> = path
        .split('/')
        .map(|s| s.trim_end_matches(".cook").to_string())
        .collect();

    let metadata = if recipe.metadata.map.is_empty() {
        None
    } else {
        // Get standard metadata fields (handle both string and number types)
        let get_field = |key: &str| -> Option<String> {
            recipe.metadata.get(key).and_then(|v| {
                if let Some(s) = v.as_str() {
                    Some(s.to_string())
                } else if let Some(n) = v.as_i64() {
                    Some(n.to_string())
                } else {
                    v.as_f64().map(crate::util::format::format_number)
                }
            })
        };

        let mut custom_metadata = Vec::new();
        for (key, value) in recipe.metadata.map_filtered() {
            if let (Some(key_str), Some(val_str)) = (key.as_str(), value.as_str()) {
                if key_str.starts_with("source.") || key_str.starts_with("time.") {
                    continue;
                }

                custom_metadata.push((key_str.to_string(), val_str.to_string()));
            }
        }

        Some(RecipeMetadata {
            servings: get_field("servings"),
            time: get_field("time"),
            difficulty: get_field("difficulty"),
            course: get_field("course"),
            prep_time: get_field("prep time")
                .or_else(|| get_field("prep_time"))
                .or_else(|| get_field("preptime"))
                .or_else(|| get_field("time.prep")),
            cook_time: get_field("cook time")
                .or_else(|| get_field("cook_time"))
                .or_else(|| get_field("cooktime"))
                .or_else(|| get_field("time.cook")),
            cuisine: get_field("cuisine"),
            diet: get_field("diet"),
            author: get_field("author").or_else(|| get_field("source.author")),
            description: get_field("description"),
            source: get_field("source").or_else(|| get_field("source.name")),
            source_url: get_field("source.url"),
            custom: custom_metadata,
        })
    };

    // Use title from metadata if available, otherwise use filename
    let recipe_name = recipe
        .metadata
        .get("title")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .unwrap_or_else(|| {
            path.split('/')
                .next_back()
                .unwrap_or(&path)
                .replace(".cook", "")
        });

    let template = RecipeTemplate {
        active: "recipes".to_string(),
        recipe: RecipeData {
            name: recipe_name,
            metadata,
        },
        recipe_path: path,
        breadcrumbs,
        scale,
        tags,
        ingredients,
        cookware,
        sections,
        image_path,
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
    };

    template.into_response()
}

async fn edit_page(
    Path(path): Path<String>,
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> axum::response::Response {
    tracing::info!("Edit page requested for path: {}", path);

    // Validate path to prevent directory traversal
    let path_check = Utf8Path::new(&path);
    if !path_check
        .components()
        .all(|c| matches!(c, Utf8Component::Normal(_)))
    {
        tracing::error!("Invalid path: {path}");
        return error_page(lang, &state.url_prefix, format!("Invalid path: {path}"));
    }

    let recipe_path = Utf8PathBuf::from(&path);

    // Find the actual file
    let entry = match cooklang_find::get_recipe(vec![&state.base_path], &recipe_path) {
        Ok(entry) => entry,
        Err(e) => {
            tracing::error!("Recipe not found: {path}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Recipe not found: {path}: {e}"),
            );
        }
    };

    let file_path = match entry.path() {
        Some(p) => p,
        None => {
            tracing::error!("Recipe has no file path: {path}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Recipe has no file path: {path}"),
            );
        }
    };

    // Read raw content
    let content = match tokio::fs::read_to_string(file_path).await {
        Ok(content) => content,
        Err(e) => {
            tracing::error!("Failed to read recipe file: {e}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Failed to read recipe file: {e}"),
            );
        }
    };

    // Get recipe name from path
    let recipe_name = path
        .split('/')
        .next_back()
        .unwrap_or(&path)
        .replace(".cook", "")
        .replace(".menu", "");

    let template = crate::server::templates::EditTemplate {
        active: "recipes".to_string(),
        recipe_name,
        recipe_path: path,
        content,
        base_path: state.base_path.to_string(),
        tr: crate::server::templates::Tr::new(lang),
        prefix: state.url_prefix.clone(),
    };

    template.into_response()
}

#[derive(Deserialize, Default)]
struct NewPageQuery {
    error: Option<String>,
    filename: Option<String>,
}

async fn new_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Query(query): Query<NewPageQuery>,
) -> impl askama_axum::IntoResponse {
    crate::server::templates::NewTemplate {
        active: "recipes".to_string(),
        tr: Tr::new(lang),
        error: query.error,
        filename: query.filename,
        prefix: state.url_prefix.clone(),
    }
}

#[derive(Deserialize)]
struct NewRecipeForm {
    filename: String,
}

/// Helper to build redirect URL with error message
fn new_page_error(prefix: &str, error: &str, filename: &str) -> axum::response::Response {
    let encoded_error = urlencoding::encode(error);
    let encoded_filename = urlencoding::encode(filename);
    axum::response::Redirect::to(&format!(
        "{prefix}/new?error={}&filename={}",
        encoded_error, encoded_filename
    ))
    .into_response()
}

/// Validates that the request originated from the same host (CSRF protection)
fn validate_same_origin(headers: &HeaderMap, host: &str) -> bool {
    // Check Origin header first (preferred for CSRF protection)
    if let Some(origin) = headers.get(header::ORIGIN) {
        if let Ok(origin_str) = origin.to_str() {
            // Origin format is scheme://host[:port]
            if let Ok(origin_url) = url::Url::parse(origin_str) {
                if let Some(origin_host) = origin_url.host_str() {
                    let origin_with_port = if let Some(port) = origin_url.port() {
                        format!("{}:{}", origin_host, port)
                    } else {
                        origin_host.to_string()
                    };
                    return origin_with_port == host || origin_host == host;
                }
            }
        }
        return false;
    }

    // Fallback to Referer header (less reliable but better than nothing)
    if let Some(referer) = headers.get(header::REFERER) {
        if let Ok(referer_str) = referer.to_str() {
            if let Ok(referer_url) = url::Url::parse(referer_str) {
                if let Some(referer_host) = referer_url.host_str() {
                    let referer_with_port = if let Some(port) = referer_url.port() {
                        format!("{}:{}", referer_host, port)
                    } else {
                        referer_host.to_string()
                    };
                    return referer_with_port == host || referer_host == host;
                }
            }
        }
        return false;
    }

    // No Origin or Referer header - reject for safety
    // (though browsers should always send one for form submissions)
    false
}

async fn create_recipe(
    State(state): State<Arc<AppState>>,
    Host(host): Host,
    headers: HeaderMap,
    Form(form): Form<NewRecipeForm>,
) -> impl IntoResponse {
    // CSRF protection: verify request came from same origin
    if !validate_same_origin(&headers, &host) {
        tracing::warn!("CSRF validation failed for create_recipe request");
        return (StatusCode::FORBIDDEN, "Invalid request origin").into_response();
    }

    let original_filename = form.filename.clone();

    // Validate input before sanitization
    if form.filename.trim().is_empty() {
        return new_page_error(
            &state.url_prefix,
            "Recipe name cannot be empty",
            &original_filename,
        );
    }

    // Sanitize path - allow alphanumeric, space, dash, underscore, and forward slash
    let recipe_path: String = form
        .filename
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_' || *c == '/')
        .collect();

    // Clean up path: remove leading/trailing slashes, collapse multiple slashes
    let recipe_path = recipe_path
        .trim_matches('/')
        .split('/')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("/");

    if recipe_path.is_empty() {
        return new_page_error(
            &state.url_prefix,
            "Recipe name cannot be empty",
            &original_filename,
        );
    }

    let file_path = state.base_path.join(format!("{}.cook", recipe_path));

    // Security: Validate path structure before any filesystem operations
    // Check that the constructed path, when normalized, stays within base_path
    let base_path_clone = state.base_path.clone();
    let base_canonical =
        match tokio::task::spawn_blocking(move || base_path_clone.canonicalize_utf8()).await {
            Ok(Ok(p)) => p,
            _ => {
                return new_page_error(
                    &state.url_prefix,
                    "Internal error: invalid base path",
                    &original_filename,
                );
            }
        };

    // Validate parent path components don't escape base_path
    // We do this by checking the joined path doesn't contain .. after normalization
    let normalized_path = file_path.as_str().replace("\\", "/");
    if normalized_path.contains("/../") || normalized_path.ends_with("/..") {
        tracing::warn!("Path traversal attempt detected in: {}", recipe_path);
        return new_page_error(&state.url_prefix, "Invalid recipe path", &original_filename);
    }

    // For the file path, we check the parent directory
    if let Some(parent) = file_path.parent() {
        // Create parent directories if they don't exist
        if !parent.exists() {
            if let Err(e) = tokio::fs::create_dir_all(parent).await {
                tracing::error!("Failed to create directories: {}", e);
                return new_page_error(&state.url_prefix, "Failed to create directory. Check that the recipes folder has write permissions.", &original_filename);
            }
        }

        // Now verify the created parent is under base_path
        let parent_owned = parent.to_owned();
        match tokio::task::spawn_blocking(move || parent_owned.canonicalize_utf8()).await {
            Ok(Ok(parent_canonical)) => {
                if !parent_canonical.starts_with(&base_canonical) {
                    tracing::warn!(
                        "Path traversal attempt: {} not under {}",
                        parent_canonical,
                        base_canonical
                    );
                    // Clean up the created directory if it's outside base_path
                    let _ = tokio::fs::remove_dir_all(parent).await;
                    return new_page_error(
                        &state.url_prefix,
                        "Invalid recipe path",
                        &original_filename,
                    );
                }
            }
            _ => {
                return new_page_error(
                    &state.url_prefix,
                    "Invalid recipe path",
                    &original_filename,
                );
            }
        }
    }

    // Get the recipe name (last component of path) for the title
    let recipe_name = recipe_path
        .split('/')
        .next_back()
        .unwrap_or(&recipe_path)
        .replace(['-', '_'], " ");

    // Create recipe with YAML frontmatter
    let template = format!("---\ntitle: {}\n---\n\n", recipe_name);

    // Use OpenOptions with create_new to atomically check existence and create
    // This prevents TOCTOU race conditions
    use tokio::io::AsyncWriteExt;
    let file = tokio::fs::OpenOptions::new()
        .write(true)
        .create_new(true) // Fails if file exists - atomic check + create
        .open(&file_path)
        .await;

    match file {
        Ok(mut f) => {
            if let Err(e) = f.write_all(template.as_bytes()).await {
                tracing::error!("Failed to write recipe: {}", e);
                return new_page_error(
                    &state.url_prefix,
                    "Failed to write recipe file",
                    &original_filename,
                );
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            return new_page_error(
                &state.url_prefix,
                "A recipe with this name already exists",
                &original_filename,
            );
        }
        Err(e) => {
            tracing::error!("Failed to create recipe file: {}", e);
            return new_page_error(
                &state.url_prefix,
                "Failed to create recipe file",
                &original_filename,
            );
        }
    }

    // Redirect to editor
    axum::response::Redirect::to(&format!("{}/edit/{}.cook", state.url_prefix, recipe_path))
        .into_response()
}

fn get_image_path(base_path: &Utf8PathBuf, prefix: &str, img_path: String) -> Option<String> {
    tracing::debug!("Recipe image path from entry: {}", img_path);
    // If it's a URL, use it directly
    if img_path.starts_with("http://") || img_path.starts_with("https://") {
        Some(img_path)
    } else {
        // For file paths, we need to make them relative to the base path and accessible via /api/static
        let img_path = camino::Utf8Path::new(&img_path);

        // Try to strip the base_path prefix to get a relative path
        if let Ok(relative) = img_path.strip_prefix(base_path) {
            let result = format!("{prefix}/api/static/{relative}");
            tracing::debug!("Image path relative to base: {}", result);
            Some(result)
        } else if !img_path.is_absolute() {
            Some(format!("{prefix}/api/static/{img_path}"))
        } else {
            img_path
                .file_name()
                .map(|name| format!("{prefix}/api/static/{name}"))
        }
    }
}

async fn menu_page_handler(
    path: String,
    scale: f64,
    entry: cooklang_find::RecipeEntry,
    state: Arc<AppState>,
    lang: LanguageIdentifier,
) -> Result<MenuTemplate, String> {
    let recipe = crate::util::parse_recipe_from_entry(&entry, scale).map_err(|e| {
        tracing::error!("Failed to parse menu: {e}");
        format!("Failed to parse menu: {e}")
    })?;

    // Get the image path if available
    let image_path = entry.title_image().clone().and_then(|img_path| {
        if img_path.starts_with("http://") || img_path.starts_with("https://") {
            Some(img_path)
        } else {
            let img_path = camino::Utf8Path::new(&img_path);
            let prefix = &state.url_prefix;
            if let Ok(relative) = img_path.strip_prefix(&state.base_path) {
                Some(format!("{prefix}/api/static/{relative}"))
            } else if !img_path.is_absolute() {
                Some(format!("{prefix}/api/static/{img_path}"))
            } else {
                img_path
                    .file_name()
                    .map(|name| format!("{prefix}/api/static/{name}"))
            }
        }
    });

    let breadcrumbs: Vec<String> = path.split('/').map(|s| s.to_string()).collect();

    // Parse sections and content
    let mut sections = Vec::new();

    for section in &recipe.sections {
        let section_name = section.name.clone();
        let mut lines = Vec::new();

        for content in &section.content {
            use cooklang::Content;
            if let Content::Step(step) = content {
                // Build the full step content first
                let mut step_items = Vec::new();
                let mut current_text = String::new();

                for item in &step.items {
                    use crate::server::templates::MenuSectionItem;
                    use cooklang::Item;

                    match item {
                        Item::Text { value } => {
                            // Check if this is an isolated dash (bullet marker)
                            if value == "-" {
                                // Bullet marker - complete current line and start new one
                                if !current_text.is_empty() {
                                    step_items.push(MenuSectionItem::Text(current_text.clone()));
                                    current_text.clear();
                                }
                                if !step_items.is_empty() {
                                    lines.push(step_items.clone());
                                    step_items.clear();
                                }
                            } else {
                                // Split on newlines to preserve line breaks
                                let parts: Vec<&str> = value.split('\n').collect();
                                for (i, part) in parts.iter().enumerate() {
                                    if i > 0 {
                                        // Newline encountered - flush current text and line
                                        if !current_text.is_empty() {
                                            step_items
                                                .push(MenuSectionItem::Text(current_text.clone()));
                                            current_text.clear();
                                        }
                                        if !step_items.is_empty() {
                                            lines.push(step_items.clone());
                                            step_items.clear();
                                        }
                                    }
                                    if !part.is_empty() {
                                        current_text.push_str(part);
                                    }
                                }
                            }
                        }
                        Item::Ingredient { index } => {
                            // First, add any pending text
                            if !current_text.is_empty() {
                                step_items.push(MenuSectionItem::Text(current_text.clone()));
                                current_text.clear();
                            }

                            if let Some(ing) = recipe.ingredients.get(*index) {
                                // Check if this is a recipe reference using the reference field
                                if let Some(ref recipe_ref) = ing.reference {
                                    // This is a recipe reference
                                    let recipe_scale =
                                        ing.quantity.as_ref().and_then(|q| match q.value() {
                                            cooklang::Value::Number(n) => Some(n.value()),
                                            _ => None,
                                        });

                                    // Apply menu scaling to the recipe reference
                                    let final_scale = recipe_scale.map(|s| s * scale);

                                    // Build the full path from components
                                    // For web URLs - always use forward slash
                                    let name = if recipe_ref.components.is_empty() {
                                        recipe_ref.name.clone()
                                    } else {
                                        format!(
                                            "{}/{}",
                                            recipe_ref.components.join("/"),
                                            recipe_ref.name
                                        )
                                    };

                                    step_items.push(MenuSectionItem::RecipeReference {
                                        name,
                                        scale: final_scale,
                                    });
                                } else {
                                    // Regular ingredient
                                    let quantity = ing.quantity.as_ref().and_then(|q| {
                                        crate::util::format::format_quantity(q.value())
                                    });
                                    let unit = ing
                                        .quantity
                                        .as_ref()
                                        .and_then(|q| q.unit().as_ref().map(|u| u.to_string()));

                                    step_items.push(MenuSectionItem::Ingredient {
                                        name: ing.name.to_string(),
                                        quantity,
                                        unit,
                                    });
                                }
                            }
                        }
                        _ => {} // Ignore other items in menu files
                    }
                }

                // Add any remaining content as a line
                if !current_text.is_empty() {
                    step_items.push(MenuSectionItem::Text(current_text));
                }
                if !step_items.is_empty() {
                    lines.push(step_items);
                }
            }
        }

        // Filter out empty lines (lines that are only whitespace text)
        lines.retain(|line| {
            !line
                .iter()
                .all(|item| matches!(item, MenuSectionItem::Text(t) if t.trim().is_empty()))
        });

        if !lines.is_empty() {
            sections.push(MenuSection {
                name: section_name,
                lines,
            });
        }
    }

    // Get metadata
    let metadata = if recipe.metadata.map.is_empty() {
        None
    } else {
        let get_field = |key: &str| -> Option<String> {
            recipe.metadata.get(key).and_then(|v| {
                if let Some(s) = v.as_str() {
                    Some(s.to_string())
                } else if let Some(n) = v.as_i64() {
                    Some(n.to_string())
                } else {
                    v.as_f64().map(crate::util::format::format_number)
                }
            })
        };

        let mut custom_metadata = Vec::new();
        for (key, value) in recipe.metadata.map_filtered() {
            if let (Some(key_str), Some(val_str)) = (key.as_str(), value.as_str()) {
                custom_metadata.push((key_str.to_string(), val_str.to_string()));
            }
        }

        Some(RecipeMetadata {
            servings: get_field("servings"),
            time: get_field("time"),
            difficulty: get_field("difficulty"),
            course: get_field("course"),
            prep_time: get_field("prep time")
                .or_else(|| get_field("prep_time"))
                .or_else(|| get_field("preptime")),
            cook_time: get_field("cook time")
                .or_else(|| get_field("cook_time"))
                .or_else(|| get_field("cooktime")),
            cuisine: get_field("cuisine"),
            diet: get_field("diet"),
            author: get_field("author").or_else(|| get_field("source.author")),
            description: get_field("description"),
            source: get_field("source").or_else(|| get_field("source.name")),
            source_url: get_field("source.url"),
            custom: custom_metadata,
        })
    };

    let menu_name = recipe
        .metadata
        .get("title")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .unwrap_or_else(|| {
            path.split('/')
                .next_back()
                .unwrap_or(&path)
                .replace(".menu", "")
        });

    let template = MenuTemplate {
        active: "recipes".to_string(),
        name: menu_name,
        recipe_path: path,
        breadcrumbs,
        scale,
        metadata,
        sections,
        image_path,
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
    };

    Ok(template)
}

async fn shopping_list_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> impl askama_axum::IntoResponse {
    ShoppingListTemplate {
        active: "shopping".to_string(),
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
    }
}

async fn pantry_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> Result<impl askama_axum::IntoResponse, StatusCode> {
    // Load pantry configuration
    let pantry_path = state.pantry_path.as_ref();

    let mut sections = Vec::new();

    if let Some(path) = pantry_path {
        if let Ok(content) = tokio::fs::read_to_string(path).await {
            let result = cooklang::pantry::parse_lenient(&content);

            if let Some(pantry_conf) = result.output() {
                // Convert pantry data to template format
                for (section_name, items) in &pantry_conf.sections {
                    let mut pantry_items = Vec::new();

                    for item in items {
                        pantry_items.push(crate::server::templates::PantryItem {
                            name: item.name().to_string(),
                            quantity: item.quantity().map(|q| q.to_string()),
                            bought: item.bought().map(|b| b.to_string()),
                            expire: item.expire().map(|e| e.to_string()),
                            low: item.low().map(|l| l.to_string()),
                        });
                    }

                    sections.push(crate::server::templates::PantrySection {
                        name: section_name.clone(),
                        items: pantry_items,
                    });
                }
            }
        }
    }

    Ok(PantryTemplate {
        active: "pantry".to_string(),
        configured: pantry_path.is_some(),
        sections,
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
    })
}

async fn preferences_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
) -> impl askama_axum::IntoResponse {
    #[cfg(feature = "sync")]
    let (sync_logged_in, sync_email, sync_syncing) = state.sync_status().await;
    #[cfg(not(feature = "sync"))]
    let (sync_logged_in, sync_email, sync_syncing) = (false, None, false);

    PreferencesTemplate {
        active: "preferences".to_string(),
        aisle_path: state
            .aisle_path
            .as_ref()
            .map(|p| p.to_string())
            .unwrap_or_else(|| "Not configured".to_string()),
        pantry_path: state
            .pantry_path
            .as_ref()
            .map(|p| p.to_string())
            .unwrap_or_else(|| "Not configured".to_string()),
        base_path: state.base_path.to_string(),
        version: format!("{} - in food we trust", env!("CARGO_PKG_VERSION")),
        tr: Tr::new(lang),
        sync_enabled: cfg!(feature = "sync"),
        sync_logged_in,
        sync_email,
        sync_syncing,
        prefix: state.url_prefix.clone(),
    }
}