// home.jsx — Three Home layout variants for MamaFlow
// Variants:
//   'classic' — per brief, single list of all tasks
//   'focus'   — hero "lo más importante" + collapsed rest
//   'time'    — grouped by morning / afternoon / evening

function PillarsBar({ filter, setFilter, theme, onEdit, onSeeBalance, balanceOpen }) {
  const ids = Object.keys(PILLARS);
  const allActive = filter === 'all';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      padding: '0 18px 2px',
    }}>
      <button onClick={() => setFilter('all')}
        title="Todo"
        style={{
          appearance: 'none', cursor: 'pointer', flexShrink: 0,
          height: 32, padding: '0 12px', borderRadius: 999,
          background: allActive ? theme.primary : 'transparent',
          color: allActive ? 'white' : theme.textSoft,
          border: `1px solid ${allActive ? theme.primary : theme.border}`,
          fontSize: 12, fontWeight: 600, letterSpacing: 0.1,
          fontFamily: 'inherit',
        }}>Todo</button>
      <div style={{
        display: 'flex', gap: 6, flex: 1,
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        {ids.map(id => {
          const p = PILLARS[id];
          const active = filter === id;
          return (
            <button key={id} onClick={() => setFilter(id)}
              title={p.label}
              style={{
                appearance: 'none', cursor: 'pointer', flexShrink: 0,
                width: 32, height: 32, borderRadius: 16,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: active ? p.bg : 'transparent',
                border: `1px solid ${active ? p.border : theme.border}`,
                fontSize: 15, padding: 0,
                opacity: active ? 1 : 0.65,
                fontFamily: 'inherit',
                transition: 'opacity .15s, background .15s',
              }}>{p.emoji}</button>
          );
        })}
      </div>
      <button onClick={onEdit}
        title="Editar pilares"
        style={{
          appearance: 'none', cursor: 'pointer', flexShrink: 0,
          width: 32, height: 32, borderRadius: 16,
          background: 'transparent', border: `1px dashed ${theme.border}`,
          color: theme.textSoft, fontSize: 14, padding: 0,
          fontFamily: 'inherit',
        }}>＋</button>
      {onSeeBalance && (
        <button onClick={onSeeBalance}
          title={balanceOpen ? 'Ocultar balance' : 'Ver balance'}
          aria-label="Balance"
          style={{
            appearance: 'none', cursor: 'pointer', flexShrink: 0,
            width: 32, height: 32, borderRadius: 16,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: balanceOpen ? theme.primarySoft : 'transparent',
            border: `1px ${balanceOpen ? 'solid' : 'dashed'} ${balanceOpen ? theme.primaryBorder : theme.border}`,
            color: balanceOpen ? theme.primary : theme.textSoft,
            padding: 0, fontFamily: 'inherit',
            transition: 'background .15s, color .15s, border-color .15s',
          }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <rect x="2.5" y="8.5"  width="2.5" height="5"   rx="0.6" fill="currentColor"/>
            <rect x="6.75" y="5.5"  width="2.5" height="8"   rx="0.6" fill="currentColor"/>
            <rect x="11"   y="2.5"  width="2.5" height="11"  rx="0.6" fill="currentColor"/>
          </svg>
        </button>
      )}
    </div>
  );
}

function SectionLabel({ children, theme, count }) {
  return (
    <div style={{
      padding: '0 18px', marginBottom: 8,
      display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
    }}>
      <div style={{
        fontSize: 10.5, fontWeight: 700, letterSpacing: 1.2,
        color: theme.textSoft, textTransform: 'uppercase',
      }}>{children}</div>
      {count != null && (
        <div style={{
          fontSize: 11, color: theme.textSoft, fontWeight: 500,
        }}>{count}</div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Classic layout
// ─────────────────────────────────────────────────────────────
function HomeClassic({ tasks, family, theme, density, mood, onToggle, onPostpone, onTaskClick, onAssigneeClick }) {
  const [showDone, setShowDone] = React.useState(false);
  const [showAll, setShowAll] = React.useState(false);
  const moodObj = MOODS.find(m => m.id === mood) || MOODS[1];
  const cap = moodObj.cap;
  const today = tasks.filter(t => t.date === todayISO());
  const todayPending = today.filter(t => !t.done);
  const todayDone = today.filter(t => t.done);
  // Mood cap: si pesado, fluyendo, etc., escondemos las que sobran.
  const capped = !showAll && todayPending.length > cap;
  const visible = capped ? todayPending.slice(0, cap) : todayPending;
  const hidden = capped ? todayPending.slice(cap) : [];
  const upcoming = tasks.filter(t => t.date > todayISO() && !t.done).slice(0, 4);
  // Tareas "viejas" para soltar (pendientes, hoy o antes, no completadas, sin marcar reciente)
  // Detectamos por id: las del seed son t1..t12. Usamos solo tareas con fecha <= hoy y no done; las > 3 días atrás serían candidatas, pero el seed solo cubre hoy/futuro. Como demo, marcamos como "vieja" la primera tarea de la lista si lleva varios días (proxy: id numérico bajo). Para una demo coherente, ofrecemos soltar manualmente desde detalle.
  const renderRow = (t) => (
    <SwipeableTaskCard key={t.id} task={t} family={family} theme={theme}
      density={density} onToggle={onToggle} onPostpone={onPostpone} onOpen={onTaskClick} onAssigneeClick={onAssigneeClick} />
  );
  return (
    <>
      {capped && (
        <div style={{
          margin: '0 18px 12px', padding: '12px 14px',
          background: theme.surface,
          border: `1px solid ${theme.primaryBorder}`,
          borderRadius: 14,
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 9,
            background: theme.primarySoft,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 14, flexShrink: 0,
          }}>{moodObj.emoji}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontSize: 13, fontWeight: 700, color: theme.text,
              letterSpacing: -0.1, marginBottom: 2,
            }}>Modo {moodObj.label.toLowerCase()} activo</div>
            <div style={{ fontSize: 11.5, color: theme.textSoft, lineHeight: 1.4 }}>
              {moodObj.cta} <span style={{ color: theme.primary, fontWeight: 600, cursor: 'pointer' }}
                onClick={() => setShowAll(true)}>Ver todo de todos modos</span>
            </div>
          </div>
        </div>
      )}
      <SectionLabel theme={theme} count={capped ? `mostrando ${cap} de ${todayPending.length}` : `${visible.length}`}>Hoy</SectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: DENSITY[density].gap, padding: '0 18px' }}>
        {visible.map(renderRow)}
        {todayPending.length === 0 && todayDone.length === 0 && (
          <EmptyState theme={theme} text="Nada pendiente hoy. Disfruta el día 🌸" />
        )}
      </div>
      {capped && (
        <div style={{ padding: '10px 18px 0', textAlign: 'center' }}>
          <button onClick={() => setShowAll(true)} style={{
            appearance: 'none', cursor: 'pointer',
            background: 'transparent', border: `1px dashed ${theme.border}`,
            color: theme.textSoft, fontSize: 12, fontWeight: 600,
            padding: '8px 14px', borderRadius: 999, fontFamily: 'inherit',
          }}>+ {hidden.length} más · Mostrar igual</button>
        </div>
      )}
      {todayDone.length > 0 && (
        <div style={{ padding: '12px 18px 0' }}>
          <button onClick={() => setShowDone(v => !v)}
            style={{
              appearance: 'none', cursor: 'pointer',
              background: 'transparent', border: 'none',
              padding: '6px 0', fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 6,
              color: theme.textSoft, fontSize: 12, fontWeight: 600,
              letterSpacing: 0.1,
            }}>
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 18, height: 18, borderRadius: 9,
              background: theme.primarySoft, color: theme.primary,
              fontSize: 11, fontWeight: 700,
            }}>{todayDone.length}</span>
            ✓ Ya hecho hoy
            <span style={{ marginLeft: 2, fontSize: 10 }}>{showDone ? '▴' : '▾'}</span>
          </button>
          {showDone && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: DENSITY[density].gap, marginTop: 10 }}>
              {todayDone.map(renderRow)}
            </div>
          )}
        </div>
      )}
      {upcoming.length > 0 && !capped && (
        <>
          <div style={{ height: 22 }} />
          <SectionLabel theme={theme}>Próximos días</SectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: DENSITY[density].gap, padding: '0 18px' }}>
            {upcoming.map(renderRow)}
          </div>
        </>
      )}
      <div style={{ padding: '14px 18px 0', fontSize: 10.5, color: theme.textSoft, textAlign: 'center', letterSpacing: 0.1 }}>
        Desliza ← lista · → a mañana · toca para soltar sin culpa
      </div>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// Focus layout — hero task + chips for rest
// ─────────────────────────────────────────────────────────────
function HomeFocus({ tasks, family, theme, density, onToggle, onPostpone, onTaskClick, onAssigneeClick }) {
  const today = tasks.filter(t => t.date === todayISO() && !t.done);
  const hero = today[0];
  const rest = today.slice(1);
  const member = hero && family.find(m => m.id === hero.who);
  const p = hero && PILLARS[hero.pillar];
  return (
    <>
      {hero ? (
        <div style={{ padding: '0 18px' }}>
          <SectionLabel theme={theme}>Lo más cercano</SectionLabel>
          <div onClick={() => onTaskClick(hero)} style={{
            background: theme.surface,
            border: `1.5px solid ${p.border}`,
            borderRadius: 18, padding: 18,
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', top: 0, right: 0,
              width: 90, height: 90, borderRadius: '50%',
              background: p.bg, opacity: 0.7,
              transform: 'translate(30%, -30%)',
            }}/>
            <div style={{ position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                <PillarTag pillarId={hero.pillar} size="md" />
                {hero.time && (
                  <div style={{
                    fontSize: 13, fontWeight: 700, color: theme.text,
                    fontVariantNumeric: 'tabular-nums',
                  }}>{fmtTime(hero.time)}</div>
                )}
              </div>
              <div style={{
                fontSize: 19, fontWeight: 700, color: theme.text,
                lineHeight: 1.25, letterSpacing: -0.3,
                marginBottom: 14,
              }}>{hero.title}</div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                {member && <AssigneeBadge member={member} theme={theme} />}
                <button onClick={(e) => { e.stopPropagation(); onToggle(hero.id); }}
                  style={{
                    appearance: 'none', cursor: 'pointer',
                    background: theme.primary, color: 'white',
                    border: 'none', borderRadius: 999,
                    padding: '7px 14px', fontSize: 12, fontWeight: 600,
                    fontFamily: 'inherit',
                  }}>✓ Lista</button>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <EmptyState theme={theme} text="Sin pendientes urgentes. Respira 🌸" />
      )}
      {rest.length > 0 && (
        <>
          <div style={{ height: 22 }} />
          <SectionLabel theme={theme} count={`${rest.length}`}>También hoy</SectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '0 18px' }}>
            {rest.map(t => (
              <SwipeableTaskCard key={t.id} task={t} family={family} theme={theme}
                density="compact" onToggle={onToggle} onPostpone={onPostpone} onOpen={onTaskClick} onAssigneeClick={onAssigneeClick} compact />
            ))}
          </div>
        </>
      )}
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// Time-grouped layout — Mañana / Tarde / Noche
// ─────────────────────────────────────────────────────────────
function HomeTime({ tasks, family, theme, density, onToggle, onPostpone, onTaskClick, onAssigneeClick }) {
  const today = tasks.filter(t => t.date === todayISO());
  const bucket = (t) => {
    if (!t.time) return 'sin';
    const h = parseInt(t.time.split(':')[0], 10);
    if (h < 12) return 'manana';
    if (h < 18) return 'tarde';
    return 'noche';
  };
  const groups = [
    { id: 'manana', label: 'Mañana', emoji: '🌅' },
    { id: 'tarde',  label: 'Tarde',  emoji: '☀️' },
    { id: 'noche',  label: 'Noche',  emoji: '🌙' },
    { id: 'sin',    label: 'Sin hora', emoji: '✦' },
  ];
  const grouped = groups.map(g => ({ ...g, items: today.filter(t => bucket(t) === g.id) })).filter(g => g.items.length);
  return (
    <>
      {grouped.map((g, gi) => (
        <React.Fragment key={g.id}>
          {gi > 0 && <div style={{ height: 18 }} />}
          <div style={{
            padding: '0 18px', marginBottom: 8,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ fontSize: 14 }}>{g.emoji}</span>
            <span style={{
              fontSize: 10.5, fontWeight: 700, letterSpacing: 1.2,
              color: theme.textSoft, textTransform: 'uppercase',
            }}>{g.label}</span>
            <div style={{ flex: 1, height: 1, background: theme.border }} />
            <span style={{ fontSize: 11, color: theme.textSoft, fontWeight: 500 }}>{g.items.length}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: DENSITY[density].gap, padding: '0 18px' }}>
            {g.items.map(t => (
              <SwipeableTaskCard key={t.id} task={t} family={family} theme={theme}
                density={density} onToggle={onToggle} onPostpone={onPostpone} onOpen={onTaskClick} onAssigneeClick={onAssigneeClick} />
            ))}
          </div>
        </React.Fragment>
      ))}
      {grouped.length === 0 && (
        <EmptyState theme={theme} text="Nada pendiente hoy 🌸" />
      )}
    </>
  );
}

function EmptyState({ theme, text }) {
  return (
    <div style={{
      padding: '20px 18px', textAlign: 'center',
      color: theme.textSoft, fontSize: 13,
      background: theme.surface, borderRadius: 12,
      border: `1px dashed ${theme.border}`,
      margin: '0 18px',
    }}>{text}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// Main Home wrapper
// ─────────────────────────────────────────────────────────────
function Home({ variant, tasks, family, profile, theme, density, mood, setMood,
                pillarFilter, setPillarFilter,
                tab, setTab,
                onToggle, onPostpone, onTaskClick, onEditPillars, onSettings,
                onQuickCreate, onAssigneeClick }) {
  const [balanceOpen, setBalanceOpen] = React.useState(false);
  const filtered = pillarFilter === 'all' ? tasks : tasks.filter(t => t.pillar === pillarFilter);
  const todayPending = tasks.filter(t => t.date === todayISO() && !t.done).length;
  const hour = new Date().getHours();
  const timeOfDay = hour < 6 ? 'night'
                  : hour < 12 ? 'morning'
                  : hour < 18 ? 'afternoon'
                  : hour < 22 ? 'evening'
                  : 'night';
  const headerBg = headerGradient(theme, false);
  const greeting = (() => {
    if (timeOfDay === 'morning') return 'Buenos días';
    if (timeOfDay === 'afternoon') return 'Buenas tardes';
    if (timeOfDay === 'evening') return 'Buenas noches';
    return 'Hola';
  })();
  const subline = (() => {
    const moodObj = MOODS.find(m => m.id === mood) || MOODS[1];
    if (timeOfDay === 'night') {
      return todayPending === 0 ? 'Día completo. Descansa 🌙' :
             'Lo no urgente se va con el día. Sin culpa.';
    }
    return moodObj.tagline;
  })();

  const HomeVariant = { classic: HomeClassic, focus: HomeFocus, time: HomeTime }[variant] || HomeClassic;

  // Pilar "Tú" sagrado: ¿cuántas tareas en pilar 'personal' hay hoy?
  const tuToday = tasks.filter(t => t.pillar === 'personal' && t.date === todayISO()).length;

  return (
    <div style={{ paddingBottom: 140 }}>
      {/* Header */}
      <div style={{
        background: headerBg, color: 'white',
        padding: '64px 18px 18px',
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
          marginBottom: 12,
        }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: 1.3,
            color: 'rgba(255,255,255,0.65)', marginTop: 4,
          }}>{fmtDateLong(todayISO())}</div>
          <button onClick={onSettings} style={{
            appearance: 'none', cursor: 'pointer',
            background: 'rgba(255,255,255,0.15)', border: 'none',
            width: 32, height: 32, borderRadius: 10,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'white',
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M12 15a3 3 0 100-6 3 3 0 000 6z" stroke="currentColor" strokeWidth="1.8"/>
              <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 008.91 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 8.91a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
        <div style={{
          fontSize: 24, fontWeight: 700, letterSpacing: -0.4,
          lineHeight: 1.15, marginBottom: 4,
        }}>{greeting}, {(profile && profile.name) || 'Valeria'} 👋</div>
        <div style={{
          fontSize: 13, color: 'rgba(255,255,255,0.78)', marginBottom: 16,
        }}>
          {subline}
        </div>
        {/* Mood se gestiona solo desde el check-in diario abajo;
            aquí no lo repetimos para no saturar. */}
      </div>

      {/* View switcher */}
      <div style={{ padding: '14px 18px 10px' }}>
        <ViewSwitcher value={tab} onChange={setTab} theme={theme} />
      </div>

      {/* QuickAdd + Pillars + Tasks */}
      <div style={{ padding: '0 0 0' }}>
        <DailyMoodCheckin theme={theme} currentMood={mood}
          onPick={(m) => setMood(m)} />
        <CelebrationBanner tasks={tasks} theme={theme} />
        <PillarsBar filter={pillarFilter} setFilter={setPillarFilter} theme={theme}
          onEdit={onEditPillars}
          onSeeBalance={() => setBalanceOpen(o => !o)}
          balanceOpen={balanceOpen} />
        {balanceOpen && pillarFilter === 'all' && (
          <div style={{ animation: 'mf-slide-up .25s ease-out' }}>
            <WeeklyBalance tasks={tasks} theme={theme} featured />
          </div>
        )}
        <div style={{ height: 10 }} />
        <HomeVariant tasks={filtered} family={family} theme={theme}
          density={density} mood={mood}
          onToggle={onToggle} onPostpone={onPostpone} onTaskClick={onTaskClick}
          onAssigneeClick={onAssigneeClick} />
      </div>

      {/* Pilar "Tú" sagrado — alerta si llevas días sin nada para ti */}
      {tuToday === 0 && pillarFilter === 'all' && (
        <div style={{
          margin: '18px 18px 0', padding: '14px 14px 14px 16px',
          background: 'linear-gradient(95deg, #F3EEFF 0%, #FAF5FF 100%)',
          border: '1px solid #CEBDFF', borderRadius: 16,
          display: 'flex', gap: 12, alignItems: 'flex-start',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 12,
            background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18, flexShrink: 0, border: '1px solid #CEBDFF',
          }}>💆‍♀️</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#5C2F9B', letterSpacing: -0.1 }}>
              Hoy no hay nada para ti
            </div>
            <div style={{ fontSize: 11.5, color: '#7A4DB5', marginTop: 2, lineHeight: 1.4 }}>
              El pilar Tú lleva días en cero. ¿Bloqueamos 20 min de algo solo tuyo?
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              <button onClick={() => onQuickCreate && onQuickCreate({
                id: 't' + Date.now(), title: 'Algo solo para ti (20 min)',
                date: todayISO(), time: null, pillar: 'personal', who: 'me', done: false,
              })} style={{
                appearance: 'none', cursor: 'pointer',
                background: '#7A4DB5', color: 'white', border: 'none',
                borderRadius: 10, padding: '8px 12px', fontSize: 12, fontWeight: 600,
                fontFamily: 'inherit',
              }}>Bloquear 20 min</button>
            </div>
          </div>
        </div>
      )}

      {/* Affirmation */}
      <div style={{
        textAlign: 'center', padding: '32px 24px 8px',
        fontSize: 12, color: theme.textSoft, lineHeight: 1.5,
      }}>
        <div style={{
          fontSize: 10, fontWeight: 700, letterSpacing: 2,
          color: theme.primary, marginBottom: 6,
        }}>· MENOS, SIN CULPA ·</div>
        <div style={{ fontStyle: 'italic' }}>
          No estamos para hacer más. Estamos para soltar lo que no toca.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Home, PillarsBar, SectionLabel, EmptyState });
