import marimo

__generated_with = "0.15.2"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    return (mo,)


@app.cell
def _():
    from modraw import Draw
    from mohtml import img
    return Draw, img


@app.cell
def _(Draw, mo):
    widget = mo.ui.anywidget(Draw(width=1000, height=450))

    widget
    return (widget,)


@app.cell
def _(img, mo, widget):
    def safe_draw_preview(widget, mode="auto"):
        """
        Render the Draw content without raising.
        mode:
          - "auto": prefer base64; fallback to PIL
          - "base64": only base64
          - "pil": only PIL
          - "both": show both (for debugging)
        """
        # Read base64 safely
        b64 = None
        try:
            v = getattr(widget, "value", None)
            if isinstance(v, dict):
                b64 = v.get("base64")
        except Exception:
            b64 = None

        # Get PIL safely
        pil_img = None
        if hasattr(widget, "get_pil"):
            try:
                pil_img = widget.get_pil()
            except Exception:
                pil_img = None

        # Decide what to render to avoid duplication
        children = []
        if mode == "auto":
            if b64:
                children = [img(src=b64)]
            elif pil_img is not None:
                children = [pil_img]
        elif mode == "base64":
            if b64:
                children = [img(src=b64)]
        elif mode == "pil":
            if pil_img is not None:
                children = [pil_img]
        elif mode == "both":
            if b64:
                children.append(img(src=b64))
            if pil_img is not None:
                children.append(pil_img)

        return mo.vstack(children) if children else mo.md("Dibuja algo para previsualizar.")

    safe_draw_preview(widget, "base64")# fuerza solo base64  
    return


if __name__ == "__main__":
    app.run()
