Dashboard Temp Share Shortlinks Frames API

HTMLify

index.html
Views: 105 | Author: karbonsites
   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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChefMaster Pro - Recipe Management</title>
    <link href="https://fonts.googleapis.com/css2?family=Segoe+UI:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        /* === Global & Typography === */
        :root {
            --primary-color: #4f46e5; /* Indigo 600 */
            --success-color: #10b981; /* Emerald 500 */
            --bg-color: #f9fafb; /* Gray 50 */
            --card-bg: #ffffff;
            --text-color: #1f2937; /* Gray 800 */
            --border-color: #e5e7eb; /* Gray 200 */
            --currency-symbol: 'AED'; /* Default currency set to AED as requested */
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            line-height: 1.6;
        }

        h1, h2, h3 {
            font-weight: 600;
        }

        /* === Layout Structure === */
        .app-container {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar (Desktop) */
        #sidebar {
            width: 250px;
            background-color: var(--card-bg);
            border-right: 1px solid var(--border-color);
            padding: 20px 0;
            transition: transform 0.3s ease-in-out;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
            flex-shrink: 0; /* Prevent shrinking on narrow desktop */
        }

        .sidebar-header {
            padding: 0 20px 20px;
            font-size: 1.4rem;
            font-weight: 700;
            color: var(--primary-color);
            border-bottom: 1px solid var(--border-color);
            margin-bottom: 20px;
        }

        .nav-item {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.2s, color 0.2s;
            font-size: 1rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .nav-item:hover {
            background-color: #f3f4f6;
        }

        .nav-item.active {
            background-color: var(--primary-color);
            color: white;
            font-weight: 600;
        }

        /* Main Content Area */
        #main-content {
            flex-grow: 1;
            padding: 30px;
            overflow-y: auto;
        }

        .content-section {
            display: none; /* Hidden by default */
            animation: fadeIn 0.4s ease-out;
        }

        .content-section.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Cards and Inputs */
        .card {
            background: var(--card-bg);
            border-radius: 8px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
            padding: 25px;
            margin-bottom: 25px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            font-size: 0.9rem;
        }

        input[type="text"], input[type="number"], select, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            transition: border-color 0.2s;
            font-family: inherit;
        }

        input:focus, select:focus, textarea:focus {
            border-color: var(--primary-color);
            outline: none;
        }
        
        textarea {
            resize: vertical;
        }

        /* Buttons */
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: background-color 0.2s, transform 0.1s;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background-color: #4338ca; /* Indigo 700 */
        }

        .btn-success {
            background-color: var(--success-color);
            color: white;
        }
        .btn-success:hover {
            background-color: #059669; /* Emerald 600 */
        }

        .btn-danger {
            background-color: #ef4444;
            color: white;
        }
        .btn-danger:hover {
            background-color: #dc2626;
        }

        /* Tables */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        th {
            background-color: #f3f4f6;
            font-weight: 600;
        }

        /* Recipe Creation Specifics */
        .ingredient-row {
            display: grid;
            grid-template-columns: 3fr 1fr 1fr 0.5fr;
            gap: 10px;
            margin-bottom: 10px;
            align-items: center;
        }

        .ingredient-row > div:last-child {
            text-align: center; /* For the delete button */
        }

        .total-cost-display {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary-color);
            text-align: right;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 2px solid var(--border-color);
        }

        /* Recipe Master Dashboard */
        .recipe-list-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px;
            border: 1px solid var(--border-color);
            margin-bottom: 10px;
            border-radius: 6px;
            transition: box-shadow 0.2s;
        }

        .recipe-list-item:hover {
            box-shadow: 0 0 10px rgba(79, 70, 229, 0.1);
        }

        .recipe-info h3 {
            margin-bottom: 5px;
        }

        .recipe-actions button {
            margin-left: 8px;
        }

        /* Raw Materials Management */
        #raw-materials-table tbody tr td:last-child {
            text-align: center;
        }

        /* Currency Dropdown Styling */
        #currency-selector-container {
            padding: 10px 20px;
            border-bottom: 1px solid var(--border-color);
            text-align: center;
        }
        #currency-selector-container label {
            font-size: 0.85rem;
            margin-right: 10px;
            color: #6b7280;
        }

        /* Print Styling */
        @media print {
            body {
                background-color: white;
                color: black;
            }
            #sidebar, .nav-item, .btn, .print-controls, .recipe-actions, .form-group, .ingredient-row, .recipe-selector, #currency-selector-container {
                display: none !important;
            }
            .app-container {
                display: block;
                min-height: auto;
                padding: 0;
            }
            #main-content {
                padding: 0;
            }
            .content-section {
                display: block !important;
                box-shadow: none !important;
                page-break-before: auto;
            }
            h1, h2 {
                color: black !important;
            }
            .card {
                box-shadow: none !important;
                border: 1px solid #ccc;
                page-break-inside: avoid;
            }
            table {
                page-break-inside: avoid;
            }
            th, td {
                border-color: #ccc;
            }
        }

        /* --- Mobile Responsiveness --- */
        
        /* Tablet/Small Desktop (768px < width <= 1024px) */
        @media (max-width: 1024px) {
             .ingredient-row {
                /* Adjust columns to fit unit cost and make delete button fit better */
                grid-template-columns: 2fr 1fr 1fr 0.7fr 0.5fr;
            }
            .ingredient-row > div:nth-child(4) { /* Subtotal column */
                grid-column: span 1;
            }
            .ingredient-row > div:last-child { /* Delete button column */
                grid-column: 5 / 6;
            }
            
            /* Adjust header row for mobile layout */
            .ingredient-row.header-row div {
                display: none; /* Hide header column labels */
            }
            .ingredient-row.header-row div:nth-child(1) { display: block; } /* Show Material label */
            .ingredient-row.header-row div:nth-child(2) { display: block; } /* Show Qty label */
            .ingredient-row.header-row div:nth-child(3) { display: block; } /* Show Unit Cost label */
            .ingredient-row.header-row div:nth-child(4) { display: block; } /* Show Subtotal label */

            /* Since we can't use CSS 'content' easily on divs inside grid without significant rework, 
               we will simplify the mobile header row to just show key labels for alignment */
            .ingredient-row.header-row {
                display: grid;
                grid-template-columns: 2fr 1fr 1fr 0.7fr 0.5fr;
                font-weight: 600;
                color: #6b7280;
            }
            .ingredient-row.header-row > div {
                display: block !important; /* Make sure labels show */
                padding: 0; margin: 0;
            }
            .ingredient-row.header-row div:nth-child(5) { grid-column: 5 / 6; text-align: center; }
            
            /* Hide unnecessary header labels that overlap */
            .ingredient-row.header-row div:nth-child(3), .ingredient-row.header-row div:nth-child(4) { display: none !important; } 
            .ingredient-row.header-row div:nth-child(1) { grid-column: 1 / 3; } /* Material span 2 columns */
            .ingredient-row.header-row div:nth-child(2) { grid-column: 3 / 4; } /* Qty */
            .ingredient-row.header-row div:nth-child(5) { grid-column: 5 / 6; } /* Action */
        }

        /* Mobile View (max-width: 768px) */
        @media (max-width: 768px) {
            .app-container {
                flex-direction: column;
            }
            #sidebar {
                width: 100%;
                height: auto;
                padding: 10px 0;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                border-right: none;
                border-bottom: 1px solid var(--border-color);
            }
            .sidebar-header {
                display: none; /* Hide header on mobile */
            }
            .nav-list {
                display: flex;
                justify-content: space-around;
                padding: 0 10px;
                gap: 5px;
                overflow-x: auto; /* Allow horizontal scroll if many items */
                white-space: nowrap;
            }
            .nav-item {
                padding: 10px 10px;
                flex-direction: column;
                gap: 2px;
                font-size: 0.85rem;
                justify-content: center;
                flex: 1 1 auto; /* Allow items to grow/shrink slightly */
                min-width: 80px;
                text-align: center;
            }
            #main-content {
                padding: 20px 15px;
            }
            .total-cost-display {
                font-size: 1.3rem;
            }
            
            /* Mobile Ingredient Row adjustments */
            .ingredient-row {
                grid-template-columns: 2fr 1fr 1fr 0.5fr; /* Reduced complexity */
            }
            .ingredient-row > div:nth-child(4) { /* Hide Unit Cost display on mobile */
                display: none;
            }
            .ingredient-row > div:last-child { /* Move delete button to share a column with subtotal span if needed */
                grid-column: 4 / 5; 
            }

            /* Header adjustments for mobile */
            .ingredient-row.header-row {
                grid-template-columns: 2fr 1fr 1fr 0.5fr;
            }
            .ingredient-row.header-row div:nth-child(1) { grid-column: 1 / 3; } /* Material */
            .ingredient-row.header-row div:nth-child(2) { grid-column: 3 / 4; } /* Qty */
            .ingredient-row.header-row div:nth-child(3), .ingredient-row.header-row div:nth-child(4) { display: none !important; } /* Hide Unit Cost & Subtotal headers */
            .ingredient-row.header-row div:nth-child(5) { grid-column: 4 / 5; text-align: center; } /* Action */

            /* Raw Materials split layout on mobile */
            #raw-materials .card-container {
                display: block !important;
            }
            #raw-materials .card {
                width: 100%;
            }
            
            /* Recipe Master Action Bar */
            .print-controls {
                display: flex !important;
                flex-direction: column;
                gap: 10px;
            }
            .print-controls button {
                width: 100%;
            }

            /* Recipe List Item Stack */
            .recipe-list-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            .recipe-actions {
                width: 100%;
                display: flex;
                justify-content: flex-end;
            }
            .recipe-actions button {
                flex: 1;
                text-align: center;
            }
        }
    </style>
</head>
<body>

    <div class="app-container">
        <!-- Sidebar Navigation -->
        <aside id="sidebar">
            <div id="currency-selector-container">
                <label for="currency-selector">Cost Currency:</label>
                <select id="currency-selector" onchange="updateCurrencySettings()">
                    <option value="AED">AED (United Arab Emirates Dirham)</option>
                    <option value="USD">USD (US Dollar)</option>
                    <option value="EUR">EUR (Euro)</option>
                    <option value="GBP">GBP (British Pound)</option>
                    <option value="JPY">JPY (Japanese Yen)</option>
                    <option value="INR">INR (Indian Rupee)</option>
                    <option value="CAD">CAD (Canadian Dollar)</option>
                    <option value="AUD">AUD (Australian Dollar)</option>
                    <option value="CHF">CHF (Swiss Franc)</option>
                    <option value="SGD">SGD (Singapore Dollar)</option>
                    <option value="SAR">SAR (Saudi Riyal)</option>
                </select>
            </div>
            <div class="sidebar-header">ChefMaster Pro</div>
            <nav class="nav-list">
                <div class="nav-item active" data-section="create-recipe" onclick="switchSection('create-recipe')">
                    <span>Create Recipe</span>
                </div>
                <div class="nav-item" data-section="recipe-master" onclick="switchSection('recipe-master')">
                    <span>Recipe Master</span>
                </div>
                <div class="nav-item" data-section="raw-materials" onclick="switchSection('raw-materials')">
                    <span>Raw Materials</span>
                </div>
            </nav>
        </aside>

        <!-- Main Content Area -->
        <main id="main-content">

            <!-- 1. Create Recipe Section -->
            <section id="create-recipe" class="content-section active">
                <h2>Create New Recipe</h2>
                <div class="card">
                    <div class="form-group">
                        <label for="recipe-name">Recipe Name</label>
                        <input type="text" id="recipe-name" placeholder="e.g., Classic Beef Stroganoff">
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div class="form-group">
                            <label for="recipe-yield">Yield (Portions)</label>
                            <input type="number" id="recipe-yield" value="1" min="1">
                        </div>
                        <div class="form-group">
                            <label for="recipe-category">Category</label>
                            <select id="recipe-category">
                                <option value="Main">Main Course</option>
                                <option value="Dessert">Dessert</option>
                                <option value="Starter">Starter</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- NEW: Auto-Scaling Input -->
                    <div class="form-group">
                        <label for="auto-scale-target">Auto-Calculate / Scale Yield To:</label>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                             <input type="number" id="auto-scale-target" min="1" step="1" placeholder="Enter target portion count (e.g., 80)" oninput="autoCalculateYield()">
                             <button class="btn btn-primary" style="background-color: #3b82f6;" onclick="resetYieldFromScale()">
                                Reset Yield
                             </button>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="recipe-remarks">Remarks</label>
                        <textarea id="recipe-remarks" rows="3" placeholder="Notes on preparation or serving suggestions..."></textarea>
                    </div>

                    <h3>Ingredients (Costed at <span id="current-display-currency">AED</span>)</h3>
                    <div id="ingredients-container">
                        <!-- Ingredient rows dynamically added here -->
                        <div class="ingredient-row header-row" style="font-weight: 600; color: #6b7280;">
                            <div>Material</div>
                            <div>Qty</div>
                            <div>Unit Cost</div>
                            <div>Subtotal</div>
                            <div></div>
                        </div>
                    </div>
                    <button class="btn btn-success" onclick="addIngredientRow()" style="margin-top: 15px;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                        Add Ingredient
                    </button>
                    
                    <div class="total-cost-display">
                        Total Cost: <span id="total-recipe-cost">AED 0.00</span>
                    </div>
                    
                    <div style="text-align: right; margin-top: 20px;">
                        <button class="btn btn-primary" onclick="saveRecipe()">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>
                            Save Recipe
                        </button>
                    </div>
                </div>
            </section>

            <!-- 2. Recipe Master (Dashboard) Section -->
            <section id="recipe-master" class="content-section">
                <h2>Recipe Master Dashboard</h2>
                <div class="print-controls" style="display: flex; gap: 10px; margin-bottom: 20px;">
                    <button class="btn btn-primary" onclick="printSelectedRecipes()" style="background-color: #6366f1;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                        Print Selected Reports
                    </button>
                    <button class="btn btn-primary" onclick="viewAllRecipeDetails()" style="background-color: #1e40af;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>
                        View All Cost Breakdowns
                    </button>
                </div>
                
                <div id="recipe-list-container">
                    <!-- Recipes listed here -->
                </div>
            </section>

            <!-- 3. Raw Materials Management Section -->
            <section id="raw-materials" class="content-section">
                <h2>Raw Materials Management</h2>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px;" class="card-container">
                    <!-- Add/Edit Material Form -->
                    <div class="card">
                        <h3 id="material-form-title">Add New Material</h3>
                        <div class="form-group">
                            <label for="material-name">Material Name</label>
                            <input type="text" id="material-name" placeholder="e.g., All-Purpose Flour">
                        </div>
                        <div class="form-group">
                            <label for="material-unit">Unit</label>
                            <select id="material-unit">
                                <option value="kg">Kilogram (kg)</option>
                                <option value="ltr">Liter (ltr)</option>
                                <option value="pcs">Piece (pcs)</option>
                                <option value="g">Gram (g)</option>
                                <option value="ml">Milliliter (ml)</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="material-rate">Purchase Rate (Cost per Unit in <span id="material-rate-currency">AED</span>)</label>
                            <input type="number" id="material-rate" min="0" step="0.01" placeholder="0.00">
                        </div>
                        <div style="text-align: right;">
                            <button class="btn btn-success" id="save-material-btn" onclick="saveMaterial()">Save Material</button>
                            <button class="btn btn-danger" id="cancel-material-edit" onclick="cancelEditMaterial()" style="display: none;">Cancel</button>
                        </div>
                    </div>

                    <!-- Material List Table -->
                    <div class="card">
                        <h3>Material Database</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Unit</th>
                                    <th>Rate</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="raw-materials-table">
                                <!-- Materials listed here -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

        </main>
    </div>

    <script>
        // --- STATE MANAGEMENT (Using localStorage) --- 
        const STORAGE_KEY_MATERIALS = 'chefMasterMaterials';
        const STORAGE_KEY_RECIPES = 'chefMasterRecipes';

        let materials = JSON.parse(localStorage.getItem(STORAGE_KEY_MATERIALS)) || {};
        let recipes = JSON.parse(localStorage.getItem(STORAGE_KEY_RECIPES)) || [];

        let currentIngredientIndex = 0; // Counter for dynamic ingredient rows
        let editingMaterialId = null; // Tracks if we are editing a material
        let currentCurrency = 'AED';
        
        const currencySymbols = {
            'AED': { symbol: 'AED', rate: 1 }, // Base currency for relative comparison (though here we use static rates)
            'USD': { symbol: '$', rate: 3.67 }, 
            'EUR': { symbol: '€', rate: 4.04 },
            'GBP': { symbol: '£', rate: 4.64 },
            'JPY': { symbol: '¥', rate: 0.024 },
            'INR': { symbol: '₹', rate: 0.044 },
            'CAD': { symbol: 'C$', rate: 2.70 },
            'AUD': { symbol: 'A$', rate: 2.42 },
            'CHF': { symbol: 'CHF', rate: 4.13 },
            'SGD': { symbol: 'S$', rate: 2.71 },
            'SAR': { symbol: 'SAR', rate: 0.98 } 
        };

        function saveData() {
            localStorage.setItem(STORAGE_KEY_MATERIALS, JSON.stringify(materials));
            localStorage.setItem(STORAGE_KEY_RECIPES, JSON.stringify(recipes));
        }

        // --- UI UTILITIES & CURRENCY HANDLING ---
        
        function formatCurrency(value) {
            const symbol = currencySymbols[currentCurrency].symbol;
            // If the base currency is the selected one (AED), we assume the stored rate is correct for that display.
            // For others, we would ideally store rates relative to a base currency and convert. 
            // Since original rates are stored as absolute numbers (e.g., 8.50 per kg),
            // we will treat the stored rate as the rate in the CURRENTLY selected currency for simplicity in this context, 
            // UNLESS the user changes currency AFTER saving ingredients, which requires a full recalculation.
            
            return `${symbol} ${parseFloat(value).toFixed(2)}`;
        }

        function updateCurrencySettings() {
            const selector = document.getElementById('currency-selector');
            currentCurrency = selector.value;
            
            document.getElementById('current-display-currency').textContent = currentCurrency;
            document.getElementById('material-rate-currency').textContent = currentCurrency;

            // If the currency changes, ALL displayed costs must be recalculated based on current stored AED rates (or assumed local rates).
            // To simplify, we will force a full recalculation if currency is changed, assuming the base cost stored in materials/recipes was in the *last used* currency.
            // A robust solution requires storing rates relative to a single base currency (e.g., USD or AED).

            if (confirm(`Changing currency to ${currentCurrency} requires recalculating all costs. Proceed? (This may slightly alter calculated costs if the rates stored previously were based on a different currency.)`)) {
                 recalculateAllCostsBasedOnNewCurrency();
            }
            
            // Always refresh views that display costs
            if(document.getElementById('create-recipe').classList.contains('active')) {
                calculateTotalCost(); // Recalculate current working recipe
            }
            renderRawMaterials();
            renderRecipeMaster();
        }

        function recalculateAllCostsBasedOnNewCurrency() {
            // IMPORTANT: Since we don't have dynamic conversion rates stored, we must assume the stored material rate
            // and recipe total cost were based on the currency when they were last saved. 
            // If currency changes, we simply update the display symbol.
            // For this exercise, we only update the symbol display in formatCurrency and don't attempt complex historical rate conversion.
            
            // Exception: Recipe Master needs to display the new symbol/cost.
            saveData(); // Save state change (even if costs aren't mathematically adjusted)
            renderRecipeMaster();
        }


        function switchSection(sectionId) {
            document.querySelectorAll('.content-section').forEach(section => {
                section.classList.remove('active');
            });
            document.getElementById(sectionId).classList.add('active');

            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-section') === sectionId) {
                    item.classList.add('active');
                }
            });

            if (sectionId === 'recipe-master') {
                renderRecipeMaster();
            } else if (sectionId === 'raw-materials') {
                renderRawMaterials();
                cancelEditMaterial(); // Ensure form is reset when viewing materials
            } else if (sectionId === 'create-recipe') {
                // Reset form state
                document.getElementById('recipe-name').value = '';
                document.getElementById('recipe-yield').value = 1;
                document.getElementById('auto-scale-target').value = '';
                document.getElementById('recipe-remarks').value = '';
                document.getElementById('total-recipe-cost').textContent = formatCurrency(0);
                currentIngredientIndex = 0;
                const container = document.getElementById('ingredients-container');
                // Clear existing rows, keeping only the header
                const header = container.querySelector('.ingredient-row.header-row').outerHTML;
                container.innerHTML = header;
                addIngredientRow(); // Start with one empty row
            }
        }

        // --- RAW MATERIALS LOGIC ---
        
        function renderRawMaterials() {
            const tableBody = document.getElementById('raw-materials-table');
            tableBody.innerHTML = '';

            const sortedMaterials = Object.entries(materials).sort(([, a], [, b]) => a.name.localeCompare(b.name));

            if (sortedMaterials.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #9ca3af;">No raw materials defined yet.</td></tr>';
                return;
            }

            sortedMaterials.forEach(([id, mat]) => {
                const row = tableBody.insertRow();
                row.innerHTML = `
                    <td>${mat.name}</td>
                    <td>${mat.unit}</td>
                    <td>${formatCurrency(mat.rate)}</td>
                    <td>
                        <button class="btn btn-primary" style="padding: 5px 10px;" onclick="editMaterial('${id}')">
                            Edit
                        </button>
                        <button class="btn btn-danger" style="padding: 5px 10px;" onclick="deleteMaterial('${id}')">
                            Delete
                        </button>
                    </td>
                `;
            });
        }

        function saveMaterial() {
            const name = document.getElementById('material-name').value.trim();
            const unit = document.getElementById('material-unit').value;
            const rate = parseFloat(document.getElementById('material-rate').value);

            if (!name || !unit || isNaN(rate) || rate < 0) {
                alert('Please ensure all fields are filled correctly (Rate must be a positive number).');
                return;
            }

            if (editingMaterialId) {
                // Edit existing
                materials[editingMaterialId].name = name;
                materials[editingMaterialId].unit = unit;
                materials[editingMaterialId].rate = rate;
                alert(`Material '${name}' updated.`);
            } else {
                // Add new
                const newId = Date.now().toString();
                materials[newId] = { name, unit, rate };
                alert(`Material '${name}' added successfully.`);
            }

            saveData();
            renderRawMaterials();
            resetMaterialForm();
        }

        function editMaterial(id) {
            editingMaterialId = id;
            const mat = materials[id];

            document.getElementById('material-form-title').textContent = 'Edit Material';
            document.getElementById('material-name').value = mat.name;
            document.getElementById('material-unit').value = mat.unit;
            document.getElementById('material-rate').value = mat.rate;

            document.getElementById('save-material-btn').textContent = 'Update Material';
            document.getElementById('cancel-material-edit').style.display = 'inline-flex';
        }

        function cancelEditMaterial() {
            editingMaterialId = null;
            resetMaterialForm();
        }

        function resetMaterialForm() {
            document.getElementById('material-form-title').textContent = 'Add New Material';
            document.getElementById('material-name').value = '';
            document.getElementById('material-unit').value = 'kg';
            document.getElementById('material-rate').value = '';
            document.getElementById('save-material-btn').textContent = 'Save Material';
            document.getElementById('cancel-material-edit').style.display = 'none';
        }

        function deleteMaterial(id) {
            if (confirm('Are you sure you want to delete this material? This will affect calculations for all recipes using it.')) {
                delete materials[id];
                saveData();
                renderRawMaterials();
                
                // Check affected recipes and recalculate if necessary
                recipes.forEach(recipe => {
                    recipe.ingredients = recipe.ingredients.filter(ing => ing.name !== materials[id]?.name); // Filter out ingredients made from the deleted material
                    // Recalculate totals for affected recipes
                    recipe.totalCost = recipe.ingredients.reduce((sum, ing) => sum + ing.subtotal, 0);
                });
                saveData();
                renderRecipeMaster();
            }
        }

        // --- RECIPE CREATION LOGIC ---

        function getMaterialRate(materialName) {
            // Find material by name
            const foundMat = Object.values(materials).find(m => m.name === materialName);
            if (foundMat) {
                return foundMat.rate;
            }
            return 0; // Default cost if material not found
        }

        function updateIngredientCost(rowElement) {
            const inputQty = rowElement.querySelector('input[name="qty"]');
            const selectMaterial = rowElement.querySelector('select[name="material"]');
            const spanCost = rowElement.querySelector('span[name="unit-cost"]');
            const spanSubtotal = rowElement.querySelector('span[name="subtotal"]');

            const qty = parseFloat(inputQty.value) || 0;
            const materialName = selectMaterial.value;
            
            let rate = 0;
            if (materialName) {
                rate = getMaterialRate(materialName);
            }
            
            spanCost.textContent = formatCurrency(rate);
            const subtotal = qty * rate;
            spanSubtotal.textContent = formatCurrency(subtotal);

            calculateTotalCost();
        }

        function calculateTotalCost() {
            let total = 0;
            document.querySelectorAll('.ingredient-row:not(.header-row)').forEach(row => {
                const subtotalText = row.querySelector('span[name="subtotal"]').textContent.replace(/[^0-9.]/g, ''); // Strip currency symbol/text
                total += parseFloat(subtotalText) || 0;
            });
            document.getElementById('total-recipe-cost').textContent = formatCurrency(total);
            
            // Update yield/scaling based on current total cost and current yield
            const currentYield = parseInt(document.getElementById('recipe-yield').value);
            const originalYield = parseInt(document.getElementById('recipe-yield').dataset.originalYield || currentYield.toString());

            if(originalYield > 0) {
                 const costPerPortion = total / currentYield;
                 document.getElementById('total-recipe-cost').dataset.costPerPortion = costPerPortion.toFixed(4);
            }

            // Update auto-scale display if it's active
            const targetInput = document.getElementById('auto-scale-target');
            if(targetInput.value) {
                autoCalculateYield(true); // Recalculate cost based on current ingredient quantities
            }
        }

        function autoCalculateYield(isRecalculating = false) {
            const yieldInput = document.getElementById('recipe-yield');
            const targetInput = document.getElementById('auto-scale-target');
            const currentYield = parseInt(yieldInput.value) || 1;
            const targetYield = parseInt(targetInput.value);

            // If the user types into the target, update the actual yield input and recalculate ingredient quantities/costs
            if (!isNaN(targetYield) && targetYield > 0) {
                
                const scaleFactor = targetYield / currentYield; 
                
                // 1. Update the displayed yield
                if (!yieldInput.dataset.originalYield) {
                    yieldInput.dataset.originalYield = currentYield; // Store base yield before scaling
                }
                yieldInput.value = targetYield;

                // 2. Apply scaling to ingredients only if we are recalculating, not just typing
                if (isRecalculating || !isRecalculating && !yieldInput.dataset.scalingInitiated) {
                     document.querySelectorAll('.ingredient-row:not(.header-row)').forEach(row => {
                        const qtyInput = row.querySelector('input[name="qty"]');
                        const originalQtyText = qtyInput.dataset.originalQty;
                        
                        if (!originalQtyText) {
                            qtyInput.dataset.originalQty = qtyInput.value;
                        }
                        
                        const originalQty = parseFloat(qtyInput.dataset.originalQty || qtyInput.value);
                        qtyInput.value = (originalQty * scaleFactor).toFixed(4);

                        updateIngredientCost(row);
                    });
                    yieldInput.dataset.scalingInitiated = 'true';
                }
                
                // 3. Recalculate total cost based on scaled quantities
                calculateTotalCost();

            } else if (targetInput.value === '' && yieldInput.dataset.originalYield) {
                // Clear scaling
                resetYieldFromScale();
            }
        }

        function resetYieldFromScale() {
            const yieldInput = document.getElementById('recipe-yield');
            const targetInput = document.getElementById('auto-scale-target');
            
            if (yieldInput.dataset.originalYield) {
                const originalYield = parseInt(yieldInput.dataset.originalYield);
                yieldInput.value = originalYield;
                yieldInput.dataset.originalYield = ''; // Clear stored base
                targetInput.value = ''; // Clear target input
                yieldInput.dataset.scalingInitiated = '';
            }
            
            // Reset ingredient quantities to original state (if scaling was applied)
            document.querySelectorAll('.ingredient-row:not(.header-row)').forEach(row => {
                const qtyInput = row.querySelector('input[name="qty"]');
                if (qtyInput.dataset.originalQty) {
                    qtyInput.value = qtyInput.dataset.originalQty;
                    qtyInput.dataset.originalQty = '';
                }
                updateIngredientCost(row);
            });
        }

        function addIngredientRow() {
            const container = document.getElementById('ingredients-container');
            const uniqueId = `ing-${currentIngredientIndex++}`;

            const materialOptions = Object.values(materials).map(mat => 
                `<option value="${mat.name}">${mat.name} (${mat.unit})</option>`
            ).join('');

            const rowDiv = document.createElement('div');
            rowDiv.className = 'ingredient-row';
            rowDiv.setAttribute('data-id', uniqueId);
            rowDiv.innerHTML = `
                <div>
                    <select name="material" class="material-select" onchange="updateIngredientCost(this.closest('.ingredient-row'))">
                        <option value="">-- Select Ingredient --</option>
                        ${materialOptions}
                    </select>
                </div>
                <div>
                    <input type="number" name="qty" value="1" min="0.01" step="any" oninput="updateIngredientCost(this.closest('.ingredient-row'))">
                </div>
                <div>
                    <span name="unit-cost">${formatCurrency(0)}</span>
                </div>
                <div>
                    <span name="subtotal">${formatCurrency(0)}</span>
                </div>
                <div>
                    <button class="btn btn-danger" type="button" onclick="removeIngredientRow(this.closest('.ingredient-row'))" style="padding: 5px 10px;">
                        X
                    </button>
                </div>
            `;

            container.appendChild(rowDiv);
            
            // Initialize the newly added row
            updateIngredientCost(rowDiv);
        }

        function removeIngredientRow(rowElement) {
            // If this row was scaled, we need to ensure scaling logic is updated if this ingredient was the base
            const qtyInput = rowElement.querySelector('input[name="qty"]');
            if(qtyInput.dataset.originalQty) {
                delete qtyInput.dataset.originalQty;
                // Since one ingredient is removed, the scaling factor might implicitly change if we were using the scaled yield.
                // We force a recalculation on the remaining ingredients.
                autoCalculateYield(true);
            }

            rowElement.remove();
            calculateTotalCost();
        }

        function saveRecipe() {
            const name = document.getElementById('recipe-name').value.trim();
            let yieldVal = parseInt(document.getElementById('recipe-yield').value);
            const category = document.getElementById('recipe-category').value;
            const remarks = document.getElementById('recipe-remarks').value;
            
            // Clean cost text to get number
            const totalCostText = document.getElementById('total-recipe-cost').textContent.replace(/[^0-9.]/g, ''); 
            const totalCost = parseFloat(totalCostText);

            if (!name || yieldVal <= 0) {
                alert('Recipe Name and Yield must be provided.');
                return;
            }

            const ingredients = [];
            let hasValidIngredients = false;
            document.querySelectorAll('.ingredient-row:not(.header-row)').forEach(row => {
                const materialSelect = row.querySelector('select[name="material"]');
                const qtyInput = row.querySelector('input[name="qty"]');
                
                const materialName = materialSelect.value;
                const qty = parseFloat(qtyInput.value);
                
                if (materialName && qty > 0) {
                    hasValidIngredients = true;
                    // Get rate and subtotal from the displayed text (which uses the current currency symbol)
                    const rateText = row.querySelector('span[name="unit-cost"]').textContent.replace(/[^0-9.]/g, ''); 
                    const subtotalText = row.querySelector('span[name="subtotal"]').textContent.replace(/[^0-9.]/g, ''); 
                    
                    const rate = parseFloat(rateText);
                    const subtotal = parseFloat(subtotalText);
                    
                    ingredients.push({
                        name: materialName,
                        quantity: qty,
                        unitCost: rate, // Store cost in current display currency
                        subtotal: subtotal
                    });
                }
            });

            if (!hasValidIngredients) {
                alert('Please add at least one valid ingredient.');
                return;
            }
            
            // If scaling was active, revert yield back to the calculated base yield before saving
            const originalYield = parseInt(document.getElementById('recipe-yield').dataset.originalYield || yieldVal.toString());

            const newRecipe = {
                id: Date.now().toString(),
                name, 
                yield: originalYield, // Store the base yield (pre-scaling)
                category, 
                remarks,
                ingredients, 
                totalCost // Total cost is based on the ingredients array's subtotal sum
            };

            recipes.push(newRecipe);
            saveData();
            alert(`Recipe "${name}" saved successfully! Base Yield: ${originalYield}`);
            switchSection('recipe-master');
        }

        // --- RECIPE MASTER LOGIC ---

        function renderRecipeMaster() {
            const container = document.getElementById('recipe-list-container');
            container.innerHTML = '';
            
            if (recipes.length === 0) {
                container.innerHTML = '<div class="card" style="text-align: center;">No recipes saved yet. Go to Create Recipe to begin!</div>';
                return;
            }

            // Sort recipes by name
            recipes.sort((a, b) => a.name.localeCompare(b.name));

            recipes.forEach(recipe => {
                const itemDiv = document.createElement('div');
                itemDiv.className = 'recipe-list-item card';
                itemDiv.setAttribute('data-recipe-id', recipe.id);
                
                // Note: We display the stored totalCost, which uses the symbol from when it was saved.
                // formatCurrency will apply the *current* symbol.
                const displayCost = formatCurrency(recipe.totalCost);
                const costPerPortion = recipe.totalCost / recipe.yield;
                
                itemDiv.innerHTML = `
                    <div class="recipe-info">
                        <input type="checkbox" class="recipe-selector" value="${recipe.id}" style="margin-right: 10px;">
                        <div>
                            <strong>${recipe.name}</strong> (Base Yield: ${recipe.yield} portions)
                            <div style="font-size: 1.2rem; color: var(--primary-color); margin-top: 5px;">
                                Total Cost: ${displayCost} 
                                <span style="font-size: 0.9rem; font-weight: 400;">(${formatCurrency(costPerPortion)}/Portion)</span>
                            </div>
                        </div>
                    </div>
                    <div class="recipe-actions">
                        <button class="btn btn-primary" onclick="viewRecipeDetail('${recipe.id}')" style="background-color: #6366f1;">
                            View/Print
                        </button>
                        <button class="btn btn-danger" onclick="deleteRecipe('${recipe.id}', '${recipe.name}')">
                            Delete
                        </button>
                    </div>
                `;
                container.appendChild(itemDiv);
            });
        }

        function deleteRecipe(id, name) {
            if (confirm(`Are you sure you want to delete the recipe: ${name}?`)) {
                recipes = recipes.filter(r => r.id !== id);
                saveData();
                renderRecipeMaster();
            }
        }

        function viewRecipeDetail(recipeId) {
            const recipe = recipes.find(r => r.id === recipeId);
            if (!recipe) return;

            const printWindow = window.open('', '_blank');
            
            let ingredientsHtml = `
                <table>
                    <thead>
                        <tr><th>Ingredient</th><th>Qty</th><th>Unit Cost</th><th>Subtotal</th></tr>
                    </thead>
                    <tbody>
            `;

            recipe.ingredients.forEach(ing => {
                // ing.unitCost reflects the cost per unit at the time of saving
                ingredientsHtml += `
                    <tr>
                        <td>${ing.name}</td>
                        <td>${ing.quantity.toFixed(4)}</td>
                        <td>${formatCurrency(ing.unitCost)}</td>
                        <td>${formatCurrency(ing.subtotal)}</td>
                    </tr>
                `;
            });
            
            const costPerPortion = recipe.totalCost / recipe.yield;

            ingredientsHtml += `
                    </tbody>
                    <tfoot>
                        <tr><td colspan="3" style="text-align: right; font-weight: bold;">TOTAL COST (for ${recipe.yield} Portions):</td><td>${formatCurrency(recipe.totalCost)}</td></tr>
                    </tfoot>
                </table>
            `;

            const htmlContent = `
                <html>
                <head>
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Report: ${recipe.name}</title>
                    <link href="https://fonts.googleapis.com/css2?family=Segoe+UI:wght@300;400;600;700&display=swap" rel="stylesheet">
                    <style>
                        :root {
                            --primary-color: #4f46e5; 
                        }
                        body { font-family: 'Segoe UI', sans-serif; margin: 40px; }
                        h1, h2 { color: #1f2937; margin-bottom: 15px; }
                        .report-header p { margin-bottom: 5px; }
                        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                        th, td { border: 1px solid #ccc; padding: 10px; text-align: left; }
                        th { background-color: #f3f4f6; }
                        tfoot td { background-color: #f3f4f6; font-weight: bold; }
                        .cost-total { font-size: 1.5rem; color: var(--primary-color); margin-top: 20px; border-top: 2px solid #eee; padding-top: 10px; }
                        /* Hide UI elements for clean printing */
                        @media print {
                            body { margin: 20px; }
                            .cost-total { page-break-before: avoid; }
                        }
                    </style>
                </head>
                <body>
                    <h1>Recipe Report: ${recipe.name}</h1>
                    <div class="report-header">
                        <p><strong>Category:</strong> ${recipe.category}</p>
                        <p><strong>Base Yield:</strong> ${recipe.yield} Portions</p>
                        <p><strong>Remarks:</strong> ${recipe.remarks || 'N/A'}</p>
                    </div>
                    ${ingredientsHtml}
                    <div class="cost-total">Cost Per Portion: ${formatCurrency(costPerPortion)}</div>
                
  <a href="https://karbonsites.space/home" target="_blank" id="karbon-promo-banner">
      <span>✨</span>
      <div>Built with <b>Karbon Sites</b></div>
  </a>
</body>
                </html>
            `;
            
            printWindow.document.write(htmlContent);
            printWindow.document.close();
        }

        function viewAllRecipeDetails() {
             if (recipes.length === 0) {
                alert('No recipes saved to view.');
                return;
            }
            const printWindow = window.open('', '_blank');
            
            let combinedHtml = `<html><head><title>Batch Recipe Report</title><meta name="viewport" content="width=device-width, initial-scale=1.0"><link href="https://fonts.googleapis.com/css2?family=Segoe+UI:wght@300;400;600;700&display=swap" rel="stylesheet"><style>body { font-family: 'Segoe UI', sans-serif; margin: 20px; } h2 { color: #1f2937; margin-top: 30px; border-bottom: 2px solid #4f46e5; padding-bottom: 5px; } table { width: 100%; border-collapse: collapse; margin-bottom: 40px; } th, td { border: 1px solid #ccc; padding: 8px; text-align: left; } th { background-color: #f3f4f6; } .cost-info { margin-bottom: 15px; font-size: 0.9rem; } .page-break { page-break-before: always; } .page-break:first-child { page-break-before: auto; }</style></head><body><h1>Selected Recipe Batch Report</h1>`;

            recipes.sort((a, b) => a.name.localeCompare(b.name));

            recipes.forEach((recipe, index) => {
                let ingredientsHtml = `
                    <div class="page-break" data-recipe-id=\"${recipe.id}\"></div>
                    <h2>${index + 1}. ${recipe.name}</h2>
                    <div class="cost-info">
                        <strong>Category:</strong> ${recipe.category} | 
                        <strong>Base Yield:</strong> ${recipe.yield} Portions
                    </div>
                    <table>
                        <thead><tr><th>Ingredient</th><th>Qty</th><th>Unit Cost</th><th>Subtotal</th></tr></thead>
                        <tbody>
                `;

                recipe.ingredients.forEach(ing => {
                    ingredientsHtml += `
                        <tr>
                            <td>${ing.name}</td>
                            <td>${ing.quantity.toFixed(4)}</td>
                            <td>${formatCurrency(ing.unitCost)}</td>
                            <td>${formatCurrency(ing.subtotal)}</td>
                        </tr>
                    `;
                });
                
                const costPerPortion = recipe.totalCost / recipe.yield;

                ingredientsHtml += `
                        </tbody>
                        <tfoot><tr><td colspan="3" style="text-align: right; font-weight: bold;">TOTAL COST:</td><td>${formatCurrency(recipe.totalCost)}</td></tr></tfoot>
                    </table>
                    <p><strong>Cost per Portion:</strong> ${formatCurrency(costPerPortion)}</p>
                    <p><strong>Remarks:</strong> ${recipe.remarks || 'N/A'}</p>
                `;
                combinedHtml += ingredientsHtml;
            });

            combinedHtml += '</body></html>';
            printWindow.document.write(combinedHtml);
            printWindow.document.close();
            printWindow.print();
        }

        // --- INITIALIZATION ---

        function initialize() {
            // 1. Ensure we have some default materials if storage is empty
            if (Object.keys(materials).length === 0) {
                materials['m1'] = { name: 'Salt', unit: 'g', rate: 0.005 };
                materials['m2'] = { name: 'Water', unit: 'ltr', rate: 0.001 };
                materials['m3'] = { name: 'Chicken Breast', unit: 'kg', rate: 8.50 };
                saveData();
            }
            
            // Set initial currency based on dropdown default
            updateCurrencySettings();

            // 2. Render initial states
            renderRawMaterials();
            renderRecipeMaster();
            
            // 3. Start with one ingredient row in the creation form
            addIngredientRow();
        }

        window.onload = initialize;
    </script>
</body>
</html>