// App shell: sidebar (desktop) + bottom nav (mobile) + vues

// ── Sidebar (desktop uniquement) ─────────────────────

function Sidebar({ view, setView, items, openForm, user, onLogout, syncError }) {
  const userInfo = USERS[user] || { name: user, color: 'var(--terracotta)', avatar: (user||'?')[0].toUpperCase() };
  const today = TODAY;
  const todayCount  = itemsOnDate(items, today).filter(x => x.kind === 'task' && ['todo','progress'].includes(statusOn(x, today))).length;
  const overdue     = items.filter(x => x.kind === 'task' && (x.recurrence?.kind || 'none') === 'none' && isBefore(fromYmd(x.date), today) && !['done','cancelled'].includes(x.status)).length;
  const eventsCount = items.filter(x => x.kind !== 'task').length;

  const NavItem = ({ id, icon, label, badge, badgeColor }) => {
    const active = view === id;
    return (
      <button onClick={() => setView(id)} style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '10px 12px', borderRadius: 10,
        background: active ? 'var(--surface)' : 'transparent',
        border: `1px solid ${active ? 'var(--line)' : 'transparent'}`,
        color: active ? 'var(--ink)' : 'var(--ink-2)',
        boxShadow: active ? 'var(--shadow-sm)' : 'none',
        fontWeight: active ? 600 : 500, fontSize: 13.5,
        width: '100%', textAlign: 'left', transition: 'all .15s ease',
      }}
      onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-2)'; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
      >
        <Icon name={icon} size={16} color={active ? 'var(--terracotta)' : 'var(--ink-3)'} />
        <span className="grow">{label}</span>
        {badge != null && badge > 0 && (
          <span style={{
            background: badgeColor || 'var(--terracotta-tint)',
            color: badgeColor ? '#fff' : 'var(--terracotta-2)',
            padding: '2px 8px', borderRadius: 999,
            fontSize: 11, fontWeight: 600, minWidth: 22, textAlign: 'center',
          }}>{badge}</span>
        )}
      </button>
    );
  };

  return (
    <aside style={{
      borderRight: '1px solid var(--line)',
      background: 'var(--bg-2)',
      padding: '22px 18px',
      display: 'flex', flexDirection: 'column', gap: 22,
      position: 'sticky', top: 0, height: '100vh',
    }}>
      <div className="row gap-2" style={{ alignItems: 'center' }}>
        <div style={{
          width: 34, height: 34, borderRadius: 10,
          background: 'var(--terracotta)', color: '#FFF8F0',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontSize: 22, fontStyle: 'italic',
        }}>m</div>
        <div className="col" style={{ gap: 0 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, lineHeight: 1 }}>Maisonnée</div>
          <div className="tiny" style={{ marginTop: 2 }}>Baptiste & Imelda</div>
        </div>
      </div>

      <Button variant="primary" icon="plus" onClick={() => openForm()} style={{ justifyContent: 'center' }}>
        Nouvelle entrée
      </Button>

      <div className="col gap-1">
        <div className="tiny" style={{ padding: '0 12px 6px' }}>Espace</div>
        <NavItem id="dashboard" icon="sparkle"  label="Aujourd'hui"      badge={todayCount} />
        <NavItem id="calendar"  icon="calendar" label="Calendrier" />
        <NavItem id="tasks"     icon="list"     label="Toutes les tâches" />
      </div>

      <div className="col gap-1">
        <div className="tiny" style={{ padding: '0 12px 6px' }}>Repères</div>
        <NavItem id="overdue" icon="bell" label="En retard"   badge={overdue}     badgeColor={overdue > 0 ? 'var(--prio-high)' : null} />
        <NavItem id="events"  icon="cake" label="Événements"  badge={eventsCount} badgeColor="var(--event)" />
      </div>

      <div style={{ flex: 1 }} />

      {syncError && (
        <div style={{
          padding: '10px 12px', background: '#FDF2F2',
          border: '1px solid #F5C6C6', borderRadius: 12,
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 12, color: '#B23A2A',
        }}>
          <Icon name="bell" size={14} color="#B23A2A" />
          <span>Erreur de synchro</span>
        </div>
      )}

      <div style={{
        padding: '14px', background: 'var(--surface)',
        border: '1px solid var(--line)', borderRadius: 14,
      }}>
        <div className="row gap-3">
          <div style={{ width: 36, height: 36, borderRadius: 999, background: userInfo.color, color: '#FFF8F0', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontSize: 18 }}>{userInfo.avatar}</div>
          <div className="col grow" style={{ gap: 0, minWidth: 0 }}>
            <div className="truncate" style={{ fontWeight: 600, fontSize: 13 }}>{userInfo.name}</div>
            <div className="tiny" style={{ marginTop: 2 }}>connecté(e)</div>
          </div>
          <IconButton icon="back" label="Se déconnecter" onClick={onLogout} />
        </div>
      </div>
    </aside>
  );
}

// ── Bottom navigation (mobile uniquement) ─────────────

function BottomNav({ view, setView, items }) {
  const today = TODAY;
  const todayCount  = itemsOnDate(items, today).filter(x => x.kind === 'task' && ['todo','progress'].includes(statusOn(x, today))).length;
  const overdueCount = items.filter(x => x.kind === 'task' && (x.recurrence?.kind || 'none') === 'none' && isBefore(fromYmd(x.date), today) && !['done','cancelled'].includes(x.status)).length;
  const eventsCount = items.filter(x => x.kind !== 'task').length;

  const tabs = [
    { id: 'dashboard', icon: 'sparkle',  label: 'Accueil',    badge: todayCount,    badgeColor: 'var(--terracotta)' },
    { id: 'calendar',  icon: 'calendar', label: 'Calendrier' },
    { id: 'tasks',     icon: 'list',     label: 'Tâches' },
    { id: 'overdue',   icon: 'bell',     label: 'En retard',  badge: overdueCount,  badgeColor: 'var(--prio-high)' },
    { id: 'events',    icon: 'cake',     label: 'Événements', badge: eventsCount,   badgeColor: 'var(--event)' },
  ];

  return (
    <nav className="bottom-nav">
      {tabs.map(tab => {
        const active = view === tab.id;
        return (
          <button key={tab.id} className={'bottom-tab' + (active ? ' active' : '')} onClick={() => setView(tab.id)}>
            {tab.badge > 0 && (
              <span className="bottom-badge" style={{ background: tab.badgeColor || 'var(--terracotta)' }}>
                {tab.badge > 9 ? '9+' : tab.badge}
              </span>
            )}
            <Icon name={tab.icon} size={22} color={active ? 'var(--terracotta)' : 'var(--ink-3)'} strokeWidth={active ? 2 : 1.5} />
            <span className="bottom-tab-label">{tab.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ── App principal ─────────────────────────────────────

function App() {
  const { user, login, logout, loading } = useAuthSB();
  const { items, upsert, remove, setStatusOn, syncError, reload } = useStoreSB();
  const [view,     setView]     = React.useState('dashboard');
  const [formOpen, setFormOpen] = React.useState(false);
  const [editing,  setEditing]  = React.useState(null);

  const openForm = (initial) => { setEditing(initial || null); setFormOpen(true); };
  const onEdit   = (item)    => { setEditing(item);            setFormOpen(true); };

  // Recharge les items dès que l'utilisateur est connecté
  React.useEffect(() => {
    if (user) reload();
  }, [user]);

  const handleLogin = async (key) => {
    await login(key);
  };

  if (loading) return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-3)', fontFamily: 'var(--font-display)', fontSize: 22 }}>
      Chargement…
    </div>
  );
  if (!user) return <LoginScreen onLogin={handleLogin} />;

  const overdueItems = items.filter(x =>
    x.kind === 'task' &&
    (x.recurrence?.kind || 'none') === 'none' &&
    isBefore(fromYmd(x.date), TODAY) &&
    !['done','cancelled'].includes(x.status)
  );

  return (
    <div className="app">
      <main style={{ overflowX: 'hidden' }}>
        {view === 'dashboard' && <DashboardView items={items} openForm={openForm} onStatusChange={setStatusOn} onEdit={onEdit} navigate={setView} user={user} />}
        {view === 'calendar'  && <CalendarView  items={items} openForm={openForm} onStatusChange={setStatusOn} onEdit={onEdit} />}
        {view === 'tasks'     && <TasksView     items={items} openForm={openForm} onStatusChange={setStatusOn} onEdit={onEdit} />}
        {view === 'overdue'   && <OverdueView   items={overdueItems} onStatusChange={setStatusOn} onEdit={onEdit} openForm={openForm} />}
        {view === 'events'    && <EventsView    items={items} onStatusChange={setStatusOn} onEdit={onEdit} openForm={openForm} />}
      </main>

      <BottomNav view={view} setView={setView} items={items} />
      <button className="fab" onClick={() => openForm()} aria-label="Nouvelle entrée">
        <Icon name="plus" size={24} color="#FFF8F0" strokeWidth={2} />
      </button>

      {syncError && (
        <div style={{
          position: 'fixed', bottom: 76, left: 16, right: 16,
          background: '#FDF2F2', border: '1px solid #F5C6C6',
          borderRadius: 12, padding: '10px 14px',
          zIndex: 150,
          display: 'flex', alignItems: 'flex-start', gap: 8,
        }}>
          <Icon name="bell" size={14} color="#B23A2A" style={{ flexShrink: 0, marginTop: 1 }} />
          <span style={{ fontSize: 12, color: '#B23A2A', wordBreak: 'break-all' }}>Erreur de synchro : {syncError}</span>
        </div>
      )}

      <Modal open={formOpen} onClose={() => setFormOpen(false)}>
        <TaskForm
          initial={editing}
          onSave={upsert}
          onDelete={remove}
          onClose={() => setFormOpen(false)}
        />
      </Modal>
    </div>
  );
}

// ── Vues secondaires ──────────────────────────────────

function OverdueView({ items, onStatusChange, onEdit, openForm }) {
  const sorted = [...items].sort((a, b) => a.date.localeCompare(b.date));
  return (
    <div className="col gap-5 view-pad" style={{ maxWidth: 1100, margin: '0 auto' }}>
      <SectionHeading eyebrow="À rattraper" title="Tâches en retard" count={sorted.length} />
      {sorted.length === 0 ? (
        <Empty icon="check" title="Tout est à jour" hint="Aucune tâche n'est en retard." />
      ) : (
        <div className="col gap-2">
          {sorted.map(it => <TaskRow key={it.id} item={it} date={fromYmd(it.date)} onStatusChange={onStatusChange} onEdit={onEdit} />)}
        </div>
      )}
    </div>
  );
}

function EventsView({ items, onStatusChange, onEdit, openForm }) {
  const events = items.filter(x => x.kind !== 'task');
  const today  = TODAY;
  const occ    = events.map(it => ({ item: it, date: fromYmd(it.date) })).sort((a, b) => a.date - b.date);
  const upcoming = occ.filter(({ date }) => !isBefore(date, today));
  const past     = occ.filter(({ date }) =>  isBefore(date, today));

  const Section = ({ title, list }) => (
    <div className="col gap-3">
      <SectionHeading eyebrow={title} title={title === 'À venir' ? 'À venir' : 'Passés'} count={list.length} />
      {list.length === 0
        ? <div className="muted small" style={{ padding: 16 }}>Aucun événement</div>
        : <div className="col gap-2">{list.map(({ item, date }) => <TaskRow key={item.id} item={item} date={date} onStatusChange={onStatusChange} onEdit={onEdit} />)}</div>
      }
    </div>
  );

  return (
    <div className="col gap-6 view-pad" style={{ maxWidth: 1100, margin: '0 auto' }}>
      <SectionHeading
        eyebrow="Vie de famille" title="Événements" count={events.length}
        action={<Button variant="primary" icon="plus" onClick={() => openForm({ kind: 'appointment' })}>Nouvel événement</Button>}
      />
      <Section title="À venir" list={upcoming} />
      <Section title="Passés"  list={past} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
