// components.jsx — shared building blocks for MamaFlow

// ─────────────────────────────────────────────────────────────
// Theme tokens — light + dark
// ─────────────────────────────────────────────────────────────
const THEME = {
  light: {
    bg:        '#FAF6F6',
    surface:   '#FFFFFF',
    surfaceAlt:'#FFF0F5',
    text:      '#1F1515',
    textSoft:  '#75605F',
    border:    '#EDE0E0',
    borderSoft:'#F5EBEB',
    primary:   '#C9626B',
    primarySoft:'#FFF0F5',
    primaryBorder:'#FFB8CC',
    secondary: '#E8789B',
    whatsapp:  '#25D366',
    shadow:    '0 1px 2px rgba(31,21,21,0.04)',
    overlay:   'rgba(31,21,21,0.45)',
  },
  dark: {
    bg:        '#1A1212',
    surface:   '#241818',
    surfaceAlt:'#2E1E22',
    text:      '#F5ECEC',
    textSoft:  '#A8908F',
    border:    '#3A2828',
    borderSoft:'#2E1E1E',
    primary:   '#E07882',
    primarySoft:'#3A1F25',
    primaryBorder:'#5C2F38',
    secondary: '#E8789B',
    whatsapp:  '#25D366',
    shadow:    '0 1px 2px rgba(0,0,0,0.3)',
    overlay:   'rgba(0,0,0,0.65)',
  }
};

// Density multipliers
const DENSITY = {
  compact: { gap: 8,  pad: 12, taskPad: 11, mood: 38, cardR: 10 },
  comfy:   { gap: 14, pad: 18, taskPad: 16, mood: 48, cardR: 14 },
};

// ─────────────────────────────────────────────────────────────
// Pillar Pill — selectable filter or static tag
// ─────────────────────────────────────────────────────────────
function PillarTag({ pillarId, size = 'sm', style = {} }) {
  const p = PILLARS[pillarId];
  if (!p) return null;
  const small = size === 'sm';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      background: p.bg, color: p.text,
      border: `1px solid ${p.border}`,
      borderRadius: 999,
      padding: small ? '2px 8px 2px 6px' : '4px 10px 4px 8px',
      fontSize: small ? 10.5 : 12, fontWeight: 600, letterSpacing: 0.1,
      lineHeight: 1.3, whiteSpace: 'nowrap',
      ...style,
    }}>
      <span style={{ fontSize: small ? 11 : 13, filter: 'saturate(1.1)' }}>{p.emoji}</span>
      {p.label}
    </span>
  );
}

function PillarPill({ pillarId, active, onClick, theme }) {
  const p = PILLARS[pillarId];
  return (
    <button onClick={onClick}
      style={{
        appearance: 'none', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '7px 13px 7px 11px',
        borderRadius: 999,
        background: active ? p.bg : 'transparent',
        color: active ? p.text : theme.textSoft,
        border: `1px solid ${active ? p.border : theme.border}`,
        fontSize: 12.5, fontWeight: 600, letterSpacing: 0.1,
        whiteSpace: 'nowrap', flexShrink: 0,
        transition: 'all .15s ease',
      }}>
      <span style={{ fontSize: 14 }}>{p.emoji}</span>
      {p.label}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Checkbox — square rounded
// ─────────────────────────────────────────────────────────────
function Checkbox({ checked, onChange, primary, border, size = 22 }) {
  return (
    <button onClick={onChange} aria-label={checked ? 'Desmarcar' : 'Completar'}
      style={{
        appearance: 'none', cursor: 'pointer', flexShrink: 0,
        width: size, height: size, borderRadius: 6,
        background: checked ? primary : 'transparent',
        border: `1.5px solid ${checked ? primary : border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 0, transition: 'all .2s cubic-bezier(.3,.7,.4,1.5)',
        transform: checked ? 'scale(1)' : 'scale(1)',
      }}>
      {checked && (
        <svg width={size * 0.6} height={size * 0.6} viewBox="0 0 14 14" style={{
          animation: 'mf-check-pop .25s ease-out',
        }}>
          <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>
  );
}

// ─────────────────────────────────────────────────────────────
// Family avatar (circular initial)
// ─────────────────────────────────────────────────────────────
function Avatar({ member, size = 24, showRing = false }) {
  if (!member) return null;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: member.color, color: 'white',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.42, fontWeight: 700,
      boxShadow: showRing ? `0 0 0 2px white, 0 0 0 3.5px ${member.color}` : 'none',
      flexShrink: 0, letterSpacing: 0,
    }}>{member.short}</div>
  );
}

// "Asignado" badge — pill with member name. Tappable to filter by person.
function AssigneeBadge({ member, theme, onClick }) {
  if (!member) return null;
  const isMe = member.id === 'me';
  const interactive = !!onClick;
  const stop = (e) => e.stopPropagation();
  return (
    <span
      onClick={interactive ? (e) => { e.stopPropagation(); onClick(member.id); } : undefined}
      onMouseDown={interactive ? stop : undefined}
      onMouseUp={interactive ? stop : undefined}
      onTouchStart={interactive ? stop : undefined}
      onTouchEnd={interactive ? stop : undefined}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '2px 8px 2px 6px',
        borderRadius: 999,
        background: isMe ? theme.primarySoft : '#EEF2FF',
        color: isMe ? theme.primary : '#4A5FD5',
        fontSize: 10.5, fontWeight: 600, letterSpacing: 0.1,
        lineHeight: 1.3, whiteSpace: 'nowrap',
        cursor: interactive ? 'pointer' : 'default',
      }}>
      <span style={{ fontSize: 11 }}>{isMe ? '👩' : member.short === 'P' ? '👨' : member.short === 'A' ? '👵' : '👤'}</span>
      {member.name}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Task card
// ─────────────────────────────────────────────────────────────
function TaskCard({ task, family, theme, density, onToggle, onClick, onAssigneeClick, compact = false }) {
  const member = family.find(m => m.id === task.who);
  const d = DENSITY[density];
  return (
    <div onClick={onClick}
      style={{
        background: theme.surface,
        border: `1px solid ${theme.border}`,
        borderRadius: d.cardR + 2,
        padding: d.taskPad,
        display: 'flex', alignItems: 'flex-start', gap: 12,
        cursor: onClick ? 'pointer' : 'default',
        opacity: task.done ? 0.55 : 1,
        transition: 'opacity .25s ease',
      }}>
      <div onClick={(e) => e.stopPropagation()}>
        <Checkbox
          checked={task.done}
          onChange={() => onToggle(task.id)}
          primary={theme.primary}
          border={theme.border}
        />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: d.fontSize, fontWeight: 600, color: theme.text,
          textDecoration: task.done ? 'line-through' : 'none',
          textDecorationColor: theme.textSoft,
          textDecorationThickness: 1.5,
          lineHeight: 1.35, marginBottom: density === 'compact' ? 4 : 6,
          letterSpacing: -0.05,
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          {task.repeat && <span title="Se repite" style={{ fontSize: 10, opacity: 0.55 }}>↻</span>}
          <span style={{ flex: 1, minWidth: 0 }}>{task.title}</span>
          {task.photo && (
            <span title="Tiene foto" aria-label="Tiene foto"
              style={{ color: theme.textSoft, opacity: 0.7, fontSize: 11, flexShrink: 0 }}>
              <svg width="13" height="13" 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>
            </span>
          )}
        </div>
        {task.description && !compact && !task.done && (
          <div style={{
            fontSize: 12, color: theme.textSoft, lineHeight: 1.4,
            marginBottom: density === 'compact' ? 6 : 8,
            display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
            overflow: 'hidden', letterSpacing: -0.05,
          }}>{task.description}</div>
        )}
        <div style={{
          display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6,
        }}>
          <PillarTag pillarId={task.pillar} />
          {task.time && (
            <span style={{ fontSize: d.sub, color: theme.textSoft, fontWeight: 500 }}>
              {fmtTime(task.time)}
            </span>
          )}
          {!compact && member && <AssigneeBadge member={member} theme={theme} onClick={onAssigneeClick} />}
        </div>
      </div>
      {compact && member && (
        <Avatar member={member} size={d.avatar} />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Segmented view switcher (Lista / Mes / Tú) — toggle compacto
// para alternar las 3 vistas del mismo dato.
// ─────────────────────────────────────────────────────────────
function ViewSwitcher({ value, onChange, theme }) {
  const opts = [
    { id: 'tasks',    label: 'Lista',     icon: ListIcon },
    { id: 'calendar', label: 'Mes',       icon: CalIcon  },
    { id: 'tu',       label: 'Tú',        icon: HeartIcon },
  ];
  return (
    <div style={{
      display: 'inline-flex',
      background: 'rgba(0,0,0,0.04)',
      borderRadius: 999,
      padding: 3,
      position: 'relative',
    }}>
      {opts.map(o => {
        const active = o.id === value;
        const Icon = o.icon;
        return (
          <button key={o.id} onClick={() => onChange(o.id)}
            style={{
              appearance: 'none', cursor: 'pointer',
              background: active ? theme.surface : 'transparent',
              border: 'none',
              boxShadow: active ? '0 1px 2px rgba(31,21,21,0.08)' : 'none',
              borderRadius: 999,
              padding: '6px 14px 6px 11px',
              display: 'inline-flex', alignItems: 'center', gap: 5,
              color: active ? theme.text : theme.textSoft,
              fontSize: 12.5, fontWeight: 600, letterSpacing: -0.05,
              fontFamily: 'inherit',
              transition: 'all .15s ease',
            }}>
            <Icon color={active ? theme.text : theme.textSoft} />
            {o.label}
          </button>
        );
      })}
    </div>
  );
}
function ListIcon({ color }) {
  return (
    <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
      <path d="M3 4h2M3 8h2M3 12h2M7 4h7M7 8h7M7 12h7" stroke={color} strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  );
}
function HeartIcon({ color }) {
  return (
    <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
      <path d="M8 13.5s-5-3-5-7a3 3 0 0 1 5-2 3 3 0 0 1 5 2c0 4-5 7-5 7z" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
    </svg>
  );
}
function CalIcon({ color }) {
  return (
    <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
      <rect x="2" y="3.5" width="12" height="10.5" rx="2" stroke={color} strokeWidth="1.5"/>
      <path d="M2 6.5h12M5.5 2v3M10.5 2v3" stroke={color} strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  );
}

// Legacy alias for any callers still expecting TabBar
const TabBar = ViewSwitcher;

// ─────────────────────────────────────────────────────────────
// FAB — circular, abre el form completo de tarea (con pilar,
// hora, asignado, etc.) y se queda como atajo siempre alcanzable.
// ─────────────────────────────────────────────────────────────
function FAB({ onClick, theme, label = '+ Agregar tarea' }) {
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 50,
      display: 'flex', justifyContent: 'center', alignItems: 'center',
      gap: 10, zIndex: 30, pointerEvents: 'none',
    }}>
      <button onClick={onClick} style={{
        appearance: 'none', cursor: 'pointer', pointerEvents: 'auto',
        background: theme.primary, color: 'white',
        border: 'none', borderRadius: 28,
        padding: '13px 22px',
        fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
        fontFamily: 'inherit',
        boxShadow: `0 6px 18px ${theme.primary}55, 0 2px 4px ${theme.primary}33`,
        display: 'inline-flex', alignItems: 'center', gap: 4,
        transition: 'transform .15s ease',
      }}>{label}</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// QuickAdd — input inline al inicio de la lista. Es el camino
// principal para agregar tareas (1 toque, escribe, Enter o ✓).
// Crea tarea con defaults (hoy, sin hora, pilar = el filtrado o
// 'hijos', asignado = me). Para algo más detallado, está el FAB.
// ─────────────────────────────────────────────────────────────
function QuickAdd({ theme, pillarFilter, onCreate, onOpenFull }) {
  const [text, setText] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const inputRef = React.useRef(null);
  const submit = () => {
    const v = text.trim();
    if (!v) return;
    const pillar = (pillarFilter && pillarFilter !== 'all') ? pillarFilter : 'hijos';
    onCreate({
      id: 't' + Date.now(),
      title: v, date: todayISO(), time: null,
      pillar, who: 'me', done: false,
    });
    setText('');
    inputRef.current?.focus();
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      background: theme.surface,
      border: `1px solid ${focused ? theme.primaryBorder : theme.border}`,
      borderRadius: 14,
      padding: '4px 4px 4px 12px',
      transition: 'border-color .15s ease',
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 6,
        border: `1.5px dashed ${theme.primaryBorder}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: theme.primary, fontSize: 14, fontWeight: 400, lineHeight: 1,
        flexShrink: 0,
      }}>＋</div>
      <input ref={inputRef}
        value={text}
        onChange={(e) => setText(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
        placeholder="Agregar algo a hoy…"
        style={{
          flex: 1, minWidth: 0,
          background: 'transparent', border: 'none', outline: 'none',
          padding: '10px 0', fontSize: 14, fontWeight: 500,
          color: theme.text, fontFamily: 'inherit',
          letterSpacing: -0.1,
        }} />
      {text.trim() ? (
        <button onClick={submit}
          style={{
            appearance: 'none', cursor: 'pointer',
            background: theme.primary, color: 'white',
            border: 'none', borderRadius: 10,
            width: 34, height: 34,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'inherit', flexShrink: 0,
          }}>
          <svg width="14" height="14" 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>
      ) : (
        <button onClick={onOpenFull} aria-label="Más opciones"
          style={{
            appearance: 'none', cursor: 'pointer',
            background: 'transparent', border: 'none',
            color: theme.textSoft, fontSize: 11, fontWeight: 600,
            padding: '0 10px', height: 34,
            display: 'flex', alignItems: 'center', gap: 4,
            fontFamily: 'inherit', flexShrink: 0,
            letterSpacing: 0.2,
          }}>
          <svg width="13" height="13" viewBox="0 0 16 16">
            <path d="M4 6h8M5.5 9h5M7 12h2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
          Detalles
        </button>
      )}
    </div>
  );
}

Object.assign(window, {
  THEME, DENSITY,
  PillarTag, PillarPill, Checkbox, Avatar, AssigneeBadge,
  TaskCard, TabBar, ViewSwitcher, FAB, QuickAdd,
});
