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 
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
import html
import json
import os
import threading
import uuid
from datetime import datetime
from pathlib import Path

import streamlit as st
import streamlit.components.v1 as components

try:
    from huggingface_hub import HfApi
except Exception:
    HfApi = None

if os.name == "nt":
    import msvcrt
else:
    import fcntl

BASE_DIR = Path(__file__).resolve().parent
WRITE_LOCK = threading.Lock()
HF_DATASET_REPO_ID = os.getenv("HF_DATASET_REPO_ID", "").strip()
HF_DATASET_FILENAME = os.getenv("HF_DATASET_FILENAME", "laboratorio_prompts.jsonl").strip()
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()

st.set_page_config(
    page_title="Laboratorio de Prompts Pedagógicos",
    page_icon="✦",
    layout="wide",
    initial_sidebar_state="collapsed",
)

# -----------------------------
# Estado
# -----------------------------
defaults = {
    "step": 1,
    "strategy": "",
    "selected_strategy": "",
    "topic": "",
    "basic_prompt": "",
    "basic_prompt_saved": "",
    "response_1": "",
    "response_1_saved": "",
    "initial_fit": "",
    "initial_notes": "",
    "role": "",
    "context": "",
    "objective": "",
    "guide": "",
    "constraints": "",
    "advanced_prompt": "",
    "advanced_prompt_saved": "",
    "response_2": "",
    "response_2_saved": "",
    "advanced_fit": "",
    "comparison_notes": "",
    "score_1": {},
    "score_2": {},
    "reflection_factor": "",
    "reflection_use": "",
    "strategy_usefulness": "★★★☆☆",
    "reflection_sentence": "",
    "teacher_name": "",
    "submission_id": "",
    "results_saved": False,
}
for k, v in defaults.items():
    if k not in st.session_state:
        st.session_state[k] = v

if not st.session_state.submission_id:
    st.session_state.submission_id = str(uuid.uuid4())

# Respaldo estable del prompt base para evitar perdida por rerenders.
if st.session_state.basic_prompt and not st.session_state.basic_prompt_saved:
    st.session_state.basic_prompt_saved = st.session_state.basic_prompt
if st.session_state.advanced_prompt and not st.session_state.advanced_prompt_saved:
    st.session_state.advanced_prompt_saved = st.session_state.advanced_prompt
if st.session_state.response_1 and not st.session_state.response_1_saved:
    st.session_state.response_1_saved = st.session_state.response_1
if st.session_state.response_2 and not st.session_state.response_2_saved:
    st.session_state.response_2_saved = st.session_state.response_2

STRATEGY_CARDS = [
    (
        "🧩 Múltiples ejemplos",
        "Generar ejemplos diversos que permitan comprender un mismo concepto desde diferentes situaciones.",
    ),
    (
        "💡 Múltiples explicaciones",
        "Explicar un concepto de diferentes maneras, niveles y perspectivas.",
    ),
    (
        "✅ Pruebas de bajo riesgo",
        "Crear preguntas y ejercicios que permitan practicar y recuperar conocimientos.",
    ),
    (
        "🔎 Evaluación del aprendizaje",
        "Analizar respuestas para reconocer aprendizajes, dificultades y confusiones.",
    ),
    (
        "🔄 Practica distribuida",
        "Recuperar y conectar conocimientos estudiados anteriormente.",
    ),
]

STEP_LABELS = [
    "Selección de estrategia",
    "Un prompt sencillo",
    "Experimenta con tu prompt",
    "Anatomía avanzada",
    "Tu prompt avanzado",
    "Segunda experimentacion",
    "Comparacion",
    "Evaluacion comparativa",
    "Reflexion final",
]

VISUAL_STAGES = [
    "Estrategia",
    "Prompt sencillo",
    "Anatomía avanzada",
    "Prompt avanzado",
    "Comparación",
    "Evaluación",
]

VISUAL_STAGE_BY_STEP = {
    1: 1,
    2: 2,
    3: 2,
    4: 3,
    5: 4,
    6: 4,
    7: 5,
    8: 6,
    9: 6,
}

# -----------------------------
# Estilo
# -----------------------------
st.markdown(
    """

<style>

    .stApp {

        background: radial-gradient(circle at 15% 15%, #f2f8ef 0%, #f7f7f5 35%, #f2f0ec 100%);

        color: #17222f;

    }



    .block-container {

        max-width: 1080px;

        padding-top: 2.2rem;

        padding-bottom: 3.5rem;

    }



    h1, h2, h3 {

        letter-spacing: -0.02em;

    }



    .eyebrow {

        font-size: 0.8rem;

        text-transform: uppercase;

        letter-spacing: 0.12em;

        color: #5c6773;

        font-weight: 700;

        margin-bottom: 0.35rem;

    }



    .hero {

        background: white;

        border: 1px solid #dde5dc;

        border-radius: 20px;

        padding: 1.6rem 1.7rem;

        box-shadow: 0 8px 30px rgba(21, 33, 44, 0.05);

        margin-bottom: 1.2rem;

    }



    .hero h1 {

        font-size: 2rem;

        margin: 0.1rem 0 0.4rem 0;

    }



    .hero p {

        color: #3d4652;

        line-height: 1.65;

        margin-bottom: 0;

    }



    .stage-indicator {

        background: #ffffffde;

        border: 1px solid #dbe3df;

        border-radius: 999px;

        padding: 0.52rem 0.9rem;

        margin-bottom: 0.9rem;

        font-size: 0.87rem;

        color: #66717e;

        overflow-x: auto;

        white-space: nowrap;

    }



    .stage-active {

        color: #17222f;

        font-weight: 700;

    }



    .step-card {

        background: white;

        border: 1px solid #dce4df;

        border-radius: 16px;

        padding: 1.3rem 1.35rem;

        margin-bottom: 0.95rem;

    }



    .strategy-card {

        background: white;

        border: 1px solid #d9e2dd;

        border-radius: 14px;

        padding: 1rem 1.05rem;

        height: 100%;

    }



    .prompt-box {

        background: #f8faf8;

        border: 1px solid #dde4df;

        border-radius: 12px;

        padding: 0.9rem 1rem;

        font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;

        white-space: pre-wrap;

        line-height: 1.5;

        min-height: 120px;

    }



    div[data-testid="stProgress"] > div > div > div > div {

        background-color: #1a5e3d;

    }



    div.stButton > button {

        border-radius: 999px;

        border: 1px solid #ccd8d1;

        padding: 0.55rem 1rem;

        font-weight: 650;

        background: white;

    }



    div.stButton > button[kind="primary"] {

        background: #1a5e3d;

        color: #ffffff !important;

        border-color: #1a5e3d;

    }



    div.stButton > button[kind="primary"] * {

        color: #ffffff !important;

    }



    .footer-note {

        color: #6a7785;

        font-size: 0.84rem;

        margin-top: 2rem;

    }



    /* Mejora de contraste para opciones de seleccion */

    div[data-testid="stRadio"] > label,

    div[data-testid="stRadio"] > label p {

        color: #000000 !important;

        font-size: 1.1rem !important;

        font-weight: 700 !important;

    }



    /* Contraste global para labels y textos de formularios */

    div[data-testid="stTextInput"] label,

    div[data-testid="stTextInput"] label p,

    div[data-testid="stTextArea"] label,

    div[data-testid="stTextArea"] label p,

    div[data-testid="stSelectbox"] label,

    div[data-testid="stSelectbox"] label p,

    div[data-testid="stSelectSlider"] label,

    div[data-testid="stSelectSlider"] label p,

    div[data-testid="stSlider"] label,

    div[data-testid="stSlider"] label p,

    div[data-testid="stMultiSelect"] label,

    div[data-testid="stMultiSelect"] label p,

    div[data-testid="stCheckbox"] label,

    div[data-testid="stCheckbox"] label p,

    div[data-testid="stMarkdownContainer"] p,

    .stCaption,

    .stAlert p {

        color: #000000 !important;

    }



    /* Texto escrito en gris claro sobre fondo negro */

    div[data-testid="stTextInput"] input,

    div[data-testid="stTextArea"] textarea,

    div[data-testid="stTextInput"] input::placeholder,

    div[data-testid="stTextArea"] textarea::placeholder {

        color: #d9d9d9 !important;

        -webkit-text-fill-color: #d9d9d9 !important;

        opacity: 1 !important;

    }



    div[data-testid="stTextInput"] input,

    div[data-testid="stTextArea"] textarea {

        background-color: #000000 !important;

        border-color: #3a3a3a !important;

    }



    div[role="radiogroup"] label,

    div[role="radiogroup"] label p,

    div[role="radiogroup"] span {

        color: #17222f !important;

    }



    div[role="radiogroup"] label {

        background: #ffffff;

        border: 1px solid #d9e2dd;

        border-radius: 10px;

        padding: 0.3rem 0.55rem;

    }



    /* Ajustes responsivos para dispositivos moviles */

    @media (max-width: 768px) {

        .block-container {

            padding-top: 1.1rem;

            padding-bottom: 2rem;

            padding-left: 0.7rem;

            padding-right: 0.7rem;

        }



        h1 {

            font-size: 1.55rem !important;

            line-height: 1.25;

        }



        h2 {

            font-size: 1.25rem !important;

        }



        .stage-indicator {

            white-space: normal;

            line-height: 1.45;

            border-radius: 14px;

            padding: 0.65rem 0.75rem;

            font-size: 0.82rem;

        }



        div[data-testid="stRadio"] > label,

        div[data-testid="stRadio"] > label p {

            font-size: 0.96rem !important;

        }



        div[role="radiogroup"] {

            gap: 0.45rem;

        }



        div[role="radiogroup"] label {

            width: 100%;

            min-height: 2.2rem;

            align-items: flex-start;

            padding: 0.5rem 0.65rem;

        }



        .prompt-box {

            min-height: 90px;

            padding: 0.75rem 0.8rem;

            font-size: 0.92rem;

        }



        iframe {

            width: 100% !important;

        }



        /* En movil apila columnas para evitar cortes horizontales */

        div[data-testid="stHorizontalBlock"] {

            flex-wrap: wrap;

            row-gap: 0.5rem;

        }



        div[data-testid="column"] {

            min-width: 100% !important;

            flex: 1 1 100% !important;

        }

    }

</style>

""",
    unsafe_allow_html=True,
)


def go_next():
    st.session_state.step = min(9, st.session_state.step + 1)


def go_back():
    st.session_state.step = max(1, st.session_state.step - 1)


def sync_selected_strategy():
    st.session_state.selected_strategy = st.session_state.strategy


def reset_lab():
    for key, value in defaults.items():
        st.session_state[key] = value
    st.session_state.submission_id = str(uuid.uuid4())


def _acquire_file_lock(lock_file):
    lock_file.seek(0)
    lock_file.write("0")
    lock_file.flush()
    lock_file.seek(0)
    if os.name == "nt":
        msvcrt.locking(lock_file.fileno(), msvcrt.LK_LOCK, 1)
    else:
        fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)


def _release_file_lock(lock_file):
    lock_file.seek(0)
    if os.name == "nt":
        msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
    else:
        fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)


def _build_payload():
    return {
        "saved_at": datetime.now().isoformat(timespec="seconds"),
        "submission_id": st.session_state.submission_id,
        "teacher_name": st.session_state.teacher_name.strip(),
        "selected_strategy": st.session_state.selected_strategy or st.session_state.strategy,
        "screen_8_evaluation": {
            "score_1": st.session_state.score_1,
            "score_2": st.session_state.score_2,
        },
        "screen_9_evaluation": {
            "strategy_usefulness": st.session_state.strategy_usefulness,
            "reflection_factor": st.session_state.reflection_factor,
            "reflection_use": st.session_state.reflection_use,
            "reflection_sentence": st.session_state.reflection_sentence,
        },
    }


def _save_results_local(payload):
    output_path = BASE_DIR / "resultados" / "laboratorio_prompts.jsonl"
    output_path.parent.mkdir(parents=True, exist_ok=True)
    lock_path = output_path.with_suffix(output_path.suffix + ".lock")
    line = json.dumps(payload, ensure_ascii=False) + "\n"

    with WRITE_LOCK:
        with lock_path.open("a+", encoding="utf-8") as lock_file:
            _acquire_file_lock(lock_file)
            try:
                existing_ids = set()
                if output_path.exists():
                    with output_path.open("r", encoding="utf-8") as input_file:
                        for raw_line in input_file:
                            raw_line = raw_line.strip()
                            if not raw_line:
                                continue
                            try:
                                row = json.loads(raw_line)
                                row_id = row.get("submission_id")
                                if row_id:
                                    existing_ids.add(row_id)
                            except json.JSONDecodeError:
                                continue

                if payload["submission_id"] in existing_ids:
                    return output_path, "duplicate"

                with output_path.open("a", encoding="utf-8") as output_file:
                    output_file.write(line)
                    output_file.flush()
                    os.fsync(output_file.fileno())
            finally:
                _release_file_lock(lock_file)

    return output_path, "saved"


def _save_results_hf_dataset(payload):
    if not HF_DATASET_REPO_ID:
        return None, "not_configured", "Define HF_DATASET_REPO_ID para activar guardado en dataset."
    if not HF_TOKEN:
        return None, "not_configured", "Define HF_TOKEN para activar guardado en dataset."
    if HfApi is None:
        return None, "missing_dependency", "No se pudo importar huggingface_hub."

    api = HfApi(token=HF_TOKEN)
    target_file = HF_DATASET_FILENAME or "laboratorio_prompts.jsonl"

    lines = []
    existing_ids = set()
    try:
        remote_content = api.hf_hub_download(
            repo_id=HF_DATASET_REPO_ID,
            repo_type="dataset",
            filename=target_file,
        )
        with open(remote_content, "r", encoding="utf-8") as f:
            for raw_line in f:
                stripped = raw_line.strip()
                if not stripped:
                    continue
                lines.append(stripped)
                try:
                    row = json.loads(stripped)
                    row_id = row.get("submission_id")
                    if row_id:
                        existing_ids.add(row_id)
                except json.JSONDecodeError:
                    continue
    except Exception:
        # Si el archivo aun no existe en el dataset, iniciamos desde vacio.
        lines = []
        existing_ids = set()

    if payload["submission_id"] in existing_ids:
        return f"{HF_DATASET_REPO_ID}/{target_file}", "duplicate", "Registro ya existente en dataset."

    lines.append(json.dumps(payload, ensure_ascii=False))
    body = "\n".join(lines) + "\n"

    api.upload_file(
        path_or_fileobj=body.encode("utf-8"),
        path_in_repo=target_file,
        repo_id=HF_DATASET_REPO_ID,
        repo_type="dataset",
        commit_message="Add laboratorio_prompts entry",
    )
    return f"{HF_DATASET_REPO_ID}/{target_file}", "saved", "Registro guardado en dataset de Hugging Face."


def build_advanced_prompt():
    return (
        f"Actua como {st.session_state.role.strip()}.\n\n"
        f"Contexto:\n{st.session_state.context.strip()}\n\n"
        f"Tu objetivo es:\n{st.session_state.objective.strip()}\n\n"
        f"Para realizar la tarea considera las siguientes indicaciones:\n{st.session_state.guide.strip()}\n\n"
        f"Respeta las siguientes restricciones:\n{st.session_state.constraints.strip()}"
    ).strip()


def save_lab_results():
    payload = _build_payload()

    try:
        remote_path, remote_status, remote_message = _save_results_hf_dataset(payload)
        if remote_status in {"saved", "duplicate"}:
            return remote_path, remote_status, remote_message
    except Exception as exc:
        remote_message = f"Fallo guardado remoto: {exc}"

    local_path, local_status = _save_results_local(payload)
    if remote_message:
        fallback_message = f"{remote_message} Se guardo localmente en {local_path}."
    else:
        fallback_message = f"Guardado local en {local_path}."
    return str(local_path), local_status, fallback_message


def nav_buttons(next_disabled=False, next_label="Guardar y continuar →"):
    c1, c2, c3 = st.columns([1.1, 1.6, 4.2])
    with c1:
        if st.session_state.step > 1:
            if st.button("← Anterior", use_container_width=True):
                go_back()
                st.rerun()
    with c2:
        if st.session_state.step < 9:
            if st.button(
                next_label,
                type="primary",
                disabled=next_disabled,
                use_container_width=True,
            ):
                go_next()
                st.rerun()


def render_stage_indicator(step: int):
    active_stage = VISUAL_STAGE_BY_STEP[step]
    segments = []
    for idx, label in enumerate(VISUAL_STAGES, start=1):
        css_class = "stage-active" if idx == active_stage else ""
        bullet = "●"
        segments.append(f'<span class="{css_class}">{bullet} {label}</span>')
    st.markdown(
        '<div class="stage-indicator">' + " — ".join(segments) + "</div>",
        unsafe_allow_html=True,
    )


def copy_prompt_block(prompt_text: str, key: str, height: int = 210):
        safe_preview = html.escape(prompt_text if prompt_text.strip() else "(Aun no hay contenido)")
        json_text = json.dumps(prompt_text)
        block = f"""

        <div style="border:1px solid #dde4df; border-radius:12px; padding:0.9rem; background:#f8faf8;">

            <button id="copy-btn-{key}" style="border-radius:999px; border:1px solid #ccd8d1; background:white; padding:0.45rem 0.75rem; font-weight:650; cursor:pointer;">📋 Copiar prompt</button>

            <span id="copy-msg-{key}" style="margin-left:0.6rem; color:#1a5e3d; font-size:0.88rem;"></span>

            <pre style="white-space:pre-wrap; font-family:ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; margin-top:0.8rem;">{safe_preview}</pre>

        </div>

        <script>

        const copyBtn = document.getElementById("copy-btn-{key}");

        const copyMsg = document.getElementById("copy-msg-{key}");

        if (copyBtn) {{

            copyBtn.onclick = async () => {{

                try {{

                    await navigator.clipboard.writeText({json_text});

                    copyMsg.textContent = "Prompt copiado";

                    setTimeout(() => {{ copyMsg.textContent = ""; }}, 2200);

                }} catch (e) {{

                    copyMsg.textContent = "No se pudo copiar automaticamente";

                }}

            }};

        }}

        </script>

        """
        components.html(block, height=height, scrolling=False)


step = st.session_state.step

# -----------------------------
# Cabecera y progreso
# -----------------------------
st.markdown("# Laboratorio de Prompts Pedagógicos")
st.markdown(
    "En este laboratorio experimentarás cómo la construcción de un prompt puede modificar "
    "las respuestas generadas por un modelo de lenguaje. Trabajarás con una de las 5 "
    "estrategias educativas propuestas por [Mollick (2023)](https://dx.doi.org/10.2139/ssrn.4391243)."
)
render_stage_indicator(step)
st.markdown(f"### {STEP_LABELS[step - 1]}")
st.progress(step / len(STEP_LABELS))
st.caption(f"Pantalla {step} de {len(STEP_LABELS)}")


# -----------------------------
# Pantalla 1
# -----------------------------
if step == 1:

    for title, description in STRATEGY_CARDS:
        with st.container(border=True):
            st.markdown(f"### {title}")
            st.write(description)

    st.radio(
        "Selecciona una estrategia",
        options=[card[0] for card in STRATEGY_CARDS],
        key="strategy",
        index=None if st.session_state.strategy == "" else [card[0] for card in STRATEGY_CARDS].index(st.session_state.strategy),
        on_change=sync_selected_strategy,
    )

    # Si ya existe valor por estado previo, lo mantenemos sincronizado.
    if st.session_state.strategy and not st.session_state.selected_strategy:
        st.session_state.selected_strategy = st.session_state.strategy

    nav_buttons(next_disabled=not bool(st.session_state.strategy), next_label="Comenzar laboratorio →")

# -----------------------------
# Pantalla 2
# -----------------------------
elif step == 2:
    st.markdown("## Construye un prompt sencillo")
    if st.session_state.selected_strategy:
        st.caption(f"Estrategia seleccionada: {st.session_state.selected_strategy}")
    st.write("Piensa en una situación de tu práctica docente en la que puedas aplicar la estrategia seleccionada. " \
    "Escribe una instrucción sencilla para que un modelo de lenguaje realice la tarea.")

    st.text_input(
        "Tema o contenido de mi asignatura",
        key="topic",
        placeholder="Ej. fotosíntesis, derivadas, ética profesional, argumentación, etc.",
    )

    st.text_area(
        "Mi prompt básico",
        key="basic_prompt",
        height=190,
        placeholder="Escribe aquí un prompt básico sobre tu tema y para la estrateghia seleccionada...",
    )

    # Persistimos el valor para usarlo en pantallas posteriores.
    st.session_state.basic_prompt_saved = st.session_state.basic_prompt

    st.info("NOTA: No intentes construir todavía un prompt perfecto. Escríbelo como normalmente le pedirías la tarea a ChatGPT, Claude o Copilot.")

    nav_buttons(next_disabled=not st.session_state.basic_prompt.strip())

# -----------------------------
# Pantalla 3
# -----------------------------
elif step == 3:
    st.markdown("## Prueba tu prompt")
    st.write("Copia el siguiente prompt y ejecutalo por fuera en tu LLM favorito.")

    prompt_base = st.session_state.basic_prompt_saved or st.session_state.basic_prompt
    copy_prompt_block(prompt_base, key="basic", height=150)

    st.write("Regresa al laboratorio y pega la respuesta generada a continuación")
    st.text_area(
        "Respuesta obtenida",
        key="response_1",
        height=220,
        placeholder="Pega aqui la respuesta al prompt básico...",
    )

    st.session_state.response_1_saved = st.session_state.response_1

    st.radio(
        "¿La respuesta correspondió con lo que esperabas?",
        ["Si completamente", "Parcialmente", "No"],
        key="initial_fit",
        horizontal=True,
    )

    nav_buttons(next_disabled=not st.session_state.response_1.strip())

# -----------------------------
# Pantalla 4
# -----------------------------
elif step == 4:
    st.markdown("## Ahora vamos a construir un prompt avanzado")
    st.write(
        "Un prompt puede hacerse más explícito proporcionando al modelo información sobre quién debe ser, "
        "qué contexto debe considerar, qué resultado debe producir y bajo qué condiciones."
    )

    selected_strategy_label = st.session_state.selected_strategy or st.session_state.strategy or "No seleccionada"

    fields = [
        ("👤 Rol",
            "¿Desde qué perspectiva debe actuar?", 
            "Ejemplo: Actúa como una profesora de biología",
            "role", 
            95
        ),
        (
            "🌎 Contexto",
            "¿Qué debe saber el modelo sobre tus estudiantes, asignatura o situacion?",
            "Ejemplo: Mis estudiantes son de licenciatura en pedagogía.",
            "context",
            125,
        ),
        (
            "🎯 Objetivo",
            f"¿Qué resultado quieres obtener? Estrategia seleccionada: {selected_strategy_label}",
            f"Ejemplo: Aplica la estrategia: \"{selected_strategy_label}\" en el tema de...",
            "objective",
            120,
        ),
        (
            "🧭 Guia adicional",
            "¿Algún recurso adicional para ejecutar la estrategia?",
            "Ejemplo: Incluye analogías, diagrama, imagenes, nivel de complejidad, criterios pedagógicos, etc.",
            "guide",
            120,
        ),
        (
            "🚧 Restricciones",
            "¿Qué condiciones debe respetar o qué debe evitar?",
            "Ejemplo: Longitud, vocabulario, formato, estilo, etc.",
            "constraints",
            120,
        ),
    ]

    for title, question, placeholder, key, h in fields:
        with st.container(border=True):
            st.markdown(f"### {title}")
            st.caption(question)
            st.text_area(
                title,
                key=key,
                height=h,
                placeholder=placeholder,
                label_visibility="collapsed",
            )

    ready = all(st.session_state[k].strip() for k in ["role", "context", "objective", "guide", "constraints"])
    nav_buttons(next_disabled=not ready)

# -----------------------------
# Pantalla 5
# -----------------------------
elif step == 5:
    if not st.session_state.advanced_prompt.strip():
        st.session_state.advanced_prompt = build_advanced_prompt()

    st.markdown("## Este es tu nuevo prompt")
    st.write("Hemos integrado los elementos que escribiste anteriormente. Leelo y modificalo si consideras necesario.")

    st.text_area(
        "Prompt avanzado",
        key="advanced_prompt",
        height=320,
    )

    # Persistimos el prompt avanzado para evitar perdida por rerenders.
    st.session_state.advanced_prompt_saved = st.session_state.advanced_prompt

    st.caption("La herramienta ayuda a estructurar el prompt, pero la decisión final sigue siendo del usuario.")

    nav_buttons(next_disabled=not st.session_state.advanced_prompt.strip(), next_label="Guardar prompt avanzado →")

# -----------------------------
# Pantalla 6
# -----------------------------
elif step == 6:
    st.markdown("## Prueba ahora tu prompt avanzado")
    st.write("Copia el siguiente prompt avanzado y ejecútalo por fuera en tu LLM favorito.")

    prompt_avanzado = st.session_state.advanced_prompt_saved or st.session_state.advanced_prompt
    copy_prompt_block(prompt_avanzado, key="advanced", height=250)

    st.text_area(
        "Segunda respuesta",
        key="response_2",
        height=220,
        placeholder="Pega aquí la nueva respuesta...",
    )

    st.session_state.response_2_saved = st.session_state.response_2

    st.radio(
        "¿La respuesta se aproxima mas a lo que buscabas?",
        ["Mucho mas", "Algo mas", "Es similar", "Es peor"],
        key="advanced_fit",
        horizontal=True,
    )

    nav_buttons(next_disabled=not st.session_state.response_2.strip())

# -----------------------------
# Pantalla 7
# -----------------------------
elif step == 7:
    st.markdown("## Observa ambas respuestas")
    st.write("Antes de evaluarlas, identifica que diferencias observas.")

    prompt_basico = st.session_state.basic_prompt_saved or st.session_state.basic_prompt
    respuesta_1 = st.session_state.response_1_saved or st.session_state.response_1
    prompt_avanzado = st.session_state.advanced_prompt_saved or st.session_state.advanced_prompt
    respuesta_2 = st.session_state.response_2_saved or st.session_state.response_2

    col1, col2 = st.columns(2, gap="large")
    with col1:
        st.markdown("### Prompt basico")
        st.markdown(f'<div class="prompt-box">{html.escape(prompt_basico)}</div>', unsafe_allow_html=True)
        st.markdown("### Respuesta obtenida")
        st.markdown(f'<div class="prompt-box">{html.escape(respuesta_1)}</div>', unsafe_allow_html=True)

    with col2:
        st.markdown("### Prompt avanzado")
        st.markdown(f'<div class="prompt-box">{html.escape(prompt_avanzado)}</div>', unsafe_allow_html=True)
        st.markdown("### Respuesta obtenida")
        st.markdown(f'<div class="prompt-box">{html.escape(respuesta_2)}</div>', unsafe_allow_html=True)

    nav_buttons(next_label="Evaluar →")

# -----------------------------
# Pantalla 8
# -----------------------------
elif step == 8:
    st.markdown("## Evalua ambas respuestas")
    st.caption("Escala de evaluación: 1 = bajo, 2 = bajo-medio, 3 = medio, 4 = medio-alto, 5 = alto.")

    criteria = [
        "Precisión",
        "Cumplimiento de la instrucción",
        "Adecuación pedagógica",
        "Adecuación al estudiante",
        "Utilidad para mi práctica docente",
    ]

    header1, header2, header3 = st.columns([2.5, 1.5, 1.5])
    with header1:
        st.markdown("**Criterio**")
    with header2:
        st.markdown("**Respuesta prompt básico**")
    with header3:
        st.markdown("**Respuesta prompt avanzado**")

    scores_1 = {}
    scores_2 = {}
    for i, criterion in enumerate(criteria):
        c1, c2, c3 = st.columns([2.5, 1.5, 1.5])
        with c1:
            st.write(criterion)
        with c2:
            scores_1[criterion] = st.select_slider(
                f"R1 {criterion}",
                options=[1, 2, 3, 4, 5],
                value=3,
                key=f"score1_{i}",
                label_visibility="collapsed",
            )
        with c3:
            scores_2[criterion] = st.select_slider(
                f"R2 {criterion}",
                options=[1, 2, 3, 4, 5],
                value=3,
                key=f"score2_{i}",
                label_visibility="collapsed",
            )

    st.session_state.score_1 = scores_1
    st.session_state.score_2 = scores_2

    total_1 = sum(scores_1.values())
    total_2 = sum(scores_2.values())
    diff = total_2 - total_1

    st.divider()
    m1, m2, m3 = st.columns(3)
    m1.metric("Respuesta prompt Básico", f"{total_1}/25")
    m2.metric("Respuesta prompt Avanzado", f"{total_2}/25")
    m3.metric("Diferencia", f"{diff:+d}")

    st.warning(
        "Una mayor puntuación no implica necesariamente que un prompt más largo sea siempre mejor. "
        "El objetivo es reconocer qué información resulta necesaria para orientar al modelo hacia el propósito pedagógico."
    )

    nav_buttons(next_label="Ir a reflexion final →")

# -----------------------------
# Pantalla 9
# -----------------------------
elif step == 9:
    st.markdown("## Reflexion final")

    strategy_name = st.session_state.selected_strategy or st.session_state.strategy or "la estrategia elegida"

    st.radio(
        f"¿Qué tan útil puede ser aplicar la estrategia de Mollick: {strategy_name} en tu práctica docente?",
        ["★☆☆☆☆", "★★☆☆☆", "★★★☆☆", "★★★★☆", "★★★★★"],
        key="strategy_usefulness",
    )

    st.radio(
        "¿Qué elemento consideras es el más importante en un prompt avanzado?",
        ["Rol", "Contexto", "Objetivo", "Guia", "Restricciones", "No puedo determinarlo"],
        key="reflection_factor",
    )

    st.radio(
        "¿Utilizarías alguna de las estrategias descritas con tus estudiantes?",
        ["Sí", "Probablemente", "No"],
        key="reflection_use",
    )

    st.text_input(
        "Escribe tu nombre para registrar la actividad completada",
        key="teacher_name",
        placeholder="Escribe aqui tu nombre",
    )

    if st.button("Guardar resultados", type="primary", use_container_width=True):
        if st.session_state.results_saved:
            st.info("Esta sesion ya guardo resultados. Reinicia el laboratorio para crear un nuevo registro.")
        elif st.session_state.teacher_name.strip():
            try:
                saved_path, status, save_message = save_lab_results()
                if status == "saved":
                    st.session_state.results_saved = True
                    st.success(f"Resultados guardados en {saved_path}")
                    st.caption(save_message)
                else:
                    st.session_state.results_saved = True
                    st.info("Esta sesion ya tenia un registro guardado anteriormente.")
                    st.caption(save_message)
            except OSError as exc:
                st.error(f"No fue posible guardar resultados por un error de archivo: {exc}")
            except Exception as exc:
                st.error(f"Ocurrio un error inesperado al guardar resultados: {exc}")
        else:
            st.error("Ingresa el nombre del docente antes de guardar.")

    st.markdown(
        """

        <div class="step-card">

            <strong>Cierre del laboratorio</strong><br>

            Tu análisis comparativo es más importante que elegir automáticamente un ganador.

            Lo valioso es identificar qué componentes del prompt aportan precisión, pertinencia

            pedagógica y utilidad real para tu contexto.

        </div>

        """,
        unsafe_allow_html=True,
    )

    c1, c2 = st.columns([1.2, 2.4])
    with c1:
        if st.button("← Volver", use_container_width=True):
            go_back()
            st.rerun()
    with c2:
        st.button(
            "Reiniciar laboratorio",
            type="primary",
            use_container_width=True,
            on_click=reset_lab,
        )

st.markdown(
    '<div class="footer-note">Prototipo educativo. Creado por <a href="https://erikycd.github.io/" target="_blank">ECD</a></div>',
    unsafe_allow_html=True,
)