/* ============================================================
   ONLYCLEAN — Admin: routines + fixed content editors
   (app/admin_routines.jsx)
   ============================================================ */

const INTENSITY_OPTS = [
  { v: "high", l: "High intensity" },
  { v: "low", l: "Low intensity" },
  { v: "recovery", l: "Recovery" },
  { v: "rest", l: "Full rest" },
];

/* ---------------- Routines list ---------------- */
function RoutinesPanel() {
  const [routines, setRoutines] = useState(null);
  const [editing, setEditing] = useState(null);   // "new-workout" | "new-recovery" | routine obj
  const [confirm, setConfirm] = useState(null);
  const toast = useToast();
  const load = () => window.DB.listRoutines().then(setRoutines);
  useEffect(() => { load(); }, []);

  if (editing) {
    const routine = editing === "new-workout" ? window.DB.newRoutine()
                  : editing === "new-recovery" ? window.DB.newRecovery()
                  : editing;
    return <RoutineEditor routine={routine} onClose={() => { setEditing(null); load(); }} />;
  }
  if (!routines) return <div className="panel">Cargando…</div>;

  const badge = (i) => i === "high" ? "var(--coral)" : i === "low" ? "var(--low)" : i === "rest" ? "#333" : "#8b97a4";
  const workouts = routines.filter((r) => r.intensity !== "recovery");
  const recoveries = routines.filter((r) => r.intensity === "recovery");

  const Row = ({ r }) => (
    <div className="adm-list-item" key={r.id}>
      <span className="av" style={{ background: badge(r.intensity), color: "#fff" }}>
        <RecoIcon name={r.intensity === "recovery" ? (r.icon || "heart") : "dumbbell"} style={{ width: 17, height: 17 }} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="nm">{r.title}</div>
        <div className="em">{r.intensity === "recovery" ? "Recuperación" : r.intensity} · {r.blocks.length} bloque(s)</div>
      </div>
      <button className="icon-btn" title="Duplicar" onClick={async () => { const dup = JSON.parse(JSON.stringify(r)); dup.id = ""; dup.title = r.title + " (copia)"; await window.DB.saveRoutine(dup); toast("Duplicada"); load(); }}><Icon name="copy" style={{ width: 15, height: 15 }} /></button>
      <button className="icon-btn" onClick={() => setEditing(r)}><Icon name="edit" style={{ width: 16, height: 16 }} /></button>
      <button className="icon-btn danger" onClick={() => setConfirm(r)}><Icon name="trash" style={{ width: 16, height: 16 }} /></button>
    </div>
  );

  return (
    <div>
      <div className="panel">
        <div className="row-between" style={{ marginBottom: 16 }}>
          <div><h3>Rutinas de entrenamiento</h3><div className="sub" style={{ margin: 0 }}>{workouts.length} rutina(s) · se enlazan a los días del calendario</div></div>
          <Pill onClick={() => setEditing("new-workout")}><Icon name="plus" style={{ width: 16, height: 16 }} /> Nueva rutina</Pill>
        </div>
        <div className="adm-list">
          {workouts.map((r) => <Row r={r} key={r.id} />)}
          {workouts.length === 0 && <p className="sub">Aún no hay rutinas de entrenamiento.</p>}
        </div>
      </div>

      <div className="panel">
        <div className="row-between" style={{ marginBottom: 16 }}>
          <div><h3>Tipos de recuperación</h3><div className="sub" style={{ margin: 0 }}>{recoveries.length} tipo(s) · Ice bath, Sauna, Fisioterapia… se asignan como recuperación recomendada de un día</div></div>
          <Pill onClick={() => setEditing("new-recovery")}><Icon name="plus" style={{ width: 16, height: 16 }} /> Nueva recuperación</Pill>
        </div>
        <div className="adm-list">
          {recoveries.map((r) => <Row r={r} key={r.id} />)}
          {recoveries.length === 0 && <p className="sub">Aún no hay tipos de recuperación.</p>}
        </div>
      </div>

      <Confirm open={!!confirm} text={`¿Eliminar "${confirm?.title}"? Los días que lo usen quedarán sin esa asignación.`}
        onNo={() => setConfirm(null)}
        onYes={async () => { await window.DB.deleteRoutine(confirm.id); setConfirm(null); toast("Eliminado"); load(); }} />
    </div>
  );
}

/* ---------------- Routine editor ---------------- */
function RoutineEditor({ routine, onClose }) {
  const [r, setR] = useState(() => JSON.parse(JSON.stringify(routine)));
  const isRecovery = r.intensity === "recovery";
  const toast = useToast();
  const set = (k, v) => setR((p) => ({ ...p, [k]: v }));

  const setBlock = (bi, patch) => setR((p) => { const blocks = p.blocks.map((b) => ({ ...b, items: b.items.map((i) => ({ ...i })) })); blocks[bi] = { ...blocks[bi], ...patch }; return { ...p, blocks }; });
  const addBlock = () => setR((p) => ({ ...p, blocks: [...p.blocks, window.DB.newBlock()] }));
  const delBlock = (bi) => setR((p) => ({ ...p, blocks: p.blocks.filter((_, i) => i !== bi) }));
  const moveBlock = (bi, dir) => setR((p) => { const blocks = [...p.blocks]; const ni = bi + dir; if (ni < 0 || ni >= blocks.length) return p; [blocks[bi], blocks[ni]] = [blocks[ni], blocks[bi]]; return { ...p, blocks }; });

  const setItem = (bi, ii, patch) => setR((p) => { const blocks = p.blocks.map((b) => ({ ...b, items: b.items.map((i) => ({ ...i })) })); blocks[bi].items[ii] = { ...blocks[bi].items[ii], ...patch }; return { ...p, blocks }; });
  const addItem = (bi) => setR((p) => { const blocks = p.blocks.map((b) => ({ ...b, items: b.items.map((i) => ({ ...i })) })); blocks[bi].items.push(window.DB.newItem()); return { ...p, blocks }; });
  const delItem = (bi, ii) => setR((p) => { const blocks = p.blocks.map((b) => ({ ...b, items: b.items.map((i) => ({ ...i })) })); blocks[bi].items = blocks[bi].items.filter((_, j) => j !== ii); return { ...p, blocks }; });

  async function save() {
    if (!r.title.trim()) { toast("Pon un título"); return; }
    await window.DB.saveRoutine(r);
    toast("Rutina guardada");
    onClose();
  }

  return (
    <div>
      <div className="panel">
        <div className="row-between" style={{ marginBottom: 16 }}>
          <BackPill onClick={onClose} label={isRecovery ? "Volver" : "Volver a rutinas"} />
          <Pill onClick={save}><Icon name="check" style={{ width: 16, height: 16 }} /> {isRecovery ? "Guardar recuperación" : "Guardar rutina"}</Pill>
        </div>
        <h3>{routine.id ? (isRecovery ? "Editar recuperación" : "Editar rutina") : (isRecovery ? "Nueva recuperación" : "Nueva rutina")}</h3>
        <div className="sub">{isRecovery ? "Tipo de recuperación (Ice bath, Sauna, Fisioterapia…). Mismo formato de bloques; cada ítem admite una URL de video." : "Estructura por bloques. Cada ejercicio admite una URL de video (YouTube, Vimeo o .mp4)."}</div>
        <div className="grid2">
          <div className="field"><label>Título</label><input className="input" value={r.title} onChange={(e) => set("title", e.target.value)} /></div>
          {isRecovery
            ? <div className="field"><label>Icono (para el badge del calendario)</label>
                <select className="input" value={r.icon || "heart"} onChange={(e) => set("icon", e.target.value)}>
                  {RECOVERY_ICONS.map((o) => <option key={o.v} value={o.v}>{o.l}</option>)}
                </select>
              </div>
            : <div className="field"><label>Intensidad</label>
                <select className="input" value={r.intensity} onChange={(e) => set("intensity", e.target.value)}>
                  {INTENSITY_OPTS.filter((o) => o.v !== "recovery").map((o) => <option key={o.v} value={o.v}>{o.l}</option>)}
                </select>
              </div>}
        </div>
        {!isRecovery && <div className="field"><label>Warm-up</label><input className="input" value={r.warmup} onChange={(e) => set("warmup", e.target.value)} placeholder="Articular · Movilidad · Muscular" /></div>}
        <div className="field"><label>Nota final (cold down / observaciones)</label><input className="input" value={r.note} onChange={(e) => set("note", e.target.value)} /></div>
      </div>

      {r.blocks.map((b, bi) => (
        <div className="panel" key={b.id} style={{ paddingBottom: 16 }}>
          <div className="block-edit" style={{ border: "none", padding: 0, background: "none", margin: 0 }}>
            <div className="row-between" style={{ marginBottom: 12 }}>
              <span className="mini" style={{ fontWeight: 700, letterSpacing: ".12em", textTransform: "uppercase" }}>Bloque {bi + 1}</span>
              <div style={{ display: "flex", gap: 6 }}>
                <button className="icon-btn" style={{ width: 30, height: 30 }} onClick={() => moveBlock(bi, -1)} title="Subir"><Icon name="chevronLeft" style={{ width: 14, height: 14, transform: "rotate(90deg)" }} /></button>
                <button className="icon-btn" style={{ width: 30, height: 30 }} onClick={() => moveBlock(bi, 1)} title="Bajar"><Icon name="chevronRight" style={{ width: 14, height: 14, transform: "rotate(90deg)" }} /></button>
                <button className="icon-btn danger" style={{ width: 30, height: 30 }} onClick={() => delBlock(bi)}><Icon name="trash" style={{ width: 14, height: 14 }} /></button>
              </div>
            </div>
            <div className="grid2">
              <div className="field"><label>Nombre del bloque</label><input className="input" value={b.name} onChange={(e) => setBlock(bi, { name: e.target.value })} placeholder="Bloque 1 · Ronda 1" /></div>
              <div className="field"><label>Esquema</label><input className="input" value={b.scheme} onChange={(e) => setBlock(bi, { scheme: e.target.value })} placeholder="EMOM 9 / SUPER SET x3…" /></div>
            </div>

            <label className="mini" style={{ fontWeight: 700, color: "var(--ink-soft)" }}>EJERCICIOS</label>
            <div style={{ marginTop: 8 }}>
              {b.items.map((it, ii) => (
                <div className="ex-edit" key={it.id}>
                  <div className="ex-edit-top">
                    <input className="input ex-qty-in" value={it.qty} onChange={(e) => setItem(bi, ii, { qty: e.target.value })} placeholder="reps" title="Cantidad / reps / tiempo" />
                    <input className="input" value={it.name} onChange={(e) => setItem(bi, ii, { name: e.target.value })} placeholder="Ejercicio" />
                    <button className="icon-btn danger" onClick={() => delItem(bi, ii)}><Icon name="trash" style={{ width: 15, height: 15 }} /></button>
                  </div>
                  <input className="input ex-note-in" value={it.meta} onChange={(e) => setItem(bi, ii, { meta: e.target.value })} placeholder="Nota / comentario (opcional)" />
                  <div className="ex-video-row">
                    <Icon name="link" style={{ width: 15, height: 15, color: "var(--muted)", flex: "0 0 auto" }} />
                    <input className="input" style={{ fontSize: 13 }} value={it.video} onChange={(e) => setItem(bi, ii, { video: e.target.value })} placeholder="URL del video del ejercicio (opcional)" />
                  </div>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
              <button className="add-row" onClick={() => addItem(bi)}><Icon name="plus" style={{ width: 14, height: 14 }} /> Añadir ejercicio</button>
            </div>

            <div className="field" style={{ marginTop: 12 }}><label>Descanso / nota del bloque</label><input className="input" value={b.note} onChange={(e) => setBlock(bi, { note: e.target.value })} placeholder="3 min de descanso…" /></div>
          </div>
        </div>
      ))}
      <button className="add-row" onClick={addBlock} style={{ marginBottom: 24 }}><Icon name="plus" style={{ width: 14, height: 14 }} /> Añadir bloque</button>
    </div>
  );
}

/* ---------------- Fixed content editor ---------------- */
/* ---------------- Fixed content editor (esquema fiel al PDF) ---------------- */
const _clone = (x) => JSON.parse(JSON.stringify(x));
const _toLines = (s) => s.split("\n").filter((x) => x.trim() !== "");
const ACCENT_OPTS = [
  { v: "light", l: "Gris claro" }, { v: "faint", l: "Gris muy claro" }, { v: "white", l: "Blanco" },
  { v: "coral", l: "Coral" }, { v: "graybox", l: "Gris" }, { v: "dark", l: "Carbón" }, { v: "bare", l: "Sin recuadro" },
];

function AccentField({ value, onChange }) {
  return (
    <div className="field"><label>Color del contenedor</label>
      <select className="input" value={value || "light"} onChange={(e) => onChange(e.target.value)}>
        {ACCENT_OPTS.map((o) => <option key={o.v} value={o.v}>{o.l}</option>)}
      </select>
    </div>
  );
}
function LinesField({ label = "Texto (una línea por renglón)", value, onChange }) {
  return (
    <div className="field"><label>{label}</label>
      <textarea className="input" value={(value || []).join("\n")} onChange={(e) => onChange(_toLines(e.target.value))} />
    </div>
  );
}
function MacrosField({ value, onChange }) {
  const macros = value || [];
  const setM = (i, k, v) => { const m = macros.map((x) => ({ ...x })); m[i][k] = v; onChange(m); };
  return (
    <div className="field"><label>Macros</label>
      {macros.map((m, i) => (
        <div key={i} style={{ display: "flex", gap: 8, marginBottom: 6 }}>
          <input className="input" style={{ flex: "0 0 80px" }} value={m.v} onChange={(e) => setM(i, "v", e.target.value)} placeholder="65%" />
          <input className="input" value={m.l} onChange={(e) => setM(i, "l", e.target.value)} placeholder="Proteína" />
          <button className="icon-btn danger" onClick={() => onChange(macros.filter((_, j) => j !== i))}><Icon name="trash" style={{ width: 14, height: 14 }} /></button>
        </div>
      ))}
      <button className="add-row" onClick={() => onChange([...macros, { v: "", l: "" }])}><Icon name="plus" style={{ width: 14, height: 14 }} /> Macro</button>
    </div>
  );
}
function GroupsField({ value, onChange }) {
  const groups = value || [];
  const setG = (gi, patch) => { const g = _clone(groups); g[gi] = { ...g[gi], ...patch }; onChange(g); };
  const setItem = (gi, ii, patch) => { const g = _clone(groups); g[gi].items[ii] = { ...g[gi].items[ii], ...patch }; onChange(g); };
  return (
    <div>
      {groups.map((g, gi) => (
        <div className="block-edit" key={gi}>
          <div className="field" style={{ marginBottom: 8 }}><label>Subgrupo {gi + 1}</label><input className="input" value={g.sub} onChange={(e) => setG(gi, { sub: e.target.value })} /></div>
          {g.items.map((it, ii) => (
            <div key={ii} style={{ borderLeft: "2px solid var(--line)", paddingLeft: 12, marginBottom: 8 }}>
              <div className="field" style={{ marginBottom: 6 }}><label>Etiqueta (opcional)</label><input className="input" value={it.when} onChange={(e) => setItem(gi, ii, { when: e.target.value })} placeholder="Antes / Durante / Cada 12 h…" /></div>
              <LinesField value={it.lines} onChange={(l) => setItem(gi, ii, { lines: l })} />
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}
function SecFields({ s, onChange }) {
  const up = (patch) => onChange({ ...s, ...patch });
  if (s.type === "cols") {
    return (
      <div className="grid2">
        {s.cols.map((col, ci) => (
          <div className="block-edit" key={ci} style={{ margin: 0 }}>
            <SecFields s={col} onChange={(nc) => onChange({ ...s, cols: s.cols.map((x, i) => (i === ci ? nc : x)) })} />
          </div>
        ))}
      </div>
    );
  }
  return (
    <React.Fragment>
      {("h" in s) && <div className="field"><label>Título</label><input className="input" value={s.h || ""} onChange={(e) => up({ h: e.target.value })} /></div>}
      {("accent" in s) && <AccentField value={s.accent} onChange={(v) => up({ accent: v })} />}
      {s.chips && <div className="field"><label>Chips (uno por línea)</label><textarea className="input" value={s.chips.join("\n")} onChange={(e) => up({ chips: _toLines(e.target.value) })} /></div>}
      {s.macros && <MacrosField value={s.macros} onChange={(m) => up({ macros: m })} />}
      {s.lines && <LinesField value={s.lines} onChange={(l) => up({ lines: l })} />}
      {s.groups && <GroupsField value={s.groups} onChange={(g) => up({ groups: g })} />}
    </React.Fragment>
  );
}

/* Reusable 3-area content editor (controlled). c = content object, mutate(fn) updates it. */
function ContentAreas({ c, mutate, only }) {
  const showSec = (k) => !only || only === k;
  return (
    <div>
      {/* Methodology */}
      {showSec("methodology") &&
      <div className="panel">
        <h3 style={{ fontSize: 16 }}>Metodología</h3>
        <div className="field" style={{ marginTop: 12 }}><label>Título</label><input className="input" value={c.methodology.title} onChange={(e) => mutate((n) => n.methodology.title = e.target.value)} /></div>
        <div className="field"><label>Intro</label><textarea className="input" value={c.methodology.intro} onChange={(e) => mutate((n) => n.methodology.intro = e.target.value)} /></div>
        <div className="field"><label>Distribución semanal (7 valores: High / Low / Rest)</label>
          <input className="input" value={c.methodology.week.values.join(", ")} onChange={(e) => mutate((n) => n.methodology.week.values = e.target.value.split(",").map((x) => x.trim()).slice(0, 7))} /></div>
        {c.methodology.intensities.map((s, i) => (
          <div className="block-edit" key={i}>
            <span className="mini" style={{ fontWeight: 700 }}>Intensidad {i + 1}</span>
            <div style={{ marginTop: 8 }}><SecFields s={s} onChange={(ns) => mutate((n) => n.methodology.intensities[i] = ns)} /></div>
          </div>
        ))}
      </div>
      }

      {/* Nutrition */}
      {showSec("nutrition") &&
      <div className="panel">
        <h3 style={{ fontSize: 16 }}>Alimentación</h3>
        <div className="field" style={{ marginTop: 12 }}><label>Título</label><input className="input" value={c.nutrition.title} onChange={(e) => mutate((n) => n.nutrition.title = e.target.value)} /></div>
        <div className="field"><label>Intro</label><textarea className="input" value={c.nutrition.intro} onChange={(e) => mutate((n) => n.nutrition.intro = e.target.value)} /></div>
        {c.nutrition.pages.map((pg, pi) => (
          <div key={pi} style={{ marginTop: 14 }}>
            <div className="row-between" style={{ marginBottom: 8 }}>
              <span className="mini" style={{ fontWeight: 700, letterSpacing: ".12em", textTransform: "uppercase" }}>Página {pi + 1}</span>
            </div>
            <div className="field"><label>Etiqueta de la página</label><input className="input" value={pg.label || ""} onChange={(e) => mutate((n) => n.nutrition.pages[pi].label = e.target.value)} /></div>
            {pg.sections.map((s, si) => (
              <div className="block-edit" key={si}>
                <span className="mini" style={{ fontWeight: 700 }}>Sección {si + 1} {s.type === "cols" ? "· dos columnas" : ""}</span>
                <div style={{ marginTop: 8 }}><SecFields s={s} onChange={(ns) => mutate((n) => n.nutrition.pages[pi].sections[si] = ns)} /></div>
              </div>
            ))}
          </div>
        ))}
      </div>
      }

      {/* Recovery */}
      {showSec("recovery") &&
      <div className="panel">
        <h3 style={{ fontSize: 16 }}>Recuperación</h3>
        <div className="field" style={{ marginTop: 12 }}><label>Título</label><input className="input" value={c.recovery.title} onChange={(e) => mutate((n) => n.recovery.title = e.target.value)} /></div>
        <div className="field"><label>Intro</label><textarea className="input" value={c.recovery.intro} onChange={(e) => mutate((n) => n.recovery.intro = e.target.value)} /></div>
        {c.recovery.sections.map((s, i) => (
          <div className="block-edit" key={i}>
            <span className="mini" style={{ fontWeight: 700 }}>Sección {i + 1} {s.type === "cols" ? "· dos columnas" : ""}</span>
            <div style={{ marginTop: 8 }}><SecFields s={s} onChange={(ns) => mutate((n) => n.recovery.sections[i] = ns)} /></div>
          </div>
        ))}
      </div>
      }
    </div>
  );
}

/* Super admin: global base template */
function ContentPanel() {
  const [c, setC] = useState(null);
  const toast = useToast();
  useEffect(() => { window.DB.getContent().then(setC); }, []);
  if (!c) return <div className="panel">Cargando…</div>;

  const mutate = (fn) => setC((prev) => { const n = _clone(prev); fn(n); return n; });
  async function save() { await window.DB.saveContent(c); toast("Plantilla guardada"); }

  return (
    <div>
      <div className="panel">
        <div className="row-between"><div><h3>Plantilla base de contenido</h3><div className="sub" style={{ margin: 0 }}>Se precarga al crear cada cliente; luego cada coach lo personaliza.</div></div>
          <Pill onClick={save}><Icon name="check" style={{ width: 16, height: 16 }} /> Guardar</Pill></div>
      </div>
      <ContentAreas c={c} mutate={mutate} />
    </div>
  );
}

/* Coach: per-client content editor with show/hide toggles. Controlled. */
function ClientContentEditor({ only, content, show, onContent, onShow }) {
  const mutate = (fn) => { const n = _clone(content); fn(n); onContent(n); };
  const areas = [
    { key: "methodology", label: "Metodología" },
    { key: "nutrition", label: "Alimentación" },
    { key: "recovery", label: "Recuperación" },
    { key: "competition", label: "Próxima competencia" },
  ];
  return (
    <div>
      {!only &&
      <div className="panel">
        <h3 style={{ fontSize: 16 }}>Secciones visibles para el cliente</h3>
        <div className="sub">Apaga una sección para ocultarla en el inicio del cliente.</div>
        {areas.map((a) => (
          <div className={`access-toggle ${show[a.key] === false ? "off" : ""}`} key={a.key} style={{ marginBottom: 10 }}>
            <div className="at-text">
              <div className="at-title">{a.label}</div>
              <div className="at-sub">{show[a.key] === false ? "Oculta — el cliente no verá este botón." : "Visible en el inicio del cliente."}</div>
            </div>
            <button type="button" className={`switch ${show[a.key] === false ? "" : "on"}`} role="switch" aria-checked={show[a.key] !== false} onClick={() => onShow({ ...show, [a.key]: show[a.key] === false })}>
              <span className="knob"></span>
            </button>
          </div>
        ))}
      </div>
      }
      <ContentAreas c={content} mutate={mutate} only={only} />
    </div>
  );
}

/* ---------------- Competition editor (per-client, by coach) ---------------- */
function ResultsEditor({ results, onChange }) {
  const list = results || [];
  const set = (i, patch) => { const r = list.map((x) => ({ ...x })); r[i] = { ...r[i], ...patch }; onChange(r); };
  return (
    <div className="block-edit" style={{ marginTop: 8 }}>
      <span className="mini" style={{ fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase" }}>Registro de resultados</span>
      {list.map((r, i) => (
        <div key={r.id} style={{ marginTop: 8 }}>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <input className="input" type="date" style={{ flex: "1 1 auto", minWidth: 0 }} value={r.date} onChange={(e) => set(i, { date: e.target.value })} />
            <button className="icon-btn danger" onClick={() => onChange(list.filter((_, j) => j !== i))}><Icon name="trash" style={{ width: 15, height: 15 }} /></button>
          </div>
          <textarea className="input" style={{ marginTop: 6, minHeight: 60 }} value={r.text} onChange={(e) => set(i, { text: e.target.value })} placeholder="Resultados (texto libre)" />
        </div>
      ))}
      <button className="add-row" onClick={() => onChange([...list, window.DB.newResult()])} style={{ marginTop: 8 }}><Icon name="plus" style={{ width: 14, height: 14 }} /> Añadir resultado</button>
    </div>
  );
}

function CompetitionEditor({ competition, onChange }) {
  const comp = competition;
  const set = (k, v) => onChange({ ...comp, [k]: v });
  const circuits = comp.circuits || [];

  const setCircuit = (ci, patch) => { const cs = _clone(circuits); cs[ci] = { ...cs[ci], ...patch }; onChange({ ...comp, circuits: cs }); };
  const addCircuit = () => onChange({ ...comp, circuits: [...circuits, window.DB.newCircuit()] });
  const delCircuit = (ci) => onChange({ ...comp, circuits: circuits.filter((_, i) => i !== ci) });

  // meta block/item helpers (meta = { title, blocks:[{id,name,scheme,items:[],note}] })
  const setMeta = (ci, fn) => { const cs = _clone(circuits); fn(cs[ci].meta); onChange({ ...comp, circuits: cs }); };

  return (
    <div>
      <div className="panel">
        <h3 style={{ fontSize: 16 }}>Datos de la competencia</h3>
        <div className="grid2" style={{ marginTop: 12 }}>
          <div className="field"><label>Nombre de la competencia</label><input className="input" value={comp.name} onChange={(e) => set("name", e.target.value)} placeholder="CALI·RIO 2024" /></div>
          <div className="field"><label>Fecha</label><input className="input" value={comp.date} onChange={(e) => set("date", e.target.value)} placeholder="15 de agosto, 2026" /></div>
          <div className="field"><label>Categoría</label><input className="input" value={comp.category} onChange={(e) => set("category", e.target.value)} placeholder="Avanzados" /></div>
          <div className="field"><label>Ubicación</label><input className="input" value={comp.location} onChange={(e) => set("location", e.target.value)} placeholder="Río de Janeiro, Brasil" /></div>
        </div>
        <div className="field"><label>Intro (mensaje motivacional)</label><textarea className="input" value={comp.intro || ""} onChange={(e) => set("intro", e.target.value)} /></div>
      </div>

      {circuits.map((cir, ci) => (
        <div className="panel" key={cir.id}>
          <div className="row-between" style={{ marginBottom: 12 }}>
            <span className="mini" style={{ fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase" }}>Circuito {ci + 1}</span>
            <button className="icon-btn danger" onClick={() => delCircuit(ci)}><Icon name="trash" style={{ width: 15, height: 15 }} /></button>
          </div>
          <div className="field"><label>Título del circuito</label><input className="input" value={cir.title} onChange={(e) => setCircuit(ci, { title: e.target.value })} placeholder="Circuito Resistencia · Clasificatorio" /></div>
          <PhotoUpload value={cir.image} onChange={(v) => setCircuit(ci, { image: v })} label="Imagen / captura del circuito" />
          <ResultsEditor results={cir.results} onChange={(r) => setCircuit(ci, { results: r })} />

          <div className="block-edit" style={{ marginTop: 4 }}>
            <span className="mini" style={{ fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase" }}>Circuito Meta</span>
            <div className="field" style={{ marginTop: 8 }}><label>Título</label><input className="input" value={cir.meta.title || ""} onChange={(e) => setMeta(ci, (m) => m.title = e.target.value)} placeholder="Circuito Meta" /></div>
            {cir.meta.blocks.map((b, bi) => (
              <div key={b.id} style={{ marginTop: 6 }}>
                <div className="field"><label>Nota / esquema del bloque (opcional)</label><input className="input" value={b.scheme} onChange={(e) => setMeta(ci, (m) => m.blocks[bi].scheme = e.target.value)} placeholder="Ajustado por tu coach" /></div>
                {b.items.map((it, ii) => (
                  <div className="ex-edit" key={it.id}>
                    <div className="ex-edit-top">
                      <input className="input ex-qty-in" value={it.qty} onChange={(e) => setMeta(ci, (m) => m.blocks[bi].items[ii].qty = e.target.value)} placeholder="reps" />
                      <input className="input" value={it.name} onChange={(e) => setMeta(ci, (m) => m.blocks[bi].items[ii].name = e.target.value)} placeholder="Ejercicio + carga (p. ej. 40 Push-up + 5kg)" />
                      <button className="icon-btn danger" onClick={() => setMeta(ci, (m) => m.blocks[bi].items = m.blocks[bi].items.filter((_, j) => j !== ii))}><Icon name="trash" style={{ width: 15, height: 15 }} /></button>
                    </div>
                    <div className="ex-video-row">
                      <Icon name="link" style={{ width: 15, height: 15, color: "var(--muted)", flex: "0 0 auto" }} />
                      <input className="input" style={{ fontSize: 13 }} value={it.video} onChange={(e) => setMeta(ci, (m) => m.blocks[bi].items[ii].video = e.target.value)} placeholder="URL de video (opcional)" />
                    </div>
                  </div>
                ))}
                <button className="add-row" onClick={() => setMeta(ci, (m) => m.blocks[bi].items.push(window.DB.newItem()))}><Icon name="plus" style={{ width: 14, height: 14 }} /> Añadir ejercicio</button>
              </div>
            ))}
            <ResultsEditor results={cir.meta.results} onChange={(r) => setMeta(ci, (m) => m.results = r)} />
          </div>
        </div>
      ))}
      <button className="add-row" onClick={addCircuit} style={{ marginBottom: 22 }}><Icon name="plus" style={{ width: 14, height: 14 }} /> Añadir circuito</button>
    </div>
  );
}

Object.assign(window, { RoutinesPanel, RoutineEditor, ContentPanel, ContentAreas, ClientContentEditor, CompetitionEditor });
