// Tempo — Routines page (manage habits + agenda)

// Suivi d'une habitude dans le temps : 7 derniers jours (points verts = fait) + série en cours.
// Rend le geste quotidien « traçable » directement là où l'utilisateur coche.
function HabitTrack({ id, recentDays, habitDoneOn, streak }) {
  if (!recentDays || !habitDoneOn) return null;
  const todayIdx = recentDays.length - 1;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexShrink: 0 }}>
      <div style={{ display: 'flex', gap: 3 }} title="7 derniers jours (vert = fait)">
        {recentDays.map((d, i) => {
          const done = habitDoneOn(id, d);
          const isToday = i === todayIdx;
          return (
            <span key={i} style={{
              width: 8, height: 8, borderRadius: '50%',
              background: done ? 'var(--green)' : 'var(--bg-elev)',
              border: done ? 'none' : '1px solid ' + (isToday ? 'var(--blue-border)' : 'var(--line)'),
            }}/>
          );
        })}
      </div>
      {streak > 0 && (
        <span title={`Série en cours : ${streak} jour${streak > 1 ? 's' : ''}`} style={{
          fontSize: 11, fontWeight: 700, color: 'var(--green-text)', background: 'var(--green-soft)',
          borderRadius: 6, padding: '2px 7px', whiteSpace: 'nowrap',
        }}>{streak} j</span>
      )}
    </div>
  );
}

function RoutinesPage({ state }) {
  const { habitsAll, addHabit, removeHabit, renameHabit, toggleHabit,
          recentDays, habitDoneOn, habitStreak,
          agenda, addAgenda, removeAgenda, toggleAgenda, loading } = state;
  const habits = habitsAll || state.habits; // graceful fallback
  const [newHabit, setNewHabit] = React.useState({ matin: '', journee: '', soir: '', pretrade: '' });
  const [newAgenda, setNewAgenda] = React.useState({ h: '14:30', e: '', tag: '' });
  const [errorMsg, setErrorMsg] = React.useState('');

  const submitHabit = async (sec) => {
    const name = (newHabit[sec] || '').trim();
    if (!name) return;
    setNewHabit({ ...newHabit, [sec]: '' });
    setErrorMsg('');
    const res = await addHabit(sec, name);
    if (res && res.error) setErrorMsg('Erreur: ' + (res.error.message || 'impossible d\'ajouter l\'habitude'));
  };

  const submitAgenda = async () => {
    if (!newAgenda.e || !newAgenda.e.trim()) return;
    setErrorMsg('');
    const res = await addAgenda(newAgenda);
    if (res && res.error) { setErrorMsg('Erreur: ' + (res.error.message || 'impossible d\'ajouter l\'événement')); return; }
    setNewAgenda({ h: '14:30', e: '', tag: '' });
  };

  return (
    <div className="scroll" style={{ width: '100%', height: '100%', overflow: 'auto' }}>
      <PageHeader title="Routines"/>
      <div style={{ padding: '20px 24px 40px', maxWidth: 1080 }}>
        <div style={{ marginBottom: 18 }}>
          <h2 style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-.02em', margin: 0, color: 'var(--fg)' }}>Habitudes &amp; agenda</h2>
          <p style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 6 }}>Ces éléments apparaissent sur ton Accueil. Modifie-les ici pour que ton dashboard se mette à jour.</p>
          {errorMsg && (
            <div style={{ marginTop: 10, padding: '8px 12px', borderRadius: 8, background: 'var(--red-soft)', color: 'var(--red-text)', fontSize: 12.5, border: '1px solid var(--line)' }}>{errorMsg}</div>
          )}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 16 }}>

          {/* Habits + Pré-trade */}
          <div className="card" style={{ padding: '22px 24px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
              <span style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-.01em' }}>Habitudes &amp; pré-trade</span>
              <span style={{ fontSize: 11.5, color: 'var(--fg-2)' }}>
                {habits.reduce((s, g) => s + g.items.filter(i => i.d).length, 0)} / {habits.reduce((s, g) => s + g.items.length, 0)}
              </span>
            </div>
            {loading && habits.every(g => g.items.length === 0) && (
              <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '10px 0' }}>Chargement…</div>
            )}
            {habits.map((g, gi) => (
              <div key={g.sec || g.g} style={{ marginBottom: gi < habits.length - 1 ? 18 : 0 }}>
                <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '.08em', color: 'var(--fg-3)', textTransform: 'uppercase', marginBottom: 10 }}>{g.g}</div>
                {g.items.map(it => (
                  <div key={it.id} style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
                    borderRadius: 8, transition: 'background .15s var(--ease)',
                  }} onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
                     onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <div onClick={() => toggleHabit(it.id)} className="tap" style={{
                      width: 18, height: 18, borderRadius: 5, flexShrink: 0,
                      border: '1.5px solid ' + (it.d ? 'var(--blue)' : 'var(--line-2)'),
                      background: it.d ? 'var(--blue)' : 'var(--bg-card)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: '#fff', cursor: 'pointer',
                    }}>{it.d && Ico.check}</div>
                    <input
                      value={it.t}
                      onChange={e => renameHabit(it.id, e.target.value)}
                      style={{
                        flex: 1, background: 'transparent', border: 'none', outline: 'none',
                        fontSize: 13.5, color: it.d ? 'var(--fg-3)' : 'var(--fg)',
                        textDecoration: it.d ? 'line-through' : 'none',
                        fontFamily: 'inherit', padding: 0, letterSpacing: '-.005em',
                      }}/>
                    <HabitTrack id={it.id} recentDays={recentDays} habitDoneOn={habitDoneOn}
                      streak={habitStreak ? habitStreak(it.id) : 0}/>
                    <button onClick={() => removeHabit(it.id)} className="tap" style={{
                      width: 22, height: 22, borderRadius: 6, border: 'none',
                      background: 'transparent', cursor: 'pointer', color: 'var(--fg-3)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: .6,
                    }} title="Supprimer">{Ico.x}</button>
                  </div>
                ))}
                {/* Add row */}
                <form onSubmit={e => { e.preventDefault(); submitHabit(g.sec); }} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', marginTop: 4,
                  border: '1.5px dashed var(--line-2)', borderRadius: 8, background: 'var(--bg-soft)',
                }}>
                  <span style={{ width: 18, height: 18, borderRadius: 5, border: '1.5px dashed var(--line-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-3)' }}>{Ico.plus}</span>
                  <input
                    value={newHabit[g.sec] || ''}
                    onChange={e => setNewHabit({ ...newHabit, [g.sec]: e.target.value })}
                    placeholder={`Nouvelle habitude · ${g.g}`}
                    style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', fontSize: 13, color: 'var(--fg)', fontFamily: 'inherit' }}/>
                  <button type="submit" disabled={!newHabit[g.sec]} className="tap" style={{
                    background: newHabit[g.sec] ? 'var(--blue)' : 'transparent',
                    color: newHabit[g.sec] ? '#fff' : 'var(--fg-3)',
                    border: 'none', borderRadius: 6, padding: '4px 11px',
                    fontSize: 11, fontWeight: 600, cursor: newHabit[g.sec] ? 'pointer' : 'default',
                    fontFamily: 'inherit',
                  }}>Ajouter</button>
                </form>
              </div>
            ))}
          </div>

          {/* Agenda */}
          <div className="card" style={{ padding: '22px 24px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
              <span style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-.01em' }}>Agenda du jour</span>
              <span style={{ fontSize: 11.5, color: 'var(--fg-2)' }}>{agenda.length} événements</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 14 }}>
              {agenda.length === 0 && (
                <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '8px 10px' }}>Aucun événement aujourd'hui — ajoute-en ci-dessous.</div>
              )}
              {agenda.map(e => (
                <div key={e.id} style={{
                  display: 'grid', gridTemplateColumns: '20px 56px 1fr 80px 22px',
                  alignItems: 'center', gap: 10, padding: '8px 10px',
                  borderRadius: 8, transition: 'background .15s var(--ease)',
                }} onMouseEnter={ev => ev.currentTarget.style.background = 'var(--bg-soft)'}
                   onMouseLeave={ev => ev.currentTarget.style.background = 'transparent'}>
                  <div onClick={() => toggleAgenda(e.id)} className="tap" style={{
                    width: 16, height: 16, borderRadius: 5, flexShrink: 0,
                    border: '1.5px solid ' + (e.done ? 'var(--blue)' : 'var(--line-2)'),
                    background: e.done ? 'var(--blue)' : 'var(--bg-card)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#fff', cursor: 'pointer',
                  }}>{e.done && Ico.check}</div>
                  <span className="mono" style={{ fontSize: 11.5, color: 'var(--fg-2)', fontWeight: 500 }}>{e.h}</span>
                  <span style={{ fontSize: 13, color: e.done ? 'var(--fg-3)' : 'var(--fg)', textDecoration: e.done ? 'line-through' : 'none' }}>{e.e}</span>
                  <span style={{ fontSize: 10.5, color: 'var(--fg-2)', fontWeight: 500, padding: '2px 8px', borderRadius: 4, background: e.tag ? 'var(--bg-elev)' : 'transparent', textAlign: 'center' }}>{e.tag || ''}</span>
                  <button onClick={() => removeAgenda(e.id)} className="tap" style={{
                    width: 22, height: 22, borderRadius: 6, border: 'none',
                    background: 'transparent', cursor: 'pointer', color: 'var(--fg-3)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: .6,
                  }}>{Ico.x}</button>
                </div>
              ))}
            </div>

            {/* Add agenda */}
            <form onSubmit={ev => { ev.preventDefault(); submitAgenda(); }} style={{
              padding: '12px 14px', border: '1.5px dashed var(--line-2)', borderRadius: 10, background: 'var(--bg-soft)',
              display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr 100px', gap: 8 }}>
                <input className="input" type="time" value={newAgenda.h} onChange={ev => setNewAgenda({ ...newAgenda, h: ev.target.value })} style={{ padding: '7px 10px', fontSize: 12.5 }}/>
                <input className="input" placeholder="Événement…" value={newAgenda.e} onChange={ev => setNewAgenda({ ...newAgenda, e: ev.target.value })} style={{ padding: '7px 10px', fontSize: 12.5 }}/>
                <select className="input" value={newAgenda.tag} onChange={ev => setNewAgenda({ ...newAgenda, tag: ev.target.value })} style={{ padding: '7px 10px', fontSize: 12.5, fontFamily: 'inherit' }}>
                  <option value="">Aucun tag</option>
                  <option value="Trading">Trading</option>
                  <option value="News">News</option>
                  <option value="Perso">Perso</option>
                </select>
              </div>
              <button type="submit" disabled={!newAgenda.e} className="btn btn-blue tap" style={{ justifyContent: 'center', opacity: newAgenda.e ? 1 : .5 }}>
                {Ico.plus} Ajouter à l'agenda
              </button>
            </form>
          </div>
        </div>

        {/* Tip */}
        <div style={{ marginTop: 18, padding: '14px 16px', background: 'var(--blue-soft)', border: '1px solid var(--blue-border)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 28, height: 28, borderRadius: 8, background: '#fff', color: 'var(--blue-600)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{Ico.bell}</div>
          <div style={{ fontSize: 12.5, color: 'var(--fg)', letterSpacing: '-.005em' }}>
            Tu peux modifier ces routines à tout moment — elles se synchronisent automatiquement avec ta page <b>Accueil</b> et tes journaux quotidiens.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RoutinesPage });
