File size: 30,204 Bytes
3247c5e
 
 
 
 
 
 
 
 
 
 
e8dce15
3247c5e
e8dce15
3247c5e
e8dce15
 
3247c5e
 
 
 
 
 
 
 
 
 
e8dce15
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
3247c5e
 
 
 
 
 
 
 
 
 
e8dce15
 
 
 
3247c5e
 
 
 
 
 
 
 
 
e8dce15
3247c5e
e8dce15
 
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
3247c5e
 
 
 
 
 
 
e8dce15
 
 
 
 
 
 
 
 
 
 
 
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
 
 
 
 
 
 
 
 
 
 
 
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
3247c5e
 
 
 
e8dce15
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
 
3247c5e
 
 
 
 
 
 
 
 
e8dce15
 
 
 
3247c5e
 
 
 
 
e8dce15
 
 
 
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
3247c5e
 
 
 
 
 
 
 
 
e8dce15
 
 
 
 
 
3247c5e
e8dce15
3247c5e
 
 
e8dce15
3247c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8dce15
 
 
 
 
 
 
3247c5e
 
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
"""Piezas compartidas por «Clase guiada» y «Diagramas → código».

- Estilo UAX y cabecera.
- Trazado real de los ejemplos (se ejecutan con sys.settrace; nada está escrito a mano).
- Un único componente HTML autocontenido: código | diagrama Mermaid + animación paso a paso.
"""

import html
import io
import json
import keyword
import os
import re
import shutil
import sys
import tempfile
import threading
import tokenize
import types

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


DARK = "#101820"
BLUE = "#009FE3"
TRACE_FILE = "<ejemplo>"
MAX_EVENTS = 4000
_RUN_LOCK = threading.Lock()
BUILTINS = {"print", "input", "range", "int", "float", "str", "len", "bool", "list", "dict"}
STAGES = ["entrada", "proceso", "decision", "bucle", "salida"]


# --------------------------------------------------------------------------- estilo

def page_style():
    st.markdown(
        f"""
        <style>
          .stApp {{ background: #F5F8FA; }}
          .block-container {{ max-width: 1240px; padding-top: 2.6rem; }}
          .uax-hero {{
            background: {DARK}; border-left: 10px solid {BLUE}; border-radius: 16px;
            padding: 1.6rem 2rem; margin-bottom: 1.4rem;
            display: flex; align-items: center; justify-content: space-between; gap: 1.5rem;
          }}
          .uax-hero h1 {{ color: #fff; margin: 0; padding: 0; font-size: 2rem; line-height: 1.2; }}
          .uax-hero p {{ color: #CFE3EE; margin: .45rem 0 0; font-size: 1.05rem; }}
          .uax-logo {{ color: #fff; font-size: 2rem; font-weight: 800; letter-spacing: .02em; white-space: nowrap; }}
          .uax-logo span {{ color: {BLUE}; }}
          .uax-topic {{
            display: flex; align-items: center; gap: .8rem; margin: 2.2rem 0 .8rem;
            padding-bottom: .55rem; border-bottom: 3px solid {BLUE};
          }}
          .uax-topic b {{
            background: {BLUE}; color: #fff; min-width: 2.3rem; height: 2.3rem; border-radius: 50%;
            display: inline-flex; align-items: center; justify-content: center; font-size: 1.15rem;
          }}
          .uax-topic span {{ color: {DARK}; font-size: 1.65rem; font-weight: 750; }}
          .uax-label {{
            color: #4A5B68; font-size: .82rem; font-weight: 700; letter-spacing: .08em;
            text-transform: uppercase; margin: 1.1rem 0 .35rem;
          }}
          .uax-example {{ color: {DARK}; font-size: 1.15rem; font-weight: 700; margin: 1.3rem 0 .2rem; }}
          div.stButton > button[kind="primary"] {{
            background: {BLUE}; border-color: {BLUE}; color: #fff; font-weight: 700;
            font-size: 1.02rem; padding: .55rem 1.3rem;
          }}
          div.stButton > button[kind="primary"]:hover {{ background: #0088C4; border-color: #0088C4; color: #fff; }}
        </style>
        """,
        unsafe_allow_html=True,
    )


def hero(title, subtitle):
    st.markdown(
        f"""<div class="uax-hero"><div><h1>{html.escape(title)}</h1><p>{html.escape(subtitle)}</p></div>
        <div class="uax-logo">UA<span>X</span></div></div>""",
        unsafe_allow_html=True,
    )


def topic(number, title):
    st.markdown(
        f'<div class="uax-topic"><b>{number}</b><span>{html.escape(title)}</span></div>',
        unsafe_allow_html=True,
    )


def label(text):
    st.markdown(f'<div class="uax-label">{html.escape(text)}</div>', unsafe_allow_html=True)


def example_title(text):
    st.markdown(f'<div class="uax-example">{html.escape(text)}</div>', unsafe_allow_html=True)


# --------------------------------------------------------------------------- utilidades de código

def highlight_lines(code):
    """Devuelve una lista con el HTML coloreado de cada línea (sin dependencias externas)."""
    lines = code.splitlines()
    spans = [[] for _ in lines]
    try:
        for tok in tokenize.generate_tokens(io.StringIO(code + "\n").readline):
            name = tokenize.tok_name[tok.type]
            if name == "COMMENT":
                cls = "c"
            elif name == "STRING" or name.startswith("FSTRING"):
                cls = "s"
            elif name == "NUMBER":
                cls = "n"
            elif name == "NAME" and keyword.iskeyword(tok.string):
                cls = "k"
            elif name == "NAME" and tok.string in BUILTINS:
                cls = "b"
            else:
                continue
            (row, start), (end_row, end) = tok.start, tok.end
            if row == end_row and row <= len(lines) and end > start:
                spans[row - 1].append((start, end, cls))
    except (tokenize.TokenError, IndentationError):
        pass
    result = []
    for line, line_spans in zip(lines, spans):
        out, pos = [], 0
        for start, end, cls in sorted(line_spans):
            if start < pos:
                continue
            out.append(html.escape(line[pos:start]))
            out.append(f'<span class="{cls}">{html.escape(line[start:end])}</span>')
            pos = end
        out.append(html.escape(line[pos:]))
        result.append("".join(out))
    return result


def _lookup(mapping, line_number, text):
    """Busca por número de línea o por el primer fragmento contenido en la línea."""
    if not mapping:
        return None
    if line_number in mapping:
        return mapping[line_number]
    for key, value in mapping.items():
        if isinstance(key, str) and key in text:
            return value
    return None


def _indent(text):
    return len(text) - len(text.lstrip())


def _code(text):
    return f"<code>{html.escape(str(text))}</code>"


def line_kind(text):
    clean = text.strip()
    if "input(" in clean:
        return "entrada"
    if clean.startswith(("if ", "elif ", "else", "except")):
        return "decision"
    if clean.startswith(("for ", "while ")) or clean in ("break", "continue"):
        return "bucle"
    if clean.startswith("print("):
        return "salida"
    return "proceso"


# --------------------------------------------------------------------------- trazado real

def _short(text, limit=320):
    return text if len(text) <= limit else text[:limit] + " …"


def _snapshot(env, frame):
    values = {}

    def add(name, value):
        if isinstance(value, (types.ModuleType, types.FunctionType, types.MethodType, type)):
            return
        if type(value).__module__ == "__main__" and hasattr(value, "__dict__"):
            values[name] = f"objeto {type(value).__name__}"
            for attr, attr_value in vars(value).items():
                values[f"{name}.{attr}"] = _short(repr(attr_value))
        else:
            text = repr(value)
            if not (text.startswith("<") and text.endswith(">")):  # ficheros abiertos y similares
                values[name] = _short(text)

    for name, value in env.items():
        if not name.startswith("__") and name not in ("print", "input"):
            add(name, value)
    if frame is not None and frame.f_code.co_flags & 0x1:  # dentro de una función o método
        for name, value in frame.f_locals.items():
            add(name, value)
    return values


def _changes_text(changed, before, after):
    parts = []
    for name in changed[:4]:
        if name in before:
            parts.append(f"{_code(name)}: {_code(before[name])} → {_code(after[name])}")
        else:
            parts.append(f"{_code(name)} = {_code(after[name])}")
    return "; ".join(parts)


@st.cache_data(show_spinner=False)
def trace_program(code, inputs=()):
    """Ejecuta el ejemplo y devuelve (pasos, salida completa, variables finales)."""
    lines = code.splitlines()
    out, pending, events, errors = [], list(inputs), [], {}

    def fake_print(*args, sep=" ", end="\n", **_):
        out.append(sep.join(str(a) for a in args) + end)

    def fake_input(prompt=""):
        value = pending.pop(0) if pending else ""
        out.append(f"{prompt}{value}\n")
        return value

    env = {"__name__": "__main__", "print": fake_print, "input": fake_input}

    def tracer(frame, event, arg):
        if frame.f_code.co_filename != TRACE_FILE:
            return None
        if len(events) > MAX_EVENTS:
            raise RuntimeError("El ejemplo tiene demasiados pasos.")
        is_function = bool(frame.f_code.co_flags & 0x1)
        if event == "line":
            events.append(("line", frame.f_lineno, id(frame), frame.f_code.co_name, is_function,
                           _snapshot(env, frame), "".join(out)))
        elif event == "exception" and events:
            errors[len(events) - 1] = arg[0].__name__
        elif event == "return":
            back = frame.f_back
            caller = back.f_lineno if back is not None and back.f_code.co_filename == TRACE_FILE else None
            events.append(("return", caller if is_function else None, id(frame), frame.f_code.co_name,
                           is_function, _snapshot(env, frame), "".join(out)))
        return tracer

    # Los ejemplos que crean ficheros trabajan en una carpeta temporal propia.
    with _RUN_LOCK:
        previous, home, workdir = sys.gettrace(), os.getcwd(), tempfile.mkdtemp(prefix="aula_")
        os.chdir(workdir)
        sys.settrace(tracer)
        try:
            exec(compile(code, TRACE_FILE, "exec"), env)
        except Exception as error:  # el ejemplo se muestra igualmente, con su error
            out.append(f"{type(error).__name__}: {error}\n")
        finally:
            sys.settrace(previous)
            os.chdir(home)
            shutil.rmtree(workdir, ignore_errors=True)

    final_vars, final_out = _snapshot(env, None), "".join(out)
    steps = []
    for index, (etype, line, frame_id, func, _is_fn, before, out_before) in enumerate(events):
        if line is None:
            continue
        if index + 1 < len(events):
            nxt = events[index + 1]
            after, out_after = nxt[5], nxt[6]
        else:
            nxt, after, out_after = None, final_vars, final_out
        changed = [name for name, value in after.items() if before.get(name) != value]
        printed = out_after[len(out_before):]
        text = lines[line - 1]
        clean = text.strip()
        next_line = next((e for e in events[index + 1:] if e[0] == "line"), None)
        between = lines[line:next_line[1]] if next_line is not None and next_line[1] > line else []
        entered = (
            bool(between) and next_line[2] == frame_id
            and all(_indent(row) > _indent(text) for row in between if row.strip() and not row.strip().startswith("#"))
        )
        if clean.startswith("class ") and steps and steps[-1]["line"] == line:
            continue  # la línea «class» genera dos eventos; basta con uno
        kind = line_kind(text)
        change_text = _changes_text(changed, before, after)

        if etype == "return":
            if not changed:
                continue
            kind = "proceso"
            note = f"Termina {_code(func)} y el programa vuelve a la línea {line}. {change_text}"
        elif (next_line is not None and next_line[2] == frame_id and not clean.startswith("except")
              and lines[next_line[1] - 1].strip().startswith("except") and index in errors):
            kind = "proceso"
            note = (f"<b>Error.</b> Esta línea falla con {_code(errors[index])}: Python abandona el "
                    "<code>try</code> y busca un <code>except</code> que lo recoja.")
        elif clean == "try:":
            note = "Empieza el bloque <code>try</code>: Python vigila si alguna de sus líneas produce un error."
        elif clean.startswith("except"):
            name = clean[6:].rstrip(":").strip() or "cualquiera"
            note = (f"<b>Decisión.</b> ¿El error es de tipo {_code(name)}? → <b>{'Sí' if entered else 'No'}</b>. "
                    + ("Se ejecuta este bloque." if entered else "Se prueba el siguiente <code>except</code>."))
        elif clean.startswith("with "):
            note = ("<code>with</code> abre el recurso al entrar en el bloque y lo cierra "
                    "automáticamente al salir.")
        elif "input(" in clean:
            note = f"<b>Entrada.</b> El programa pide un dato y el usuario escribe. {change_text}"
        elif clean.startswith(("if ", "elif ")):
            cond = clean.split(" ", 1)[1].rstrip(":")
            note = (f"<b>Decisión.</b> ¿{_code(cond)}? → <b>{'Sí' if entered else 'No'}</b>. "
                    + ("Se ejecuta el bloque de esta rama." if entered else "Se salta este bloque."))
        elif clean.startswith("for "):
            if entered:
                note = f"<b>Bucle.</b> Queda un elemento por recorrer: {change_text}. Se ejecuta el cuerpo."
            else:
                note = "<b>Bucle.</b> No quedan elementos: el <code>for</code> termina y el programa sigue."
        elif clean.startswith("while "):
            cond = clean[6:].rstrip(":")
            note = (f"<b>Bucle.</b> ¿{_code(cond)}? → <b>{'Sí' if entered else 'No'}</b>. "
                    + ("Se repite el cuerpo." if entered else "El <code>while</code> termina."))
        elif clean == "break":
            note = "<b>break.</b> Se sale del bucle inmediatamente."
        elif clean.startswith("class "):
            note = (f"Se define la clase {_code(clean[6:].rstrip(':'))}: es el molde. "
                    "Todavía no existe ningún objeto.")
        elif clean.startswith("def "):
            note = (f"Se define {_code(clean[4:].split('(')[0])}. Su código queda guardado; "
                    "no se ejecuta hasta que alguien lo llame.")
        elif nxt is not None and nxt[0] == "line" and nxt[2] != frame_id and nxt[4]:
            kind = "proceso"
            note = f"<b>Llamada.</b> El programa salta al código de {_code(nxt[3])}. {change_text}"
        elif clean.startswith("print("):
            note = f"<b>Salida.</b> Se escribe en pantalla: {_code(printed.rstrip())}"
        elif change_text:
            note = f"<b>Proceso.</b> {change_text}"
        else:
            note = "<b>Proceso.</b> Se ejecuta la instrucción."

        steps.append({
            "line": line, "kind": kind, "note": note, "out": out_after,
            "vars": [[name, value, name in changed] for name, value in after.items()],
        })
    return steps, final_out, final_vars


def build_steps(code, notes):
    """Pasos en orden de escritura (para construir el programa línea a línea)."""
    steps = []
    for number, text in enumerate(code.splitlines(), 1):
        clean = text.strip()
        if not clean or clean.startswith("#"):
            continue
        note = _lookup(notes, number, text) or "Esta línea traduce el siguiente símbolo del diagrama."
        steps.append({"line": number, "kind": line_kind(text), "note": note, "out": "", "vars": []})
    return steps


# --------------------------------------------------------------------------- componente visual

def player(example, mode, flow_first=False):
    """mode: 'static' (código + diagrama), 'build' (línea a línea) o 'run' (ejecución animada)."""
    code = example["code"]
    lines = code.splitlines()
    nodes = example.get("nodes", {})
    hints = example.get("hints", {})

    if mode == "run":
        steps, _, _ = trace_program(code, tuple(example.get("inputs", ())))
        steps = [dict(step) for step in steps]
        for step in steps:
            hint = _lookup(hints, step["line"], lines[step["line"] - 1])
            if hint:
                step["note"] += f' <span class="hint">{hint}</span>'
        steps.append({"line": None, "kind": None, "node": "F", "out": steps[-1]["out"] if steps else "",
                      "note": "<b>Fin del programa.</b> Debajo tienes la salida completa y la explicación.",
                      "vars": [[n, v, False] for n, v, _ in steps[-1]["vars"]] if steps else []})
    elif mode == "build":
        steps = build_steps(code, example.get("build_notes", {}))
    else:
        steps = []

    last_node = "S"
    for step in steps:
        if "node" not in step:
            step["node"] = _lookup(nodes, step["line"], lines[step["line"] - 1]) or last_node
        last_node = step["node"]

    rows = example.get("rows") or len(set(re.findall(r"(\w+)(?:\(\[|\[|\{)", example["flow"]))) or 6
    scroll = rows > 13  # diagramas grandes: tamaño legible con desplazamiento
    panel = max(300, min(820, max(len(lines) * 22 + 70, 640 if scroll else rows * 66 + 70)))
    extra = {"static": 0, "build": 215, "run": 425}[mode]
    longest = max((len(row) for row in lines), default=0)
    data = {
        "mode": mode, "lines": highlight_lines(code), "flow": example["flow"], "steps": steps,
        "panel": panel, "font": 14.5 if longest <= 62 else 13 if longest <= 74 else 12, "flowFirst": flow_first, "stages": STAGES, "scroll": scroll,
    }
    payload = json.dumps(data, ensure_ascii=False).replace("</", "<\\/")
    components.html(_TEMPLATE.replace("__DATA__", payload), height=panel + extra + 16, scrolling=True)


def results(example):
    """Salida, variables finales y explicación, con componentes nativos de Streamlit."""
    _, output, variables = trace_program(example["code"], tuple(example.get("inputs", ())))
    left, right = st.columns(2, gap="large")
    with left:
        with st.container(border=True):
            st.markdown("**Salida del programa**")
            st.code(output.rstrip("\n") or "(este programa no escribe nada en pantalla)", language="text")
            if example.get("inputs"):
                typed = ", ".join(f"`{value}`" for value in example["inputs"])
                st.caption(f"Datos que teclea el usuario en esta ejecución: {typed}")
    with right:
        with st.container(border=True):
            st.markdown("**Variables al terminar**")
            if variables:
                table = "| Variable | Valor |\n|---|---|\n" + "\n".join(
                    f"| `{name}` | `{_short(value, 140).replace(chr(10), ' ↵ ').replace('|', chr(92) + '|')}` |"
                    for name, value in variables.items()
                )
                st.markdown(table)
            else:
                st.caption("No queda ninguna variable.")
    with st.container(border=True):
        st.markdown("**¿Por qué sale este resultado?**")
        st.markdown(example["why"])


def toggle(key):
    st.session_state[key] = not st.session_state.get(key, False)


_TEMPLATE = r"""
<style>
  * { box-sizing: border-box; }
  [hidden] { display: none !important; }
  body { margin: 0; font-family: "Segoe UI", Arial, sans-serif; color: #101820; background: transparent; }
  .grid { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr); gap: 14px; }
  .panel { border-radius: 12px; overflow: hidden; display: flex; flex-direction: column; }
  .panel h3 { margin: 0; padding: 9px 14px; font-size: 13px; letter-spacing: .08em; text-transform: uppercase; }
  .code { background: #101820; }
  .code h3 { color: #8FD3F2; border-bottom: 1px solid #26333F; }
  .flow { background: #fff; border: 1px solid #D5E0E8; }
  .flow h3 { color: #4A5B68; border-bottom: 1px solid #E3EBF0; }
  .src { flex: 1; padding: 10px 0; font: 14.5px/22px Consolas, "Cascadia Mono", Menlo, monospace; color: #D7E6F0; overflow: auto; }
  .ln { display: flex; white-space: pre; border-left: 4px solid transparent; padding-right: 12px; }
  .ln .no { width: 34px; text-align: right; color: #5E7384; padding-right: 12px; user-select: none; flex: none; }
  .ln.cur { background: rgba(0,159,227,.30); border-left-color: #009FE3; }
  .ln.cur .no { color: #fff; font-weight: 700; }
  .ln.hid .tx { visibility: hidden; }
  .k { color: #C99BE0; } .s { color: #E3A27F; } .n { color: #B9D8A6; } .c { color: #7FAE6B; } .b { color: #E6DC9A; }
  #flow { flex: 1; display: flex; align-items: center; justify-content: center; padding: 10px; min-height: 0; }
  #flow svg { max-width: 100% !important; width: 100%; height: 100%; }
  #flow.scroll { display: block; overflow: auto; }
  #flow.scroll svg { height: auto; }
  #flow .msg { color: #7A8B97; font-size: 14px; text-align: center; }
  #flow .node.done rect, #flow .node.done polygon, #flow .node.done path { fill: #D6F0FB !important; }
  #flow .node.active rect, #flow .node.active polygon, #flow .node.active path {
    fill: #009FE3 !important; stroke: #101820 !important; stroke-width: 3px !important; }
  #flow .node.active .nodeLabel, #flow .node.active text { color: #fff !important; fill: #fff !important; }
  #flow .node.active { animation: pop 1s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
  @keyframes pop { 50% { filter: drop-shadow(0 0 7px rgba(0,159,227,.9)); } }
  .player { margin-top: 14px; background: #fff; border: 1px solid #D5E0E8; border-radius: 12px; padding: 12px 14px; }
  .bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
  button { font: 600 14px "Segoe UI", Arial, sans-serif; padding: 7px 13px; border-radius: 8px; cursor: pointer;
           border: 1px solid #B9C8D3; background: #fff; color: #101820; }
  button:hover:not(:disabled) { border-color: #009FE3; color: #007DB3; }
  button:disabled { opacity: .4; cursor: default; }
  button.main { background: #009FE3; border-color: #009FE3; color: #fff; }
  button.main:hover:not(:disabled) { background: #0088C4; color: #fff; }
  .count { margin-left: auto; color: #4A5B68; font-size: 13px; font-weight: 600; }
  .stages { display: flex; gap: 6px; margin-top: 11px; flex-wrap: wrap; }
  .stage { flex: 1; min-width: 86px; text-align: center; padding: 7px 6px; border-radius: 8px; font-size: 13px;
           font-weight: 700; background: #EDF2F5; color: #7A8B97; transition: all .25s; }
  .stage.on { background: #101820; color: #fff; box-shadow: inset 0 -4px 0 #009FE3; }
  .note { margin-top: 11px; background: #E6F5FC; border-left: 5px solid #009FE3; border-radius: 8px;
          padding: 10px 13px; font-size: 15px; line-height: 1.5; min-height: 66px; }
  .note code, td code { font-family: Consolas, Menlo, monospace; background: rgba(16,24,32,.08); padding: 1px 5px; border-radius: 4px; font-size: 13.5px; }
  .note .hint { display: block; margin-top: 4px; color: #33505F; }
  .state { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 11px; }
  .box { border: 1px solid #D5E0E8; border-radius: 8px; height: 190px; display: flex; flex-direction: column; overflow: hidden; }
  .box h4 { margin: 0; padding: 6px 10px; font-size: 12px; letter-spacing: .08em; text-transform: uppercase; color: #4A5B68; background: #F1F5F8; }
  .box .body { flex: 1; overflow: auto; }
  table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
  td { padding: 4px 10px; border-bottom: 1px solid #EEF2F5; vertical-align: top; }
  td:first-child { width: 42%; white-space: nowrap; }
  td code { white-space: pre-wrap; word-break: break-word; }
  tr.chg td { background: #FFF4CC; }
  tr.chg td:first-child::after { content: " ● cambia"; color: #B26A00; font-size: 11px; font-weight: 700; }
  pre.out { margin: 0; padding: 8px 10px; font: 13.5px/19px Consolas, Menlo, monospace; background: #101820; color: #E4EEF4; min-height: 100%; white-space: pre-wrap; }
  .empty { color: #8A9AA6; padding: 10px; font-size: 13px; }
  @media (max-width: 760px) { .grid, .state { grid-template-columns: 1fr; } }
</style>
<div class="grid" id="grid">
  <section class="panel code" id="codePanel"><h3>Código Python</h3><div class="src" id="src"></div></section>
  <section class="panel flow" id="flowPanel"><h3>Diagrama de flujo</h3><div id="flow"><div class="msg">Cargando diagrama…</div></div></section>
</div>
<div class="player" id="player" hidden>
  <div class="bar">
    <button id="reset">⏮ Reiniciar</button>
    <button id="prev">◀ Anterior</button>
    <button id="play" class="main">⏸ Pausa</button>
    <button id="next">Siguiente ▶</button>
    <button id="end">⏭ Final</button>
    <button id="speed">Velocidad ×1</button>
    <span class="count" id="count"></span>
  </div>
  <div class="stages" id="stages"></div>
  <div class="note" id="note"></div>
  <div class="state" id="state">
    <div class="box"><h4>Variables en memoria</h4><div class="body" id="vars"></div></div>
    <div class="box"><h4>Salida en pantalla</h4><div class="body"><pre class="out" id="out"></pre></div></div>
  </div>
</div>
<script type="module">
  const D = __DATA__;
  const $ = (id) => document.getElementById(id);
  const names = { entrada: "Entrada", proceso: "Proceso", decision: "Decisión", bucle: "Bucle", salida: "Salida" };
  const esc = (t) => String(t).replace(/&/g, "&amp;").replace(/</g, "&lt;");

  $("codePanel").style.height = $("flowPanel").style.height = D.panel + "px";
  $("src").style.fontSize = D.font + "px";
  if (D.flowFirst) $("grid").style.gridTemplateColumns = "minmax(0, 1fr) minmax(0, 1.15fr)";
  if (D.flowFirst) $("grid").insertBefore($("flowPanel"), $("codePanel"));
  $("src").innerHTML = D.lines.map((h, i) =>
    `<div class="ln" data-n="${i + 1}"><span class="no">${i + 1}</span><span class="tx">${h || " "}</span></div>`).join("");
  $("stages").innerHTML = D.stages.map((s) => `<div class="stage" data-s="${s}">${names[s]}</div>`).join("");

  const build = D.mode === "build", run = D.mode === "run";
  let idx = build ? -1 : 0, timer = null, nodeEls = {}, speed = 0;
  const delays = [1700, 850, 350];
  if (D.scroll) $("flow").classList.add("scroll");

  function show() {
    const step = idx >= 0 ? D.steps[idx] : null;
    const visible = build ? (step ? step.line : 0) : Infinity;
    document.querySelectorAll(".ln").forEach((el) => {
      const n = +el.dataset.n;
      el.classList.toggle("cur", !!step && step.line === n);
      el.classList.toggle("hid", n > visible);
    });
    const current = document.querySelector(".ln.cur"), box = $("src");
    if (current && box.scrollHeight > box.clientHeight) {
      box.scrollTop = current.offsetTop - box.offsetTop - box.clientHeight / 2;
    }
    Object.values(nodeEls).forEach((el) => el.classList.remove("active", "done"));
    if (D.steps.length) {
      nodeEls["S"]?.classList.add("done");
      for (let i = 0; i < idx; i++) nodeEls[D.steps[i].node]?.classList.add("done");
      if (step) { nodeEls[step.node]?.classList.remove("done"); nodeEls[step.node]?.classList.add("active"); }
      if (D.scroll && step && nodeEls[step.node]) {
        const f = $("flow"), r = nodeEls[step.node].getBoundingClientRect(), fr = f.getBoundingClientRect();
        f.scrollTop += r.top - fr.top - f.clientHeight / 2 + r.height / 2;
      }
    }
    if (!D.steps.length) return;
    document.querySelectorAll(".stage").forEach((el) => el.classList.toggle("on", !!step && el.dataset.s === step.kind));
    $("note").innerHTML = step ? step.note
      : "<b>Antes de escribir código:</b> mirad el diagrama y localizad la entrada, el proceso, la decisión y la salida. Después pulsa «Siguiente línea».";
    $("count").textContent = step ? `Paso ${idx + 1} de ${D.steps.length}` : `${D.steps.length} líneas por escribir`;
    $("prev").disabled = idx <= (build ? -1 : 0);
    $("next").disabled = idx >= D.steps.length - 1;
    if (run && step) {
      $("vars").innerHTML = step.vars.length
        ? "<table>" + step.vars.map(([n, v, c]) => `<tr class="${c ? "chg" : ""}"><td><code>${esc(n)}</code></td><td><code>${esc(v)}</code></td></tr>`).join("") + "</table>"
        : '<div class="empty">Todavía no hay variables.</div>';
      $("out").textContent = step.out;
      $("out").parentElement.scrollTop = 1e6;
      const chg = $("vars").querySelector("tr.chg");
      if (chg) $("vars").scrollTop = Math.max(0, chg.offsetTop - 40);
    }
  }
  function stop() { clearInterval(timer); timer = null; $("play").textContent = "▶ Reproducir"; }
  function start() {
    if (idx >= D.steps.length - 1) idx = 0;
    show();
    $("play").textContent = "⏸ Pausa";
    timer = setInterval(() => { if (idx >= D.steps.length - 1) return stop(); idx++; show(); }, delays[speed]);
  }
  function go(delta) { stop(); idx = Math.max(build ? -1 : 0, Math.min(D.steps.length - 1, idx + delta)); show(); }

  if (D.steps.length) {
    $("player").hidden = false;
    $("next").onclick = () => go(1);
    $("prev").onclick = () => go(-1);
    $("reset").onclick = () => { stop(); idx = build ? -1 : 0; show(); };
    $("play").onclick = () => (timer ? stop() : start());
    $("end").onclick = () => { stop(); idx = D.steps.length - 1; show(); };
    $("speed").onclick = () => {
      speed = (speed + 1) % delays.length;
      $("speed").textContent = "Velocidad ×" + [1, 2, 5][speed];
      if (timer) { stop(); start(); }
    };
    document.addEventListener("keydown", (e) => { if (e.key === "ArrowRight") go(1); if (e.key === "ArrowLeft") go(-1); });
    if (build) { $("play").hidden = true; $("end").hidden = true; $("speed").hidden = true; $("state").hidden = true; $("next").textContent = "Siguiente línea ▶"; $("next").classList.add("main"); }
  }
  show();

  async function draw() {
  try {
    const mermaid = (await import("https://cdn.jsdelivr.net/npm/mermaid@10.9.3/dist/mermaid.esm.min.mjs")).default;
    mermaid.initialize({ startOnLoad: false, theme: "base", flowchart: { curve: "linear", htmlLabels: true },
      themeVariables: { primaryColor: "#FFFFFF", primaryBorderColor: "#101820", primaryTextColor: "#101820",
        lineColor: "#4A5B68", fontFamily: "Segoe UI, Arial, sans-serif", fontSize: "15px" } });
    const { svg } = await mermaid.render("g" + Math.random().toString(36).slice(2), D.flow);
    $("flow").innerHTML = svg;
    $("flow").querySelectorAll("g.node").forEach((el) => {
      const m = /^flowchart-(.+)-\d+$/.exec(el.id);
      if (m) nodeEls[m[1]] = el;
    });
  } catch (error) {
    $("flow").innerHTML = '<div class="msg">No se pudo cargar el diagrama (revisa la conexión a internet).</div>';
    console.error(error);
  }
  show();
  if (run) setTimeout(start, 700);
  }
  if ("IntersectionObserver" in window) {
    const watcher = new IntersectionObserver((entries) => {
      if (entries.some((entry) => entry.isIntersecting)) { watcher.disconnect(); draw(); }
    }, { rootMargin: "600px" });
    watcher.observe(document.body);
  } else { draw(); }
</script>
"""