// Mis Rutinas — saved routine templates (single source of truth: store.savedRoutines)
// View, load, rename, duplicate, delete, train, and export each routine to PDF.
// Tapping a card opens the full routine in its own detail screen — the SAME view
// the preset routines use (RtDetail), so saved and preset routines look identical.

const MR = {
  page:    '#060D18',
  panel:   '#0A1422',
  card:    '#0E1A2C',
  hov:     '#132134',
  border:  'rgba(255,255,255,0.07)',
  text:    '#E8EDF8',
  sub:     'rgba(232,237,248,0.55)',
  muted:   'rgba(232,237,248,0.55)',
  blue:    '#3B82F6',
  blueDim: 'rgba(59,130,246,0.12)',
  green:   '#22C55E',
  amber:   '#F59E0B',
  red:     '#EF4444',
};

const AR_KEY_MR = 'atlas.routine.active.v1';

function mrFmtDate(ts) {
  if (!ts) return '';
  try { return new Date(ts).toLocaleDateString('es-ES', { day: 'numeric', month: 'short', year: 'numeric' }); }
  catch { return ''; }
}

function mrCountExercises(routine) {
  return (routine.sessions || []).reduce((t, s) => t + (s.exercises || []).length, 0);
}

// ── Body-map building from a saved session's exercises ──────────────────────────
// Saved exercises carry granular groups (delt_lat, dorsal, gluteos…) and specific
// muscle names; the body-map silhouettes are coarse (pecho/espalda/hombro/pierna/
// biceps/triceps/core). Map each exercise to its silhouette and collect the real
// muscle names as legend labels, so saved routines get the same worked-zones map.
const MR_SIL = {
  pecho:'pecho', pectoral:'pecho',
  delt_ant:'hombro', delt_lat:'hombro', delt_post:'hombro', hombro:'hombro', hombros:'hombro', deltoides:'hombro',
  dorsal:'espalda', trapecio:'espalda', lumbar:'espalda', erectores:'espalda', espalda:'espalda', romboides:'espalda',
  cuadriceps:'pierna', isquio:'pierna', isquios:'pierna', isquiotibiales:'pierna', gluteos:'pierna', gluteo:'pierna',
  gemelos:'pierna', aductores:'pierna', abductores:'pierna', tibial:'pierna', pierna:'pierna', piernas:'pierna',
  biceps:'biceps', triceps:'triceps', antebrazo:'triceps',
  core:'core', abs:'core', oblicuos:'core', abdominales:'core', abdomen:'core',
};
function mrSil(group, muscleName) {
  const g = (group || '').toLowerCase();
  if (MR_SIL[g]) return MR_SIL[g];
  const m = (muscleName || '').toLowerCase();
  if (/pec/.test(m)) return 'pecho';
  if (/dorsal|espalda|trapec|romboid|lumbar|erector/.test(m)) return 'espalda';
  if (/delt|hombro/.test(m)) return 'hombro';
  if (/cuádr|cuadr|isqui|glúte|glute|gemel|pierna|aduct|abduct|tibial/.test(m)) return 'pierna';
  if (/bíceps|biceps/.test(m)) return 'biceps';
  if (/tríceps|triceps|antebrazo/.test(m)) return 'triceps';
  if (/core|abdom|oblic/.test(m)) return 'core';
  return null;
}
function mrMusclesOf(ex, which) {
  if (Array.isArray(ex.muscles)) return which === 'primary' ? ex.muscles : [];
  return (ex.muscles && ex.muscles[which]) || [];
}
function mrBuildMuscleMap(exs) {
  const primG = [], secG = [], primL = [], secL = [];
  const add = (arr, v) => { if (v && !arr.includes(v)) arr.push(v); };
  (exs || []).forEach(ex => {
    const pm = mrMusclesOf(ex, 'primary');
    const sm = mrMusclesOf(ex, 'secondary');
    const sil = mrSil(ex.group, pm[0]);
    if (sil) add(primG, sil);
    pm.forEach(l => add(primL, l));
    sm.forEach(l => { add(secL, l); const s = mrSil(null, l); if (s && !primG.includes(s)) add(secG, s); });
  });
  return { primary: { groups: primG, labels: primL.slice(0, 5) }, secondary: { groups: secG, labels: secL.slice(0, 6) } };
}

// ── Saved exercise → shared row model (same shape RtDetail renders) ─────────────
function mrExToRow(ex) {
  const sets = ex.setsCount || (Array.isArray(ex.sets) ? ex.sets.length : (Number(ex.sets) || 0));
  const reps = ex.repsRange || (Array.isArray(ex.sets) && ex.sets[0] && ex.sets[0].reps ? String(ex.sets[0].reps) : '');
  const muscle = Array.isArray(ex.muscles) ? (ex.muscles[0] || '') : (ex.muscles?.primary?.[0] || '');
  const muscles = Array.isArray(ex.muscles) ? { primary: ex.muscles, secondary: [] } : (ex.muscles || { primary: [], secondary: [] });
  return {
    id: ex.id, name: ex.name || ex.id, muscle, muscles,
    sets, reps, rir: (ex.rir ?? ''), rest: ex.rest || '', note: ex.note,
  };
}
function mrRoutineDays(routine) {
  return (routine.sessions || []).map((s, i) => ({
    name: s.name || `Día ${i + 1}`,
    muscleMap: mrBuildMuscleMap(s.exercises || []),
    exercises: (s.exercises || []).map(mrExToRow),
  }));
}
function mrRoutineChips(routine) {
  const sessions = routine.sessions || [];
  const nEx = mrCountExercises(routine);
  return [
    routine.objective,
    routine.split && String(routine.split).replace(/_/g, ' '),
    `${sessions.length} ${sessions.length === 1 ? 'sesión' : 'sesiones'}`,
    `${nEx} ejercicios`,
  ].filter(Boolean);
}
function mrSourceLabel(routine) {
  const src = routine.source === 'coach' ? 'Coach' : routine.source === 'onboarding' ? 'Onboarding' : 'Manual';
  return src + (routine.savedAt ? ` · guardada ${mrFmtDate(routine.savedAt)}` : (routine.createdAt ? ` · creada ${mrFmtDate(routine.createdAt)}` : ''));
}

// Dropdown menu item style
function mrMenuItem(color) {
  return {
    display: 'block', width: '100%', textAlign: 'left',
    padding: '12px 14px', border: 'none', cursor: 'pointer', background: 'transparent',
    color, fontFamily: 'Inter,system-ui', fontSize: 13, fontWeight: 600,
  };
}

// ── Options menu (⋯) + rename + delete — reused by the card and the detail ──────
// Renders the ⋯ button (never bubbles a tap up to an enclosing clickable card),
// its portal menu, an inline rename field, and the delete confirmation. The host
// supplies where the rename input and confirm box appear via render callbacks.
function MrOptionsMenu({ routine, onRename, onDuplicate, onDelete, width = 184 }) {
  const [menuOpen, setMenuOpen]   = React.useState(false);
  const [editing, setEditing]     = React.useState(false);
  const [confirmDel, setConfirm]  = React.useState(false);
  const [name, setName]           = React.useState(routine.name || 'Rutina');
  const menuBtnRef = React.useRef(null);

  function saveName(e) {
    if (e) e.stopPropagation();
    setEditing(false);
    if (name.trim() && name.trim() !== routine.name) onRename(routine.id, name.trim());
    else setName(routine.name || 'Rutina');
  }

  const stop = e => e.stopPropagation();

  const button = (
    <div style={{ flexShrink: 0 }} onClick={stop}>
      <button
        ref={menuBtnRef}
        aria-label="Más opciones"
        onClick={e => { e.stopPropagation(); setMenuOpen(o => !o); }}
        style={{ padding: '7px 12px', borderRadius: 8, cursor: 'pointer', background: 'transparent', color: MR.sub,
          border: `1px solid ${MR.border}`, fontFamily: 'Inter,system-ui', fontSize: 15, fontWeight: 700, lineHeight: 1 }}
      >⋯</button>
      <AtlasMenu open={menuOpen} anchorRef={menuBtnRef} onClose={() => setMenuOpen(false)} width={width}>
        <button onClick={e => { stop(e); setMenuOpen(false); setName(routine.name || 'Rutina'); setEditing(true); }} style={mrMenuItem(MR.text)}>Renombrar</button>
        <button onClick={e => { stop(e); setMenuOpen(false); onDuplicate(routine.id); }} style={mrMenuItem(MR.text)}>Duplicar</button>
        <button onClick={e => { stop(e); setMenuOpen(false); setConfirm(true); }} style={mrMenuItem('#FCA5A5')}>Eliminar</button>
      </AtlasMenu>
    </div>
  );

  const renameField = editing ? (
    <input
      autoFocus
      aria-label="Nombre de la rutina"
      value={name}
      onClick={stop}
      onChange={e => setName(e.target.value)}
      onBlur={saveName}
      onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') saveName(); if (e.key === 'Escape') { setEditing(false); setName(routine.name); } }}
      style={{ width: '100%', background: MR.panel, border: `1px solid ${MR.blue}`, borderRadius: 8, color: MR.text, fontFamily: 'Inter,system-ui', fontSize: 16, fontWeight: 800, padding: '6px 10px' }}
    />
  ) : null;

  const confirmBox = confirmDel ? (
    <div onClick={stop} style={{ marginTop: 12, padding: '14px 16px', borderRadius: 12, border: '1px solid rgba(239,68,68,0.30)', background: 'rgba(239,68,68,0.06)' }}>
      <div style={{ fontFamily: 'Inter,system-ui', fontSize: 13, fontWeight: 700, color: MR.text }}>¿Eliminar «{routine.name || 'Rutina'}»?</div>
      <div style={{ fontFamily: 'Inter,system-ui', fontSize: 12, color: MR.sub, marginTop: 4, lineHeight: 1.5 }}>
        Esta acción no se puede deshacer. Tus sesiones ya registradas en el historial no se verán afectadas.
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
        <button onClick={e => { stop(e); onDelete(routine.id); }} style={{ minHeight: 44, padding: '0 16px', borderRadius: 10, border: 'none', cursor: 'pointer', background: '#EF4444', color: '#fff', fontFamily: 'Inter,system-ui', fontSize: 13, fontWeight: 700 }}>Eliminar</button>
        <button onClick={e => { stop(e); setConfirm(false); }} style={{ minHeight: 44, padding: '0 16px', borderRadius: 10, cursor: 'pointer', background: 'transparent', color: MR.sub, border: `1px solid ${MR.border}`, fontFamily: 'Inter,system-ui', fontSize: 13, fontWeight: 700 }}>Cancelar</button>
      </div>
    </div>
  ) : null;

  return { button, renameField, confirmBox, editing };
}

// ── Single routine card — the WHOLE card opens the routine ──────────────────────
function MrRoutineCard({ routine, onOpen, onRename, onDuplicate, onDelete }) {
  const sessions = routine.sessions || [];
  const nEx = mrCountExercises(routine);
  const chips = mrRoutineChips(routine);
  const { button, renameField, confirmBox, editing } = MrOptionsMenu({ routine, onRename, onDuplicate, onDelete });

  return (
    <div
      role="button"
      tabIndex={0}
      onClick={() => onOpen(routine)}
      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(routine); } }}
      className="wp-press"
      style={{ borderRadius: 16, border: `1px solid ${MR.border}`, background: MR.card, cursor: 'pointer', textAlign: 'left' }}
    >
      <div style={{ padding: '16px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            {editing ? renameField : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ fontFamily: 'Inter,system-ui', fontSize: 16, fontWeight: 800, color: MR.text, letterSpacing: -0.3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {routine.name || 'Rutina'}
                </div>
                <span style={{ flexShrink: 0, fontFamily: 'Inter,system-ui', fontSize: 12, fontWeight: 800, color: MR.blue }}>→</span>
              </div>
            )}
            <div style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 10, color: MR.muted, marginTop: 4 }}>
              {mrSourceLabel(routine)}
            </div>
          </div>
          {button}
        </div>

        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 12 }}>
          {chips.map((c, i) => (
            <span key={i} style={{ padding: '3px 9px', borderRadius: 999, background: MR.blueDim, color: '#93C5FD', fontFamily: 'Inter,system-ui', fontSize: 10, fontWeight: 600 }}>{c}</span>
          ))}
        </div>

        {/* Session preview — names so multi-day routines read at a glance */}
        {sessions.length > 0 && (
          <div style={{ fontFamily: 'Inter,system-ui', fontSize: 11.5, color: MR.sub, marginTop: 10, lineHeight: 1.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {sessions.map((s, i) => s.name || `Día ${i + 1}`).join(' · ')}
          </div>
        )}

        {confirmBox}
      </div>
    </div>
  );
}

// ── Saved-routine detail — reuses the preset RtDetail view ──────────────────────
function MrRoutineDetail({ routine, onBack, onTrain, onLoad, onPDF, onRename, onDuplicate, onDelete }) {
  const Detail = (typeof RtDetail !== 'undefined') ? RtDetail : window.RtDetail;
  const days = mrRoutineDays(routine);
  const multi = days.length > 1;
  const chips = mrRoutineChips(routine);
  const { button, renameField, confirmBox, editing } = MrOptionsMenu({ routine, onRename, onDuplicate, onDelete, width: 190 });

  const act = (bg, color, border, extra) => ({
    minHeight: 48, borderRadius: 12, cursor: 'pointer', background: bg, color,
    border: border || 'none', fontFamily: 'Inter,system-ui', fontSize: 14, fontWeight: 800, letterSpacing: -0.2, ...extra,
  });

  return (
    <Detail
      title={editing ? renameField : (routine.name || 'Rutina')}
      subtitle={mrSourceLabel(routine)}
      chips={chips}
      titleAccessory={button}
      afterActions={confirmBox}
      days={days}
      bodyMapNote={(day) => day.name}
      onBack={onBack}
      backLabel="← Mis rutinas"
      renderActions={(dayIdx) => (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
          <button onClick={() => onTrain(routine, dayIdx)} style={act(MR.green, '#fff', 'none', { flex: '1 1 160px', boxShadow: '0 4px 18px -4px rgba(34,197,94,0.45)' })}>
            {multi ? `▶ Entrenar Día ${dayIdx + 1}` : '▶ Entrenar ahora'}
          </button>
          <button onClick={() => onLoad(routine)} style={act('rgba(255,255,255,0.04)', MR.text, `1px solid ${MR.border}`, { flex: '1 1 150px' })}>
            Cargar en Builder
          </button>
          {typeof exportRoutinePDF !== 'undefined' && (
            <button onClick={() => onPDF(routine)} style={act('rgba(59,130,246,0.07)', '#93C5FD', '1px solid rgba(59,130,246,0.20)', { flex: '1 1 120px' })}>
              ↓ Descargar PDF
            </button>
          )}
        </div>
      )}
    />
  );
}

// ── Section ─────────────────────────────────────────────────────────────────
function MisRutinasSection() {
  const { state, actions } = useStore();
  const { navigate } = useRoute();
  const routines = state.savedRoutines || [];
  const [openId, setOpenId] = React.useState(null);
  const open = routines.find(r => r.id === openId) || null;

  function trainSession(routine, sessionIndex) {
    const session = (routine.sessions || [])[sessionIndex];
    if (!session || !(session.exercises || []).length) return;
    try {
      localStorage.setItem('atlas.pendingWorkout', JSON.stringify(session.exercises));
      localStorage.setItem('atlas.pendingWorkoutMeta', JSON.stringify({
        routineId: routine.id,
        routineName: routine.name,
        sessionName: session.name || `Día ${sessionIndex + 1}`,
        sessionIndex,
        totalSessions: (routine.sessions || []).length,
      }));
    } catch (e) {}
    navigate('/player');
  }

  function loadToBuilder(routine) {
    try { localStorage.setItem(AR_KEY_MR, JSON.stringify({ ...routine, updatedAt: Date.now() })); } catch (e) {}
    navigate('/builder');
  }

  function pdf(routine) {
    if (typeof exportRoutinePDF === 'undefined') return;
    try { exportRoutinePDF(routine); } catch (e) {}
  }

  function deleteRoutine(id) {
    actions.deleteRoutine(id);
    setOpenId(prev => (prev === id ? null : prev));
  }

  // ── Detail screen ──────────────────────────────────────────────────────────
  if (open) {
    return (
      <div style={{ minHeight: '100vh', background: MR.page, padding: '28px 20px 90px' }}>
        <div style={{ maxWidth: 720, margin: '0 auto' }}>
          <MrRoutineDetail
            routine={open}
            onBack={() => setOpenId(null)}
            onTrain={trainSession}
            onLoad={loadToBuilder}
            onPDF={pdf}
            onRename={actions.renameRoutine}
            onDuplicate={(id) => { actions.duplicateRoutine(id); setOpenId(null); }}
            onDelete={deleteRoutine}
          />
        </div>
      </div>
    );
  }

  // ── List screen ────────────────────────────────────────────────────────────
  return (
    <div style={{ minHeight: '100vh', background: MR.page, padding: '28px 20px 90px' }}>
      <div style={{ maxWidth: 720, margin: '0 auto' }}>
        {/* Preset routines entry point */}
        <button onClick={() => navigate('/plantillas')} style={{ display:'flex', alignItems:'center', gap:14, width:'100%', textAlign:'left', cursor:'pointer',
          padding:'14px 16px', borderRadius:16, marginBottom:18, border:'1px solid rgba(59,130,246,0.30)',
          background:'linear-gradient(135deg, #0f2744, #1d3a6b)', color:MR.text, boxShadow:'0 8px 28px -12px rgba(59,130,246,0.5)' }}>
          <span style={{ fontSize:26, flexShrink:0 }}>🧬</span>
          <span style={{ flex:1, minWidth:0 }}>
            <span style={{ display:'block', fontFamily:'Inter,system-ui', fontSize:10, fontWeight:800, letterSpacing:1.2, color:'#93C5FD' }}>BASADAS EN CIENCIA</span>
            <span style={{ display:'block', fontFamily:'Inter,system-ui', fontSize:15.5, fontWeight:800, letterSpacing:-0.3 }}>Rutinas predeterminadas</span>
          </span>
          <span style={{ flexShrink:0, fontFamily:'Inter,system-ui', fontSize:13, fontWeight:800, color:MR.blue }}>Ver →</span>
        </button>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 22 }}>
          <div>
            <div style={{ fontFamily: 'Inter,system-ui', fontSize: 24, fontWeight: 800, color: MR.text, letterSpacing: -0.6 }}>Mis rutinas</div>
            <div style={{ fontFamily: 'Inter,system-ui', fontSize: 13, color: MR.sub, marginTop: 4 }}>
              {routines.length > 0 ? `${routines.length} ${routines.length === 1 ? 'rutina guardada' : 'rutinas guardadas'}` : 'Guarda rutinas del Coach o del Builder para reutilizarlas'}
            </div>
          </div>
          <button onClick={() => navigate('/builder')} style={{ padding: '10px 16px', borderRadius: 10, border: 'none', cursor: 'pointer', background: '#2563EB', color: '#fff', fontFamily: 'Inter,system-ui', fontSize: 13, fontWeight: 700, flexShrink: 0 }}>+ Crear rutina</button>
        </div>

        {routines.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '64px 24px', borderRadius: 18, border: `1px dashed ${MR.border}`, background: MR.card }}>
            <div style={{ fontSize: 40, marginBottom: 14 }}>📋</div>
            <div style={{ fontFamily: 'Inter,system-ui', fontSize: 16, fontWeight: 700, color: MR.text, marginBottom: 8 }}>Todavía no tienes rutinas guardadas</div>
            <div style={{ fontFamily: 'Inter,system-ui', fontSize: 13, color: MR.sub, maxWidth: 420, margin: '0 auto 22px', lineHeight: 1.6 }}>
              Genera una rutina con Atlas Coach o créala en el Builder y pulsa «Guardar rutina» para tenerla aquí siempre lista.
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <button onClick={() => navigate('/coach')} style={{ padding: '11px 20px', borderRadius: 10, border: 'none', cursor: 'pointer', background: '#2563EB', color: '#fff', fontFamily: 'Inter,system-ui', fontSize: 13, fontWeight: 700 }}>Hablar con Coach</button>
              <button onClick={() => navigate('/builder')} style={{ padding: '11px 20px', borderRadius: 10, cursor: 'pointer', background: 'transparent', color: MR.sub, border: `1px solid ${MR.border}`, fontFamily: 'Inter,system-ui', fontSize: 13, fontWeight: 700 }}>Abrir Builder</button>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {routines.map(r => (
              <MrRoutineCard
                key={r.id}
                routine={r}
                onOpen={(rt) => setOpenId(rt.id)}
                onRename={actions.renameRoutine}
                onDuplicate={actions.duplicateRoutine}
                onDelete={deleteRoutine}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MisRutinasSection });
