// task-extras.jsx — Swipe gestures, Task detail, Activity feed, Celebration

// ─────────────────────────────────────────────────────────────
// SwipeableTaskCard — wraps TaskCard with swipe actions
//   Swipe LEFT  → complete (rosa) / undo if already done
//   Swipe RIGHT → postpone 1 day (azul)
// Tap → open detail
// ─────────────────────────────────────────────────────────────
function SwipeableTaskCard({ task, family, theme, density, onToggle, onPostpone, onOpen, onAssigneeClick, compact }) {
  const [dx, setDx] = React.useState(0);
  const [released, setReleased] = React.useState(false);
  const startRef = React.useRef(null);
  const movedRef = React.useRef(false);

  const onDown = (clientX) => {
    startRef.current = clientX;
    movedRef.current = false;
    setReleased(false);
  };
  const onMove = (clientX) => {
    if (startRef.current == null) return;
    const delta = clientX - startRef.current;
    if (Math.abs(delta) > 6) movedRef.current = true;
    setDx(Math.max(-140, Math.min(140, delta)));
  };
  const onUp = () => {
    const moved = movedRef.current;
    const threshold = 70;
    if (dx <= -threshold) {
      setReleased(true);
      setDx(-380);
      setTimeout(() => { onToggle(task.id); setDx(0); setReleased(false); }, 200);
    } else if (dx >= threshold) {
      setReleased(true);
      setDx(380);
      setTimeout(() => { onPostpone(task.id); setDx(0); setReleased(false); }, 200);
    } else {
      setDx(0);
      if (!moved && onOpen) onOpen(task);
    }
    startRef.current = null;
  };

  const ttX = (e) => e.touches ? e.touches[0].clientX : e.clientX;

  return (
    <div style={{ position: 'relative', overflow: 'hidden', borderRadius: 14 }}>
      {/* Action backgrounds */}
      <div style={{
        position: 'absolute', inset: 0,
        background: dx < 0 ? theme.primary : dx > 0 ? '#4A5FD5' : 'transparent',
        borderRadius: 14,
        display: 'flex', alignItems: 'center',
        justifyContent: dx < 0 ? 'flex-end' : 'flex-start',
        padding: '0 22px', color: 'white', fontWeight: 700,
        fontSize: 13, letterSpacing: -0.1,
        opacity: Math.min(1, Math.abs(dx) / 70),
      }}>
        {dx < 0 ? (task.done ? '↩ Reabrir' : '✓ Lista') : '↪ Mañana'}
      </div>
      <div
        style={{
          transform: `translateX(${dx}px)`,
          transition: released ? 'transform .2s ease' : (startRef.current ? 'none' : 'transform .2s ease'),
          touchAction: 'pan-y',
        }}
        onMouseDown={(e) => onDown(e.clientX)}
        onMouseMove={(e) => startRef.current != null && onMove(e.clientX)}
        onMouseUp={onUp}
        onMouseLeave={() => startRef.current != null && onUp()}
        onTouchStart={(e) => onDown(ttX(e))}
        onTouchMove={(e) => onMove(ttX(e))}
        onTouchEnd={onUp}
      >
        <TaskCard task={task} family={family} theme={theme} density={density}
          onToggle={onToggle} onAssigneeClick={onAssigneeClick} compact={compact} />
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TaskDetailSheet — view, edit, postpone, delete
// ─────────────────────────────────────────────────────────────
function TaskDetailSheet({ task, family, theme, onClose, onSave, onDelete, onPostpone, onToggle }) {
  const open = !!task;
  const [draft, setDraft] = React.useState(task);
  React.useEffect(() => { if (task) setDraft(task); }, [task]);

  if (!draft) return <Sheet open={false} onClose={onClose} theme={theme} />;

  const member = family.find(m => m.id === draft.who);
  const update = (patch) => setDraft({ ...draft, ...patch });
  const save = () => { onSave(draft); 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="Tarea" maxHeight="88%">
      <div style={{ padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <input value={draft.title} onChange={(e) => update({ title: e.target.value })}
          style={{
            width: '100%', boxSizing: 'border-box',
            background: theme.bg, border: `1px solid ${theme.border}`,
            borderRadius: 12, padding: '13px 14px',
            fontSize: 15, fontWeight: 600, color: theme.text,
            fontFamily: 'inherit', outline: 'none', letterSpacing: -0.1,
          }} />

        <div>
          <FieldLabel>Descripción</FieldLabel>
          <textarea
            value={draft.description || ''}
            onChange={(e) => update({ description: e.target.value })}
            placeholder="Notas, contexto, lo que necesitas recordar…"
            rows={3}
            style={{
              width: '100%', boxSizing: 'border-box',
              background: theme.bg, border: `1px solid ${theme.border}`,
              borderRadius: 12, padding: '12px 14px',
              fontSize: 13.5, color: theme.text,
              fontFamily: 'inherit', outline: 'none', resize: 'vertical',
              lineHeight: 1.45, letterSpacing: -0.05, minHeight: 72,
            }} />
          <div style={{ marginTop: 8 }}>
            <PhotoAttachField value={draft.photo || null}
              onChange={(p) => update({ photo: p || undefined })} theme={theme} />
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 10 }}>
          <div>
            <FieldLabel>Fecha</FieldLabel>
            <input type="date" value={draft.date} onChange={(e) => update({ date: e.target.value })}
              style={fieldStyle(theme)} />
          </div>
          <div>
            <FieldLabel>Hora</FieldLabel>
            <input type="time" value={draft.time || ''} onChange={(e) => update({ time: e.target.value || null })}
              style={fieldStyle(theme)} />
          </div>
        </div>

        <div>
          <FieldLabel>¿Quién lo hace?</FieldLabel>
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto' }}>
            {family.map(m => {
              const active = m.id === draft.who;
              return (
                <button key={m.id} onClick={() => update({ who: m.id })}
                  style={{
                    appearance: 'none', cursor: 'pointer', flexShrink: 0,
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5,
                    background: 'transparent', border: 'none', padding: 4,
                    fontFamily: 'inherit',
                  }}>
                  <Avatar member={m} size={38} showRing={active} />
                  <div style={{ fontSize: 11, fontWeight: active ? 700 : 500, color: active ? theme.text : theme.textSoft }}>{m.name}</div>
                </button>
              );
            })}
          </div>
        </div>

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

        <div>
          <FieldLabel>Se repite</FieldLabel>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[
              { id: null,        label: 'No' },
              { id: 'daily',     label: 'Cada día' },
              { id: 'weekdays',  label: 'L-V' },
              { id: 'weekly',    label: 'Semanal' },
            ].map(o => {
              const active = (draft.repeat || null) === o.id;
              return (
                <button key={String(o.id)} onClick={() => update({ repeat: o.id })}
                  style={{
                    appearance: 'none', cursor: 'pointer',
                    padding: '7px 12px', borderRadius: 999,
                    background: active ? theme.primarySoft : 'transparent',
                    color: active ? theme.primary : theme.textSoft,
                    border: `1px solid ${active ? theme.primaryBorder : theme.border}`,
                    fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
                  }}>{o.label}</button>
              );
            })}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => { onPostpone(draft.id); onClose(); }}
            style={actionBtn(theme, 'secondary')}>↪ Mañana</button>
          <button onClick={() => { onToggle(draft.id); onClose(); }}
            style={actionBtn(theme, 'secondary')}>{draft.done ? '↩ Reabrir' : '✓ Lista'}</button>
          <button onClick={() => { onDelete(draft.id); onClose(); }}
            style={{ ...actionBtn(theme, 'danger'), flex: '0 0 auto', padding: '11px 14px' }}>🗑</button>
        </div>

        <button onClick={save}
          style={{
            appearance: 'none', cursor: 'pointer',
            background: theme.primary, color: 'white',
            border: 'none', borderRadius: 14, padding: '13px',
            fontSize: 14.5, fontWeight: 700, fontFamily: 'inherit',
            letterSpacing: -0.1,
          }}>Guardar cambios</button>
      </div>
    </Sheet>
  );
}
function actionBtn(theme, kind) {
  const base = {
    appearance: 'none', cursor: 'pointer', flex: 1,
    border: `1px solid ${theme.border}`, borderRadius: 12,
    padding: '11px', fontSize: 13, fontWeight: 600,
    fontFamily: 'inherit', letterSpacing: -0.05,
  };
  if (kind === 'danger') return { ...base, background: theme.bg, color: '#C9626B', border: `1px solid ${theme.primaryBorder}` };
  return { ...base, background: theme.bg, color: theme.text };
}

// ─────────────────────────────────────────────────────────────
// ActivityToast — slides down from top: "Papá completó: leche"
// ─────────────────────────────────────────────────────────────
function ActivityToast({ event, theme, onDismiss }) {
  React.useEffect(() => {
    if (!event) return;
    const id = setTimeout(onDismiss, 3500);
    return () => clearTimeout(id);
  }, [event, onDismiss]);
  return (
    <div style={{
      position: 'absolute', top: 58, left: 16, right: 16, zIndex: 80,
      transform: event ? 'translateY(0)' : 'translateY(-160%)',
      opacity: event ? 1 : 0,
      transition: 'transform .35s cubic-bezier(.3,.7,.4,1), opacity .25s',
      background: theme.surface,
      border: `1px solid ${theme.border}`,
      borderRadius: 14,
      padding: '10px 12px',
      display: 'flex', alignItems: 'center', gap: 10,
      boxShadow: '0 8px 28px rgba(0,0,0,0.12)',
      pointerEvents: event ? 'auto' : 'none',
    }}>
      {event && <Avatar member={event.member} size={30} />}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: theme.textSoft, lineHeight: 1.2 }}>{event?.member?.name} completó</div>
        <div style={{ fontSize: 13, fontWeight: 600, color: theme.text, letterSpacing: -0.05, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{event?.title}</div>
      </div>
      <span style={{ fontSize: 18 }}>🌸</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CelebrationBanner — shows when all today's tasks are done,
// or as a progress bar when partial.
// ─────────────────────────────────────────────────────────────
function CelebrationBanner({ tasks, theme }) {
  const today = tasks.filter(t => t.date === todayISO());
  if (today.length === 0) return null;
  const done = today.filter(t => t.done).length;
  const pct = Math.round((done / today.length) * 100);
  const allDone = done === today.length;
  return (
    <div style={{
      margin: '0 18px 14px',
      background: allDone ? '#FFF0F5' : theme.surface,
      border: `1px solid ${allDone ? '#FFB8CC' : theme.border}`,
      borderRadius: 14,
      padding: allDone ? '14px 16px' : '12px 14px',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: allDone ? theme.primary : theme.primarySoft,
        color: allDone ? 'white' : theme.primary,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 18, flexShrink: 0,
        border: allDone ? 'none' : `1px solid ${theme.primaryBorder}`,
      }}>{allDone ? '🌸' : pct >= 50 ? '✨' : '💛'}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: theme.text, letterSpacing: -0.1 }}>
          {allDone ? '¡Terminaste el día!' : `${done} de ${today.length} hoy`}
        </div>
        <div style={{
          marginTop: 4, height: 4, borderRadius: 2,
          background: allDone ? 'rgba(201,98,107,0.2)' : theme.borderSoft,
          overflow: 'hidden',
        }}>
          <div style={{
            width: `${pct}%`, height: '100%',
            background: theme.primary,
            transition: 'width .4s ease',
          }} />
        </div>
        <div style={{ fontSize: 11.5, color: theme.textSoft, marginTop: 5, lineHeight: 1.3 }}>
          {allDone ? 'Te mereces respirar. Estás haciendo un trabajo increíble 🌸' :
           done === 0 ? 'Empieza por la más sencilla. Sin presión.' :
           pct >= 75 ? 'Ya casi. Lo estás haciendo súper bien.' :
           pct >= 50 ? 'Vas a buen ritmo.' :
           'Una a la vez. Cuenta cada paso.'}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PillarSummary — chips with task counts when filter is 'all'
// ─────────────────────────────────────────────────────────────
function PillarSummary({ tasks, theme }) {
  const today = tasks.filter(t => t.date === todayISO() && !t.done);
  const counts = {};
  today.forEach(t => { counts[t.pillar] = (counts[t.pillar] || 0) + 1; });
  const entries = Object.entries(counts);
  if (entries.length === 0) return null;
  return (
    <div style={{
      display: 'flex', gap: 6, padding: '0 18px 12px',
      overflowX: 'auto', scrollbarWidth: 'none',
    }}>
      {entries.map(([pid, n]) => {
        const p = PILLARS[pid];
        return (
          <div key={pid} style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            background: p.bg, border: `1px solid ${p.border}`,
            borderRadius: 999, padding: '4px 11px 4px 8px',
            flexShrink: 0,
          }}>
            <span style={{ fontSize: 13 }}>{p.emoji}</span>
            <span style={{ fontSize: 12, fontWeight: 700, color: p.text }}>{n}</span>
            <span style={{ fontSize: 11, color: p.text, opacity: 0.7 }}>{p.label.toLowerCase()}</span>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, {
  SwipeableTaskCard, TaskDetailSheet, ActivityToast, CelebrationBanner, PillarSummary,
});
