// modals.jsx — New Task, My Family, Edit Pillars sheets

// ─────────────────────────────────────────────────────────────
// Sheet wrapper — slides up from bottom
// ─────────────────────────────────────────────────────────────
function Sheet({ open, onClose, theme, height = 'auto', maxHeight = '90%', children, title, dark }) {
  // Lock body scroll while open
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      pointerEvents: open ? 'auto' : 'none',
    }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: theme.overlay,
        opacity: open ? 1 : 0,
        transition: 'opacity .25s ease',
      }} />
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: theme.surface,
        borderTopLeftRadius: 22, borderTopRightRadius: 22,
        boxShadow: '0 -10px 40px rgba(0,0,0,0.15)',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform .3s cubic-bezier(.3,.7,.4,1)',
        maxHeight, display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
      }}>
        <div style={{
          width: 36, height: 4, borderRadius: 2,
          background: theme.border,
          margin: '8px auto 4px', flexShrink: 0,
        }} />
        {title && (
          <div style={{
            padding: '8px 18px 12px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            flexShrink: 0,
          }}>
            <div style={{
              fontSize: 16, fontWeight: 700, color: theme.text,
              letterSpacing: -0.2,
            }}>{title}</div>
            <button onClick={onClose} style={{
              appearance: 'none', cursor: 'pointer',
              background: theme.bg, border: 'none',
              width: 28, height: 28, borderRadius: 14,
              color: theme.textSoft, fontSize: 14,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'inherit',
            }}>✕</button>
          </div>
        )}
        <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>{children}</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// New Task sheet
// ─────────────────────────────────────────────────────────────
function NewTaskSheet({ open, onClose, family, theme, onCreate, prefillDate }) {
  const [title, setTitle]   = React.useState('');
  const [description, setDescription] = React.useState('');
  const [photo, setPhoto]   = React.useState(null);
  const [date, setDate]     = React.useState(prefillDate || todayISO());
  const [time, setTime]     = React.useState('');
  const [who, setWho]       = React.useState('me');
  const [pillar, setPillar] = React.useState('hijos');
  const [repeat, setRepeat] = React.useState(null);

  React.useEffect(() => {
    if (open) {
      setTitle(''); setDescription(''); setPhoto(null);
      setDate(prefillDate || todayISO()); setTime('');
      setWho('me'); setPillar('hijos'); setRepeat(null);
    }
  }, [open, prefillDate]);

  const valid = title.trim().length > 0;
  const submit = () => {
    if (!valid) return;
    onCreate({
      id: 't' + Date.now(),
      title: title.trim(),
      description: description.trim() || undefined,
      photo: photo || undefined,
      date, time: time || null,
      pillar, who, done: false, repeat,
    });
    onClose();
  };

  const FieldLabel = ({ children }) => (
    <div style={{
      fontSize: 10.5, fontWeight: 700, letterSpacing: 1.2,
      color: theme.textSoft, textTransform: 'uppercase', marginBottom: 6,
    }}>{children}</div>
  );

  return (
    <Sheet open={open} onClose={onClose} theme={theme} title="Nueva tarea" maxHeight="85%">
      <div style={{ padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <input value={title} onChange={(e) => setTitle(e.target.value)}
            placeholder="¿Qué tienes que hacer?" autoFocus
            style={{
              width: '100%', boxSizing: 'border-box',
              background: theme.bg, border: `1px solid ${theme.border}`,
              borderRadius: 12, padding: '14px 14px',
              fontSize: 15, fontWeight: 500, color: theme.text,
              fontFamily: 'inherit', outline: 'none',
              letterSpacing: -0.1,
            }} />
          <textarea value={description} onChange={(e) => setDescription(e.target.value)}
            placeholder="Notas, contexto, lo que necesitas recordar… (opcional)"
            rows={3}
            style={{
              width: '100%', boxSizing: 'border-box', marginTop: 8,
              background: theme.bg, border: `1px solid ${theme.border}`,
              borderRadius: 12, padding: '12px 14px',
              fontSize: 13.5, fontWeight: 400, color: theme.text,
              fontFamily: 'inherit', outline: 'none', resize: 'vertical',
              lineHeight: 1.45, letterSpacing: -0.05, minHeight: 70,
            }} />
          <div style={{ marginTop: 8 }}>
            <PhotoAttachField value={photo} onChange={setPhoto} theme={theme} />
          </div>
        </div>

        {/* Date + Time row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 10 }}>
          <div>
            <FieldLabel>Fecha</FieldLabel>
            <input type="date" value={date} onChange={(e) => setDate(e.target.value)}
              style={fieldStyle(theme)} />
          </div>
          <div>
            <FieldLabel>Hora</FieldLabel>
            <input type="time" value={time} onChange={(e) => setTime(e.target.value)}
              placeholder="Opcional"
              style={fieldStyle(theme)} />
          </div>
        </div>

        {/* Assignee */}
        <div>
          <FieldLabel>¿Quién lo hace?</FieldLabel>
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto', scrollbarWidth: 'none' }}>
            {family.map(m => {
              const active = m.id === who;
              return (
                <button key={m.id} onClick={() => setWho(m.id)}
                  style={{
                    appearance: 'none', cursor: 'pointer', flexShrink: 0,
                    display: 'flex', flexDirection: 'column',
                    alignItems: 'center', gap: 5, padding: 5,
                    background: 'transparent', border: 'none',
                    fontFamily: 'inherit',
                  }}>
                  <div style={{ position: 'relative' }}>
                    <Avatar member={m} size={42} showRing={active} />
                    {active && (
                      <div style={{
                        position: 'absolute', bottom: -2, right: -2,
                        width: 16, height: 16, borderRadius: '50%',
                        background: theme.primary,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        border: '2px solid white',
                      }}>
                        <svg width="8" height="8" viewBox="0 0 14 14">
                          <path d="M3 7.5 5.8 10.2 11 4.5" stroke="white" strokeWidth="2.4"
                                fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </div>
                    )}
                  </div>
                  <div style={{
                    fontSize: 11, fontWeight: active ? 700 : 500,
                    color: active ? theme.text : theme.textSoft,
                  }}>{m.name}</div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Pillar */}
        <div>
          <FieldLabel>Pilar</FieldLabel>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
            {Object.keys(PILLARS).map(pid => (
              <PillarPill key={pid} pillarId={pid}
                active={pid === pillar}
                onClick={() => setPillar(pid)}
                theme={theme} />
            ))}
          </div>
        </div>

        {/* Recurring */}
        <div>
          <FieldLabel>Se repite</FieldLabel>
          <RecurringEditor value={repeat} onChange={setRepeat} theme={theme} />
        </div>

        {/* Submit */}
        <button onClick={submit} disabled={!valid}
          style={{
            appearance: 'none', cursor: valid ? 'pointer' : 'not-allowed',
            background: valid ? theme.primary : theme.border,
            color: valid ? 'white' : theme.textSoft,
            border: 'none', borderRadius: 14,
            padding: '14px', fontSize: 14.5, fontWeight: 700,
            fontFamily: 'inherit', marginTop: 4,
            letterSpacing: -0.1,
          }}>Agregar tarea</button>
      </div>
    </Sheet>
  );
}

function fieldStyle(theme) {
  return {
    width: '100%', boxSizing: 'border-box',
    background: theme.bg, border: `1px solid ${theme.border}`,
    borderRadius: 10, padding: '11px 12px',
    fontSize: 14, color: theme.text,
    fontFamily: 'inherit', outline: 'none',
  };
}

// ─────────────────────────────────────────────────────────────
// Photo attachment field — icono cámara + miniatura
// Toca el icono → abre cámara/galería (input type=file, capture=environment).
// Si ya hay foto, muestra miniatura con botón X para quitar.
// ─────────────────────────────────────────────────────────────
function PhotoAttachField({ value, onChange, theme }) {
  const inputRef = React.useRef(null);
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => onChange(reader.result);
    reader.readAsDataURL(f);
    e.target.value = '';
  };
  if (value) {
    return (
      <div style={{ display: 'inline-flex', position: 'relative' }}>
        <img src={value} alt="adjunto"
          style={{
            width: 72, height: 72, borderRadius: 12,
            objectFit: 'cover',
            border: `1px solid ${theme.border}`,
          }} />
        <button onClick={() => onChange(null)}
          aria-label="Quitar foto"
          style={{
            position: 'absolute', top: -6, right: -6,
            appearance: 'none', cursor: 'pointer',
            width: 22, height: 22, borderRadius: 11,
            background: theme.surface, color: theme.text,
            border: `1px solid ${theme.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontWeight: 700, fontFamily: 'inherit',
            boxShadow: '0 1px 4px rgba(0,0,0,0.12)',
          }}>✕</button>
      </div>
    );
  }
  return (
    <button onClick={() => inputRef.current?.click()}
      type="button"
      aria-label="Adjuntar foto"
      style={{
        appearance: 'none', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 6,
        background: 'transparent', border: `1px dashed ${theme.border}`,
        color: theme.textSoft, padding: '8px 12px 8px 10px',
        borderRadius: 999, fontSize: 12, fontWeight: 600,
        fontFamily: 'inherit', letterSpacing: -0.05,
      }}>
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none">
        <path d="M4 8h3l2-3h6l2 3h3v11H4z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
        <circle cx="12" cy="13" r="3.5" stroke="currentColor" strokeWidth="1.6"/>
      </svg>
      Adjuntar foto
      <input ref={inputRef} type="file" accept="image/*" capture="environment"
        onChange={onFile}
        style={{ display: 'none' }} />
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Palette selector — 3 color swatches
// ─────────────────────────────────────────────────────────────
function PaletteRow({ theme, palette, onChange, customColor, onChangeCustomColor }) {
  const inputRef = React.useRef(null);
  const opts = [
    { id: 'rosa',   label: 'Rosa',   color: '#C9626B' },
    { id: 'morado', label: 'Morado', color: '#7A4DB5' },
    { id: 'verde',  label: 'Verde',  color: '#3E8A6A' },
  ];
  const customActive = palette === 'custom';
  return (
    <div style={{
      padding: '12px 14px',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8,
        background: theme.primarySoft,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: theme.primary, flexShrink: 0,
      }}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none">
          <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.6"/>
          <path d="M12 3a9 9 0 0 1 0 18M7.5 5.5l9 13M5.5 7.5l13 9" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
        </svg>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13.5, fontWeight: 600, color: theme.text,
          letterSpacing: -0.1, marginBottom: 8,
        }}>Color del tema</div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {opts.map(o => {
            const active = o.id === palette;
            return (
              <button key={o.id} onClick={() => onChange(o.id)}
                aria-label={o.label}
                title={o.label}
                style={{
                  appearance: 'none', cursor: 'pointer',
                  width: 32, height: 32, borderRadius: '50%',
                  background: o.color, padding: 0,
                  border: '2.5px solid transparent',
                  boxShadow: active
                    ? `0 0 0 2px ${o.color}, 0 2px 6px ${o.color}55`
                    : '0 1px 2px rgba(0,0,0,0.08)',
                  fontFamily: 'inherit',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  transition: 'box-shadow .15s ease, transform .15s ease',
                  transform: active ? 'scale(1.05)' : 'scale(1)',
                }}>
                {active && (
                  <svg width="12" height="12" viewBox="0 0 14 14">
                    <path d="M3 7.5 5.8 10.2 11 4.5" stroke="white" strokeWidth="2.4"
                          fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                )}
              </button>
            );
          })}
          {/* Divider */}
          <div style={{
            width: 1, height: 22, background: theme.border, margin: '0 2px',
          }} />
          {/* Eyedropper (custom color) */}
          <button onClick={() => inputRef.current?.click()}
            aria-label="Color personalizado"
            title="Color personalizado"
            style={{
              appearance: 'none', cursor: 'pointer', position: 'relative',
              width: 32, height: 32, borderRadius: '50%', padding: 0,
              background: customActive
                ? (customColor || '#C9626B')
                : `conic-gradient(from 0deg, #F97373, #F9C173, #E0F973, #73F995, #73E0F9, #9173F9, #F973C7, #F97373)`,
              border: '2.5px solid transparent',
              boxShadow: customActive
                ? `0 0 0 2px ${customColor || '#C9626B'}, 0 2px 6px rgba(0,0,0,0.15)`
                : '0 1px 2px rgba(0,0,0,0.08)',
              fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'box-shadow .15s ease, transform .15s ease',
              transform: customActive ? 'scale(1.05)' : 'scale(1)',
            }}>
            {customActive ? (
              <svg width="12" height="12" viewBox="0 0 14 14">
                <path d="M3 7.5 5.8 10.2 11 4.5" stroke="white" strokeWidth="2.4"
                      fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                style={{ filter: 'drop-shadow(0 1px 1px rgba(0,0,0,0.4))' }}>
                <path d="M14 4l6 6-9 9H5v-6l9-9z" fill="white" stroke="rgba(0,0,0,0.3)" strokeWidth="1" strokeLinejoin="round"/>
                <path d="M13 5l6 6" stroke="rgba(0,0,0,0.3)" strokeWidth="1"/>
              </svg>
            )}
            <input ref={inputRef} type="color"
              value={customColor || '#C9626B'}
              onChange={(e) => onChangeCustomColor && onChangeCustomColor(e.target.value)}
              style={{
                position: 'absolute', inset: 0, opacity: 0,
                width: '100%', height: '100%', cursor: 'pointer',
                border: 'none', padding: 0,
              }} />
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// My Family sheet
// ─────────────────────────────────────────────────────────────
function FamilySheet({ open, onClose, family, theme, onAdd, onRemove }) {
  const [name, setName] = React.useState('');
  const submit = () => {
    if (!name.trim()) return;
    onAdd(name.trim());
    setName('');
  };

  return (
    <Sheet open={open} onClose={onClose} theme={theme} title="Mi familia" maxHeight="70%">
      <div style={{ padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ fontSize: 13, color: theme.textSoft, lineHeight: 1.45 }}>
          La gente con la que compartes tareas. Se les puede asignar pendientes y recibir avisos.
        </div>

        {/* Chips */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {family.map(m => (
            <div key={m.id} style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              background: theme.bg, border: `1px solid ${theme.border}`,
              borderRadius: 999, padding: '5px 5px 5px 7px',
            }}>
              <Avatar member={m} size={22} />
              <span style={{ fontSize: 13, fontWeight: 600, color: theme.text }}>{m.name}</span>
              {m.id !== 'me' && (
                <button onClick={() => onRemove(m.id)}
                  style={{
                    appearance: 'none', cursor: 'pointer',
                    background: 'transparent', border: 'none',
                    color: theme.textSoft, fontSize: 12, padding: '2px 6px',
                    fontFamily: 'inherit',
                  }}>✕</button>
              )}
            </div>
          ))}
        </div>

        {/* Add input */}
        <div style={{ display: 'flex', gap: 8 }}>
          <input value={name} onChange={(e) => setName(e.target.value)}
            placeholder="Agregar a alguien..."
            onKeyDown={(e) => e.key === 'Enter' && submit()}
            style={{ flex: 1, ...fieldStyle(theme), padding: '12px 14px', fontSize: 14 }} />
          <button onClick={submit} disabled={!name.trim()}
            style={{
              appearance: 'none', cursor: name.trim() ? 'pointer' : 'not-allowed',
              background: name.trim() ? theme.primary : theme.border,
              color: name.trim() ? 'white' : theme.textSoft,
              border: 'none', borderRadius: 10,
              width: 44, fontSize: 22, fontWeight: 500,
              fontFamily: 'inherit', lineHeight: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>+</button>
        </div>

        <div style={{
          fontSize: 11, color: theme.textSoft,
          background: theme.surfaceAlt, border: `1px solid ${theme.primaryBorder}`,
          borderRadius: 10, padding: '10px 12px', lineHeight: 1.5,
        }}>
          🌸 Tip: cada quien ve solo sus tareas asignadas, pero todos ven el calendario familiar.
        </div>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Edit Pillars sheet — toggle visibility
// ─────────────────────────────────────────────────────────────
function PillarsSheet({ open, onClose, theme, visible, onToggle }) {
  return (
    <Sheet open={open} onClose={onClose} theme={theme} title="Mis pilares" maxHeight="80%">
      <div style={{ padding: '0 18px 18px' }}>
        <div style={{ fontSize: 13, color: theme.textSoft, lineHeight: 1.45, marginBottom: 16 }}>
          Los pilares son las áreas de tu vida. Activa solo los que vives ahorita — no tienes que llevar todo siempre.
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {Object.keys(PILLARS).map(pid => {
            const p = PILLARS[pid];
            const on = visible.includes(pid);
            return (
              <div key={pid} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 14px',
                background: on ? p.bg : theme.bg,
                border: `1px solid ${on ? p.border : theme.border}`,
                borderRadius: 12,
              }}>
                <div style={{
                  fontSize: 22, width: 36, height: 36, borderRadius: 10,
                  background: 'white', border: `1px solid ${p.border}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{p.emoji}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: on ? p.text : theme.text, letterSpacing: -0.1 }}>{p.label}</div>
                  <div style={{ fontSize: 11.5, color: theme.textSoft, marginTop: 1 }}>
                    {{
                      hijos: 'Cosas de tus peques',
                      escuela: 'Juntas, tareas, eventos',
                      citas: 'Médicos, especialistas',
                      personal: 'Tiempo para ti',
                    }[pid]}
                  </div>
                </div>
                <button onClick={() => onToggle(pid)}
                  style={{
                    appearance: 'none', cursor: 'pointer',
                    width: 44, height: 26, borderRadius: 999,
                    background: on ? theme.primary : theme.border,
                    border: 'none', position: 'relative',
                    padding: 0, transition: 'background .2s ease',
                  }}>
                  <div style={{
                    position: 'absolute', top: 2,
                    left: on ? 20 : 2,
                    width: 22, height: 22, borderRadius: '50%',
                    background: 'white',
                    boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
                    transition: 'left .2s ease',
                  }} />
                </button>
              </div>
            );
          })}
        </div>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Settings sheet — full profile, notifications, theme, account
// ─────────────────────────────────────────────────────────────
const PROFILE_EMOJIS = ['🌸','🌷','🌻','🌼','🌹','🌺','💐','🌿','🍀','✨','💛','💜','💗','🦋','☕️','📚'];

// Flat line-icon set for Settings (Valeria's avatar still uses an emoji)
function Icon({ name, size = 16, color = 'currentColor', strokeWidth = 1.6 }) {
  const p = (d) => <path d={d} fill="none" stroke={color} strokeWidth={strokeWidth}
                          strokeLinecap="round" strokeLinejoin="round" />;
  const c = (cx, cy, r) => <circle cx={cx} cy={cy} r={r} fill="none" stroke={color} strokeWidth={strokeWidth} />;
  const paths = {
    bell:     <>{p('M5 16h14M12 3a5 5 0 0 0-5 5v3l-2 4h14l-2-4V8a5 5 0 0 0-5-5z')}{p('M10 19a2 2 0 0 0 4 0')}</>,
    users:    <>{c(9, 9, 3)}{p('M3 19a6 6 0 0 1 12 0')}{p('M16 6.5a3 3 0 0 1 0 5')}{p('M21 19a5 5 0 0 0-3-4.6')}</>,
    target:   <>{c(12,12,8)}{c(12,12,4.5)}{c(12,12,1.5)}</>,
    moon:     <>{p('M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z')}</>,
    layout:   <>{p('M4 5h16v14H4z')}{p('M4 10h16M10 10v9')}</>,
    key:      <>{c(7,15,4)}{p('M10 12l10-10M16 6l3 3M14 8l3 3')}</>,
    refresh:  <>{p('M3 12a9 9 0 0 1 15-6.7L21 8')}{p('M21 4v4h-4')}{p('M21 12a9 9 0 0 1-15 6.7L3 16')}{p('M3 20v-4h4')}</>,
    sparkles: <>{p('M12 4v4M12 16v4M4 12h4M16 12h4M6 6l2 2M16 16l2 2M6 18l2-2M16 8l2-2')}</>,
    info:     <>{c(12,12,9)}{p('M12 8h.01M11 11h1v6h1')}</>,
    sun:      <>{c(12,12,3.5)}{p('M12 3v2M12 19v2M4.2 4.2l1.4 1.4M18.4 18.4l1.4 1.4M3 12h2M19 12h2M4.2 19.8l1.4-1.4M18.4 5.6l1.4-1.4')}</>,
    chart:    <>{p('M4 4v16h16')}{p('M8 16V11M12 16V7M16 16v-4')}</>,
    mail:     <>{p('M4 6h16v12H4z')}{p('M4 6l8 7 8-7')}</>,
    lock:     <>{p('M6 11h12v9H6z')}{p('M9 11V8a3 3 0 0 1 6 0v3')}</>,
    globe:    <>{c(12,12,9)}{p('M3 12h18M12 3a13 13 0 0 1 0 18M12 3a13 13 0 0 0 0 18')}</>,
    exit:     <>{p('M14 8V5H4v14h10v-3')}{p('M9 12h12M17 8l4 4-4 4')}</>,
    trash:    <>{p('M5 7h14M9 7V4h6v3M7 7l1 13h8l1-13')}</>,
    help:     <>{c(12,12,9)}{p('M9.5 9.5a2.5 2.5 0 0 1 5 0c0 1.5-2.5 2-2.5 3.5M12 17h.01')}</>,
    chat:     <>{p('M4 5h16v11H8l-4 4z')}</>,
    doc:      <>{p('M6 3h9l4 4v14H6z')}{p('M15 3v4h4M9 12h7M9 16h7M9 8h3')}</>,
    flower:   <>{c(12,12,2.2)}{p('M12 9.8c-1-2.5-3.8-3-5-1-1.2 2 .3 4.5 3 5M12 9.8c1-2.5 3.8-3 5-1 1.2 2-.3 4.5-3 5M12 14.2c-1 2.5-3.8 3-5 1-1.2-2 .3-4.5 3-5M12 14.2c1 2.5 3.8 3 5 1 1.2-2-.3-4.5-3-5')}</>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block' }}>
      {paths[name] || null}
    </svg>
  );
}

function SettingsSheet({ open, onClose, theme,
                         profile, onUpdateProfile,
                         notif, onUpdateNotif,
                         dark, onToggleDark,
                         density, onChangeDensity,
                         palette, onChangePalette,
                         customColor, onChangeCustomColor,
                         onOpenFamily, onOpenPillars,
                         onRedoOnboarding, onReset }) {
  const [pane, setPane] = React.useState('root'); // 'root' | 'profile' | 'notifications' | 'account' | 'about'
  React.useEffect(() => { if (!open) setPane('root'); }, [open]);

  const back = () => setPane('root');

  return (
    <Sheet open={open} onClose={onClose} theme={theme}
           title={pane === 'root' ? 'Ajustes'
                : pane === 'profile' ? 'Tu perfil'
                : pane === 'notifications' ? 'Notificaciones'
                : pane === 'account' ? 'Cuenta'
                : pane === 'about' ? 'Acerca de' : 'Ajustes'}
           maxHeight="88%">
      {pane !== 'root' && (
        <button onClick={back} style={{
          appearance: 'none', cursor: 'pointer', background: 'transparent', border: 'none',
          padding: '4px 18px 8px', display: 'flex', alignItems: 'center', gap: 6,
          color: theme.textSoft, fontSize: 13, fontFamily: 'inherit',
        }}>
          <svg width="14" height="14" viewBox="0 0 16 16">
            <path d="M11 3L6 8l5 5" stroke="currentColor" strokeWidth="1.8"
                  fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          Volver
        </button>
      )}
      <div style={{ padding: '0 0 24px', overflow: 'auto' }}>
        {pane === 'root' && (
          <SettingsRoot
            theme={theme} profile={profile} dark={dark} density={density}
            palette={palette} onChangePalette={onChangePalette}
            customColor={customColor} onChangeCustomColor={onChangeCustomColor}
            onToggleDark={onToggleDark} onChangeDensity={onChangeDensity}
            onOpenFamily={onOpenFamily} onOpenPillars={onOpenPillars}
            goto={setPane} onClose={onClose}
            onRedoOnboarding={onRedoOnboarding} onReset={onReset}
          />
        )}
        {pane === 'profile' && (
          <ProfilePane theme={theme} profile={profile} onUpdate={onUpdateProfile} />
        )}
        {pane === 'notifications' && (
          <NotificationsPane theme={theme} notif={notif} onUpdate={onUpdateNotif} />
        )}
        {pane === 'account' && (
          <AccountPane theme={theme} profile={profile} />
        )}
        {pane === 'about' && (
          <AboutPane theme={theme} />
        )}
      </div>
    </Sheet>
  );
}

// ── Root: list of section entries ─────────────────────────────
function SettingsRoot({ theme, profile, dark, density, onToggleDark, onChangeDensity,
                        palette, onChangePalette,
                        customColor, onChangeCustomColor,
                        onOpenFamily, onOpenPillars, goto, onClose,
                        onRedoOnboarding, onReset }) {
  return (
    <div>
      {/* Profile card */}
      <button onClick={() => goto('profile')} style={{
        appearance: 'none', cursor: 'pointer', width: 'calc(100% - 36px)',
        margin: '4px 18px 14px', padding: '12px 14px',
        background: theme.primarySoft, border: 'none', borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 12,
        fontFamily: 'inherit', textAlign: 'left',
      }}>
        <div style={{
          width: 48, height: 48, borderRadius: 24,
          background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 24, boxShadow: '0 1px 4px rgba(0,0,0,0.06)',
        }}>{profile.emoji || '🌸'}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: theme.text, letterSpacing: -0.2 }}>
            {profile.name || 'Tu nombre'}
          </div>
          <div style={{ fontSize: 12, color: theme.textSoft, marginTop: 2,
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {profile.email}
          </div>
        </div>
        <div style={{ fontSize: 12, fontWeight: 600, color: theme.primary, letterSpacing: -0.05 }}>
          Editar
        </div>
      </button>

      <SettingsGroup theme={theme} label="Tu día">
        <SettingsRow theme={theme} icon={<Icon name="bell" />} label="Notificaciones"
          hint="Recordatorios, mood, resumen semanal" onClick={() => goto('notifications')} />
        <SettingsRow theme={theme} icon={<Icon name="users" />} label="Mi familia"
          hint="Invita a tu pareja o a quien te ayuda"
          onClick={onOpenFamily} />
        <SettingsRow theme={theme} icon={<Icon name="target" />} label="Mis pilares"
          hint="Qué áreas quieres ver"
          onClick={onOpenPillars} />
      </SettingsGroup>

      <SettingsGroup theme={theme} label="Apariencia">
        <SettingsToggle theme={theme} icon={<Icon name="moon" />} label="Modo oscuro"
          value={dark} onChange={onToggleDark} />
        <SettingsSegment theme={theme} icon={<Icon name="layout" />} label="Densidad"
          options={[{ value: 'comfy', label: 'Cómodo' }, { value: 'compact', label: 'Compacto' }]}
          value={density} onChange={onChangeDensity} />
        <PaletteRow theme={theme} palette={palette} onChange={onChangePalette}
          customColor={customColor} onChangeCustomColor={onChangeCustomColor} />
      </SettingsGroup>

      <SettingsGroup theme={theme} label="Cuenta">
        <SettingsRow theme={theme} icon={<Icon name="key" />} label="Cuenta y suscripción"
          hint="Plan, contraseña, idioma" onClick={() => goto('account')} />
      </SettingsGroup>

      <SettingsGroup theme={theme} label="Más">
        <SettingsRow theme={theme} icon={<Icon name="refresh" />} label="Repetir bienvenida"
          hint="Vuelve a contarme cómo va tu vida ahora"
          onClick={() => { onClose(); setTimeout(onRedoOnboarding, 250); }} />
        <SettingsRow theme={theme} icon={<Icon name="sparkles" />} label="Restablecer datos de ejemplo"
          color={theme.textSoft} onClick={() => { onReset(); onClose(); }} />
        <SettingsRow theme={theme} icon={<Icon name="info" />} label="Acerca de MamaFlow"
          onClick={() => goto('about')} />
      </SettingsGroup>

      <div style={{ padding: '20px 18px 4px', textAlign: 'center', color: theme.textSoft,
                    fontSize: 11, lineHeight: 1.6 }}>
        Hecha con cariño para mamás<br/>
        v1.0
      </div>
    </div>
  );
}
function notifFromTheme() { return null; }
function notifSummary() { return 'Recordatorios, mood, resumen semanal'; }

// ── Profile pane ──────────────────────────────────────────────
function ProfilePane({ theme, profile, onUpdate }) {
  return (
    <div style={{ padding: '0 18px' }}>
      <div style={{ textAlign: 'center', marginBottom: 18 }}>
        <div style={{
          width: 84, height: 84, borderRadius: 42, margin: '0 auto 10px',
          background: theme.primarySoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 42,
        }}>{profile.emoji || '🌸'}</div>
        <div style={{ fontSize: 11, color: theme.textSoft, letterSpacing: 0.4, textTransform: 'uppercase', fontWeight: 600 }}>
          Elige tu emoji
        </div>
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 6,
        marginBottom: 24, padding: '12px', background: theme.surfaceAlt || theme.primarySoft,
        borderRadius: 14,
      }}>
        {PROFILE_EMOJIS.map(e => (
          <button key={e} onClick={() => onUpdate({ emoji: e })} style={{
            appearance: 'none', cursor: 'pointer', border: 'none',
            background: e === profile.emoji ? 'white' : 'transparent',
            borderRadius: 10, padding: '6px 0', fontSize: 22,
            boxShadow: e === profile.emoji ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
            transition: 'background .15s',
          }}>{e}</button>
        ))}
      </div>

      <SettingsLabel theme={theme}>Cómo te llamamos</SettingsLabel>
      <input type="text" value={profile.name || ''}
        onChange={(e) => onUpdate({ name: e.target.value })}
        placeholder="Tu nombre"
        style={{ ...fieldStyle(theme), marginBottom: 18 }} />

      <SettingsLabel theme={theme}>Email</SettingsLabel>
      <input type="email" value={profile.email || ''}
        onChange={(e) => onUpdate({ email: e.target.value })}
        placeholder="tu@email.com"
        style={{ ...fieldStyle(theme), marginBottom: 18 }} />

      <div style={{
        fontSize: 11.5, color: theme.textSoft, lineHeight: 1.5,
        padding: '10px 12px', background: theme.surfaceAlt || theme.primarySoft,
        borderRadius: 10,
      }}>
        Solo usamos tu nombre para saludarte. Tus datos no se comparten.
      </div>
    </div>
  );
}

// ── Notifications pane ────────────────────────────────────────
function NotificationsPane({ theme, notif, onUpdate }) {
  return (
    <div style={{ padding: '0 18px' }}>
      <div style={{
        padding: '10px 12px', background: theme.surfaceAlt || theme.primarySoft,
        borderRadius: 10, fontSize: 12, color: theme.textSoft, lineHeight: 1.5,
        marginBottom: 18,
      }}>
        Solo enviamos lo necesario. Nada de spam ni notificaciones genéricas.
      </div>

      <SettingsGroupInline theme={theme}>
        <SettingsToggle theme={theme} icon={<Icon name="bell" />} label="Recordatorios de tareas"
          hint="Solo de cosas con hora fija"
          value={notif.reminders} onChange={(v) => onUpdate({ reminders: v })} />
        <SettingsToggle theme={theme} icon={<Icon name="sun" />} label="Check-in de mood"
          hint="Una pregunta corta cada mañana"
          value={notif.mood} onChange={(v) => onUpdate({ mood: v })} />
        <SettingsToggle theme={theme} icon={<Icon name="chart" />} label="Resumen semanal"
          hint="Domingos por la tarde: cómo te fue"
          value={notif.weekly} onChange={(v) => onUpdate({ weekly: v })} />
        <SettingsToggle theme={theme} icon={<Icon name="users" />} label="Actividad de la familia"
          hint="Cuando alguien marca o agrega algo"
          value={notif.partner} onChange={(v) => onUpdate({ partner: v })} />
      </SettingsGroupInline>

      <SettingsLabel theme={theme} style={{ marginTop: 20 }}>Horario de descanso</SettingsLabel>
      <div style={{ fontSize: 12, color: theme.textSoft, marginBottom: 12, lineHeight: 1.45 }}>
        No te molestamos entre estas horas. Las cosas urgentes pueden esperar.
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <div style={{ flex: 1 }}>
          <SettingsLabel theme={theme} small>Desde</SettingsLabel>
          <input type="time" value={notif.quietStart}
            onChange={(e) => onUpdate({ quietStart: e.target.value })}
            style={fieldStyle(theme)} />
        </div>
        <div style={{ flex: 1 }}>
          <SettingsLabel theme={theme} small>Hasta</SettingsLabel>
          <input type="time" value={notif.quietEnd}
            onChange={(e) => onUpdate({ quietEnd: e.target.value })}
            style={fieldStyle(theme)} />
        </div>
      </div>
    </div>
  );
}

// ── Account pane ──────────────────────────────────────────────
function AccountPane({ theme, profile }) {
  return (
    <div style={{ padding: '0 18px' }}>
      <SettingsGroupInline theme={theme}>
        <SettingsRow theme={theme} icon={<Icon name="mail" />} label="Email" hint={profile.email} onClick={() => alert('Editar email')} />
        <SettingsRow theme={theme} icon={<Icon name="lock" />} label="Cambiar contraseña" onClick={() => alert('Cambiar contraseña')} />
        <SettingsRow theme={theme} icon={<Icon name="globe" />} label="Idioma" hint="Español" onClick={() => alert('Cambiar idioma')} />
      </SettingsGroupInline>

      <div style={{ marginTop: 22 }} />
      <SettingsLabel theme={theme}>Plan</SettingsLabel>
      <div style={{
        background: 'linear-gradient(135deg, #FDE7E7 0%, #FFC9D2 100%)',
        borderRadius: 16, padding: '16px 16px 14px',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#A04A57',
                      letterSpacing: 0.6, textTransform: 'uppercase' }}>Gratis</div>
        <div style={{ fontSize: 18, fontWeight: 700, color: '#5B2B36', marginTop: 4, letterSpacing: -0.2 }}>
          MamaFlow esencial
        </div>
        <div style={{ fontSize: 12.5, color: '#7A4451', marginTop: 6, lineHeight: 1.45 }}>
          Captura por foto, sincronización con tu pareja y modo cuidador sin límite.
        </div>
        <button style={{
          appearance: 'none', cursor: 'pointer', marginTop: 12,
          background: '#5B2B36', color: 'white', border: 'none',
          padding: '10px 16px', borderRadius: 12, fontFamily: 'inherit',
          fontSize: 13, fontWeight: 600, letterSpacing: -0.05,
        }}>Probar Premium gratis 14 días</button>
      </div>

      <div style={{ marginTop: 24 }} />
      <SettingsGroupInline theme={theme}>
        <SettingsRow theme={theme} icon={<Icon name="exit" />} label="Cerrar sesión" color={theme.textSoft}
          onClick={() => alert('Cerrar sesión')} />
        <SettingsRow theme={theme} icon={<Icon name="trash" />} label="Borrar mi cuenta" color="#C9626B"
          onClick={() => alert('Borrar cuenta')} />
      </SettingsGroupInline>
    </div>
  );
}

// ── About pane ────────────────────────────────────────────────
function AboutPane({ theme }) {
  return (
    <div style={{ padding: '0 18px' }}>
      <div style={{ textAlign: 'center', padding: '8px 0 20px' }}>
        <div style={{
          width: 56, height: 56, borderRadius: 28, margin: '0 auto 10px',
          background: theme.primarySoft, color: theme.primary,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name="flower" size={28} strokeWidth={1.8} /></div>
        <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.3 }}>MamaFlow</div>
        <div style={{ fontSize: 12, color: theme.textSoft, marginTop: 2 }}>v1.0</div>
      </div>

      <SettingsGroupInline theme={theme}>
        <SettingsRow theme={theme} icon={<Icon name="help" />} label="Centro de ayuda" onClick={() => alert('Ayuda')} />
        <SettingsRow theme={theme} icon={<Icon name="chat" />} label="Escríbenos" hint="hola@mamaflow.app" onClick={() => alert('Email')} />
        <SettingsRow theme={theme} icon={<Icon name="lock" />} label="Privacidad" onClick={() => alert('Privacidad')} />
        <SettingsRow theme={theme} icon={<Icon name="doc" />} label="Términos de uso" onClick={() => alert('Términos')} />
      </SettingsGroupInline>

      <div style={{ padding: '24px 8px 4px', textAlign: 'center', color: theme.textSoft,
                    fontSize: 11.5, lineHeight: 1.6 }}>
        Hecha con cariño en CDMX para mamás que ya tienen suficiente en la cabeza.
      </div>
    </div>
  );
}

// ── Shared atoms ──────────────────────────────────────────────
function SettingsGroup({ theme, label, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      {label && (
        <div style={{
          padding: '0 18px 6px', fontSize: 11, fontWeight: 700,
          color: theme.textSoft, letterSpacing: 0.6, textTransform: 'uppercase',
        }}>{label}</div>
      )}
      <div style={{
        margin: '0 14px', background: theme.surface,
        border: `1px solid ${theme.borderSoft || theme.border}`,
        borderRadius: 14, overflow: 'hidden',
      }}>
        {children}
      </div>
    </div>
  );
}
function SettingsGroupInline({ theme, children }) {
  return (
    <div style={{
      background: theme.surface,
      border: `1px solid ${theme.borderSoft || theme.border}`,
      borderRadius: 14, overflow: 'hidden',
    }}>{children}</div>
  );
}
function SettingsLabel({ theme, children, small, style }) {
  return (
    <div style={{
      padding: small ? '0 0 4px' : '0 0 6px',
      fontSize: small ? 10.5 : 11,
      fontWeight: 700, color: theme.textSoft,
      letterSpacing: 0.6, textTransform: 'uppercase',
      ...style,
    }}>{children}</div>
  );
}
function SettingsRow({ theme, icon, label, hint, onClick, color }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'pointer', width: '100%',
      background: 'transparent', border: 'none',
      padding: '13px 14px', display: 'flex', alignItems: 'center', gap: 12,
      borderTop: `1px solid ${theme.borderSoft || 'rgba(0,0,0,0.04)'}`,
      fontFamily: 'inherit', textAlign: 'left',
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 9,
        background: theme.primarySoft, color: theme.primary,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: color || theme.text, letterSpacing: -0.1 }}>
          {label}
        </div>
        {hint && (
          <div style={{ fontSize: 11.5, color: theme.textSoft, marginTop: 1,
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {hint}
          </div>
        )}
      </div>
      <svg width="14" height="14" viewBox="0 0 16 16" style={{ flexShrink: 0 }}>
        <path d="M5 3l5 5-5 5" stroke={theme.textSoft} strokeWidth="1.8"
              fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </button>
  );
}
function SettingsToggle({ theme, icon, label, hint, value, onChange }) {
  return (
    <div style={{
      padding: '13px 14px', display: 'flex', alignItems: 'center', gap: 12,
      borderTop: `1px solid ${theme.borderSoft || 'rgba(0,0,0,0.04)'}`,
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 9, background: theme.primarySoft, color: theme.primary,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: theme.text, letterSpacing: -0.1 }}>{label}</div>
        {hint && <div style={{ fontSize: 11.5, color: theme.textSoft, marginTop: 1 }}>{hint}</div>}
      </div>
      <button onClick={() => onChange(!value)} style={{
        appearance: 'none', cursor: 'pointer', border: 'none',
        width: 42, height: 24, borderRadius: 12, padding: 2,
        background: value ? theme.primary : theme.border,
        display: 'flex', justifyContent: value ? 'flex-end' : 'flex-start',
        transition: 'background .2s, justify-content .2s', flexShrink: 0,
      }}>
        <div style={{
          width: 20, height: 20, borderRadius: 10, background: 'white',
          boxShadow: '0 1px 3px rgba(0,0,0,0.18)',
        }} />
      </button>
    </div>
  );
}
function SettingsSegment({ theme, icon, label, options, value, onChange }) {
  return (
    <div style={{
      padding: '13px 14px', display: 'flex', alignItems: 'center', gap: 12,
      borderTop: `1px solid ${theme.borderSoft || 'rgba(0,0,0,0.04)'}`,
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 9, background: theme.primarySoft, color: theme.primary,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{icon}</div>
      <div style={{ flex: 1, fontSize: 14, fontWeight: 500, color: theme.text, letterSpacing: -0.1 }}>
        {label}
      </div>
      <div style={{
        display: 'flex', background: theme.primarySoft, borderRadius: 9, padding: 2,
      }}>
        {options.map(opt => (
          <button key={opt.value} onClick={() => onChange(opt.value)} style={{
            appearance: 'none', cursor: 'pointer', border: 'none',
            background: value === opt.value ? 'white' : 'transparent',
            color: theme.text, fontSize: 12, fontWeight: 600, letterSpacing: -0.05,
            padding: '5px 10px', borderRadius: 7, fontFamily: 'inherit',
            boxShadow: value === opt.value ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
            transition: 'all .15s',
          }}>{opt.label}</button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, {
  Sheet, NewTaskSheet, FamilySheet, PillarsSheet, SettingsSheet,
  fieldStyle,
});
