// Habits screen — streaks, calendar grid, IA insights

const HabitsScreen = ({ state, setState, navigate, showToast }) => {
  const { habits } = state;
  const [selected, setSelected] = React.useState(null);
  const [showNew, setShowNew] = React.useState(false);
  const totalStreak = Math.max(...habits.map(h => h.streak));
  const done = habits.filter(h => h.done).length;

  const toggleHabit = (id) => {
    setState(s => ({ ...s, habits: s.habits.map(h => h.id === id ? { ...h, done: !h.done, current: h.done ? Math.max(0, h.current - 1) : Math.min(h.target, h.current + 1) } : h) }));
    showToast('Hábito marcado');
  };

  // Intent: abrir modal de novo hábito via evento global
  React.useEffect(() => {
    const handler = () => setShowNew(true);
    window.addEventListener('cdv:open-new-habit', handler);
    return () => window.removeEventListener('cdv:open-new-habit', handler);
  }, []);

  if (selected) {
    return <HabitDetail habit={habits.find(h => h.id === selected)} onBack={() => setSelected(null)} onToggle={toggleHabit} />;
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Hábitos" subtitle="CONSTRUINDO ROTINA" right={
        <button onClick={() => setShowNew(true)} style={{
          background: CDV.brandGrad, border: 'none', width: 38, height: 38, borderRadius: 99,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
        }}><Icon name="plus" size={18} /></button>
      } />

      {/* Streak hero */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          padding: 18, borderRadius: 22, position: 'relative', overflow: 'hidden',
          background: 'linear-gradient(135deg, rgba(255,122,61,0.15) 0%, rgba(255,181,71,0.08) 100%)',
          border: `1px solid ${CDV.flame}40`,
        }}>
          <div style={{
            position: 'absolute', top: -30, right: -30, fontSize: 140, opacity: 0.07,
            animation: 'flameDance 3s ease-in-out infinite',
          }}>🔥</div>
          <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 18,
              background: 'linear-gradient(135deg, #FF7A3D, #FFB547)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
              boxShadow: '0 10px 30px -10px rgba(255,122,61,0.6)',
              animation: 'flameDance 2.5s ease-in-out infinite',
            }}>
              <Icon name="flame" size={32} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, color: CDV.flame, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Sua maior sequência</div>
              <div style={{ fontSize: 32, fontWeight: 700, color: CDV.text, letterSpacing: -0.6, marginTop: 2 }}>
                {totalStreak} <span style={{ fontSize: 16, color: CDV.textDim, fontWeight: 500 }}>dias</span>
              </div>
              <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 2 }}>Treinar — não pare agora!</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 12, marginTop: 14, paddingTop: 14, borderTop: `1px solid ${CDV.stroke}` }}>
            <MiniStat val={`${done}/${habits.length}`} label="Hoje" color={CDV.mint} />
            <MiniStat val={habits.length} label="Ativos" color={CDV.brand} />
            <MiniStat val="78%" label="Mês" color={CDV.sky} />
          </div>
        </div>
      </div>

      {/* Habits list */}
      <SectionHeader title="Seus hábitos" />
      <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {habits.map(h => (
          <HabitRow key={h.id} habit={h} onToggle={toggleHabit} onClick={() => setSelected(h.id)} />
        ))}
      </div>

      {/* AI insight */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          padding: 14, borderRadius: 16, background: CDV.brandSoft,
          border: `1px solid ${CDV.brand}40`,
          display: 'flex', gap: 12, alignItems: 'flex-start',
        }}>
          <div style={{
            width: 34, height: 34, borderRadius: 10, background: CDV.brandGrad,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', flexShrink: 0,
          }}><Icon name="sparkle" size={16} /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: CDV.brand, letterSpacing: 0.4, textTransform: 'uppercase' }}>Sofia detectou</div>
            <div style={{ fontSize: 13, color: CDV.text, marginTop: 4, lineHeight: 1.4 }}>
              Você mantém hábitos por <b>mais tempo quando começa antes das 8h</b>. Quer reagendar "Meditar" para 7h?
            </div>
          </div>
        </div>
      </div>

      <Sheet open={showNew} onClose={() => setShowNew(false)} title="Novo hábito">
        <NewHabitForm onSubmit={(habit) => {
          setState(s => ({
            ...s,
            habits: [...s.habits, {
              ...habit,
              id: 'h' + Date.now(),
              streak: 0,
              target: 1,
              current: 0,
              unit: 'sessão',
              done: false,
              history: [],
            }]
          }));
          setShowNew(false);
          showToast('Hábito criado');
        }} />
      </Sheet>
    </div>
  );
};

const MiniStat = ({ val, label, color }) => (
  <div style={{ flex: 1 }}>
    <div style={{ fontSize: 18, fontWeight: 700, color, letterSpacing: -0.3 }}>{val}</div>
    <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>{label}</div>
  </div>
);

const HabitRow = ({ habit, onToggle, onClick }) => {
  const pct = (habit.current / habit.target) * 100;
  return (
    <div onClick={onClick} style={{
      padding: 14, borderRadius: 18, background: CDV.surface, border: `1px solid ${CDV.stroke}`,
      display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer',
    }}>
      <div style={{
        width: 46, height: 46, borderRadius: 14, background: habit.color + '22',
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: habit.color, flexShrink: 0,
      }}><Icon name={habit.icon} size={22} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: CDV.text }}>{habit.name}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 2, fontSize: 11, color: CDV.flame, fontWeight: 600, marginLeft: 'auto' }}>
            <Icon name="flame" size={11} /> {habit.streak}
          </div>
        </div>
        <ProgressBar percent={pct} color={habit.color} height={4} />
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
          <div style={{ fontSize: 11, color: CDV.textDim }}>{habit.current}/{habit.target} {habit.unit}</div>
          <div style={{ display: 'flex', gap: 3 }}>
            {habit.history.slice(-7).map((d, i) => (
              <div key={i} style={{ width: 6, height: 12, borderRadius: 2, background: d ? habit.color : 'rgba(255,255,255,0.07)' }} />
            ))}
          </div>
        </div>
      </div>
      <button onClick={(e) => { e.stopPropagation(); onToggle(habit.id); }} style={{
        width: 36, height: 36, borderRadius: 12,
        background: habit.done ? habit.color : 'transparent',
        border: `1.5px solid ${habit.color}`, color: habit.done ? '#fff' : habit.color,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <Icon name={habit.done ? 'check' : 'plus'} size={16} />
      </button>
    </div>
  );
};

// ── Habit detail view ───────────────────────────────────────
const HabitDetail = ({ habit, onBack, onToggle }) => {
  const totalDone = habit.history.filter(Boolean).length;
  const successRate = Math.round((totalDone / habit.history.length) * 100);
  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title={habit.name} subtitle="DETALHES DO HÁBITO" onBack={onBack} />

      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          padding: 22, borderRadius: 22, background: `linear-gradient(135deg, ${habit.color}28 0%, ${habit.color}10 100%)`,
          border: `1px solid ${habit.color}40`, position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 18, background: habit.color,
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
              boxShadow: `0 10px 30px -10px ${habit.color}88`,
            }}><Icon name={habit.icon} size={32} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name="flame" size={18} color={CDV.flame} />
                <div style={{ fontSize: 30, fontWeight: 700, color: CDV.text, letterSpacing: -0.5 }}>{habit.streak}</div>
                <div style={{ fontSize: 13, color: CDV.textDim, fontWeight: 500 }}>dias seguidos</div>
              </div>
              <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 4 }}>
                Próximo marco: <b style={{ color: habit.color }}>30 dias</b> em {30 - habit.streak} dias
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 12, marginTop: 18, paddingTop: 18, borderTop: `1px solid ${habit.color}30` }}>
            <MiniStat val={`${successRate}%`} label="Taxa" color={habit.color} />
            <MiniStat val={totalDone} label="Total" color={CDV.text} />
            <MiniStat val="13" label="Recorde" color={CDV.amber} />
          </div>
        </div>
      </div>

      <SectionHeader title="Últimos 30 dias" />
      <div style={{ padding: '0 22px 18px' }}>
        <Card padding={18}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: 5 }}>
            {habit.history.map((d, i) => (
              <div key={i} style={{
                aspectRatio: 1, borderRadius: 6,
                background: d ? habit.color : 'rgba(255,255,255,0.05)',
                opacity: d ? 1 : 0.6,
                border: i === habit.history.length - 1 ? `2px solid ${CDV.text}` : 'none',
              }} />
            ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 11, color: CDV.textDim }}>
            <span>30 dias atrás</span>
            <span>Hoje</span>
          </div>
        </Card>
      </div>

      <SectionHeader title="Conquistas" />
      <div style={{ padding: '0 22px 18px', display: 'flex', gap: 10, overflowX: 'auto' }}>
        {[
          { name: '7 dias', icon: 'flame', unlocked: true },
          { name: '30 dias', icon: 'star', unlocked: habit.streak >= 30 },
          { name: '100 dias', icon: 'crown', unlocked: false },
          { name: 'Marco anual', icon: 'trophy', unlocked: false },
        ].map((m, i) => (
          <div key={i} style={{
            flex: '0 0 auto', width: 96, padding: 14, borderRadius: 14,
            background: m.unlocked ? habit.color + '22' : CDV.surface,
            border: `1px solid ${m.unlocked ? habit.color : CDV.stroke}`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            opacity: m.unlocked ? 1 : 0.5,
          }}>
            <Icon name={m.icon} size={22} color={m.unlocked ? habit.color : CDV.textMuted} />
            <div style={{ fontSize: 11, fontWeight: 600, color: m.unlocked ? CDV.text : CDV.textMuted, textAlign: 'center' }}>{m.name}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const NewHabitForm = ({ onSubmit, onDone }) => {
  const [name, setName] = React.useState('');
  const [icon, setIcon] = React.useState('drop');
  const [freq, setFreq] = React.useState('todo-dia');
  const [weekdays, setWeekdays] = React.useState([1, 2, 3, 4, 5]); // seg-sex default
  const colors = [CDV.brand, CDV.mint, CDV.coral, CDV.sky, CDV.amber, CDV.flame];
  const [color, setColor] = React.useState(colors[0]);
  const iconOpts = ['drop', 'book', 'dumbbell', 'meditate', 'cup', 'pomodoro', 'sun', 'flame'];
  const weekdaysValid = freq !== 'semana' || weekdays.length > 0;
  const canSave = name.trim().length > 0 && weekdaysValid;
  const toggleWeekday = (i) => setWeekdays(arr => arr.includes(i) ? arr.filter(d => d !== i) : [...arr, i].sort());
  const submit = () => {
    if (!canSave) return;
    if (typeof onSubmit === 'function') {
      onSubmit({
        name: name.trim(), icon, color, freq,
        ...(freq === 'semana' ? { weekdays } : {}),
      });
    } else if (typeof onDone === 'function') onDone();
  };

  return (
    <div style={{ padding: '12px 20px 28px' }}>
      <input value={name} onChange={e => setName(e.target.value)} placeholder="Ex: Beber 2L de água"
        style={{
          width: '100%', height: 54, borderRadius: 16, border: `1px solid ${CDV.stroke}`,
          background: CDV.surfaceHi, color: CDV.text, padding: '0 18px', fontSize: 15,
          outline: 'none', fontFamily: 'inherit',
        }} />
      <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Ícone</div>
      <div style={{ marginTop: 8, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {iconOpts.map(i => (
          <button key={i} onClick={() => setIcon(i)} style={{
            width: 48, height: 48, borderRadius: 14,
            background: icon === i ? color + '22' : CDV.surfaceHi,
            border: `1.5px solid ${icon === i ? color : CDV.stroke}`,
            color: icon === i ? color : CDV.textDim,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name={i} size={22} /></button>
        ))}
      </div>
      <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Cor</div>
      <div style={{ marginTop: 8, display: 'flex', gap: 10 }}>
        {colors.map(c => (
          <button key={c} onClick={() => setColor(c)} style={{
            width: 32, height: 32, borderRadius: 99, background: c,
            border: `2.5px solid ${color === c ? CDV.text : 'transparent'}`,
            boxShadow: color === c ? `0 0 0 2px ${CDV.bg}` : 'none',
          }} />
        ))}
      </div>
      <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Frequência</div>
      <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
        {[{ id: 'todo-dia', label: 'Todo dia' }, { id: 'semana', label: 'Dias da semana' }, { id: 'x-semana', label: '3x semana' }].map(f => (
          <button key={f.id} onClick={() => setFreq(f.id)} style={{
            flex: 1, height: 44, borderRadius: 12,
            background: freq === f.id ? color + '22' : CDV.surfaceHi,
            border: `1.5px solid ${freq === f.id ? color : CDV.stroke}`,
            color: freq === f.id ? color : CDV.textDim,
            fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          }}>{f.label}</button>
        ))}
      </div>

      {freq === 'semana' && (
        <div style={{ marginTop: 14 }}>
          <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.3, marginBottom: 6 }}>
            Selecione os dias
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
            {['D', 'S', 'T', 'Q', 'Q', 'S', 'S'].map((label, i) => {
              const active = weekdays.includes(i);
              return (
                <button key={i} onClick={() => toggleWeekday(i)} style={{
                  height: 44, borderRadius: 10,
                  background: active ? color + '24' : CDV.surfaceHi,
                  border: `1.5px solid ${active ? color : CDV.stroke}`,
                  color: active ? color : CDV.textDim,
                  fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
                }}>{label}</button>
              );
            })}
          </div>
          {weekdays.length === 0 && (
            <div style={{ fontSize: 11, color: CDV.coral, marginTop: 6 }}>
              Selecione ao menos 1 dia.
            </div>
          )}
        </div>
      )}
      <button onClick={submit} disabled={!canSave} style={{
        marginTop: 22, width: '100%', height: 54, borderRadius: 16,
        background: CDV.brandGrad, border: 'none', color: '#fff', fontWeight: 600, fontSize: 15,
        opacity: canSave ? 1 : 0.4, cursor: canSave ? 'pointer' : 'not-allowed',
      }}>Criar hábito</button>
    </div>
  );
};

Object.assign(window, { HabitsScreen });
