// Goals screen — list + detail with steps generated by AI

const GOAL_CAT_COLOR = {
  financeiro: '#5EE3A8',  // mint
  saude:      '#FF7A6B',  // coral
  estudo:     '#6FB8FF',  // sky
  pessoal:    '#FFB547',  // amber
  viagem:     '#FF8FB1',  // rosa
  outros:     '#9B98A8',  // cinza neutro
};
const getGoalCatColor = (cat) => GOAL_CAT_COLOR[cat] || '#6FB8FF';

const GoalsScreen = ({ state, setState, navigate, showToast }) => {
  const { goals } = state;
  const [selected, setSelected] = React.useState(null);
  const [showNew, setShowNew] = React.useState(false);

  if (selected) {
    return <GoalDetail goal={goals.find(g => g.id === selected)} onBack={() => setSelected(null)}
      onToggleStep={(stepId) => {
        setState(s => ({
          ...s, goals: s.goals.map(g => g.id !== selected ? g :
            { ...g, etapas: g.etapas.map(e => e.id === stepId ? { ...e, done: !e.done } : e) })
        }));
        showToast('Etapa atualizada');
      }} />;
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Metas" subtitle="O QUE QUERO CONQUISTAR" onBack={() => navigate('dashboard')} 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>
      } />

      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ display: 'flex', gap: 10 }}>
          <StatBlock label="Em andamento" value={goals.length} color={CDV.brand} />
          <StatBlock label="Concluídas" value={12} color={CDV.mint} />
          <StatBlock label="Taxa de sucesso" value="74%" color={CDV.amber} />
        </div>
      </div>

      <SectionHeader title="Suas metas ativas" />
      <div style={{ padding: '0 22px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {goals.map(g => <GoalCard key={g.id} goal={g} onClick={() => setSelected(g.id)} />)}
      </div>

      <SectionHeader title="Metas sugeridas pela IA" accent />
      <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { title: 'Economizar R$ 5k para reserva', icon: 'wallet', color: CDV.mint },
          { title: 'Ler 12 livros até dezembro', icon: 'book', color: CDV.amber },
          { title: 'Treinar 4x por semana', icon: 'dumbbell', color: CDV.coral },
        ].map((s, i) => (
          <div key={i} style={{
            padding: 14, borderRadius: 16, background: CDV.surface, border: `1px solid ${CDV.stroke}`,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <IconTile name={s.icon} color={s.color} size={38} />
            <div style={{ flex: 1, fontSize: 14, color: CDV.text }}>{s.title}</div>
            <button onClick={() => showToast('Meta adicionada')} style={{
              background: CDV.brandSoft, border: `1px solid ${CDV.brand}40`, color: CDV.brand,
              padding: '7px 12px', borderRadius: 99, fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
            }}>+ Adicionar</button>
          </div>
        ))}
      </div>

      <Sheet open={showNew} onClose={() => setShowNew(false)} title="Nova meta">
        <NewGoalForm onSubmit={(g) => {
          setState(s => ({
            ...s,
            goals: [...s.goals, {
              id: 'g' + Date.now(),
              title: g.title,
              category: g.cat,
              deadline: g.deadline,
              progress: 0,
              etapas: [],
            }]
          }));
          setShowNew(false);
          showToast('Meta criada, IA gerando etapas...');
        }} />
      </Sheet>
    </div>
  );
};

const StatBlock = ({ label, value, color }) => {
  const c = color || CDV.brand;
  return (
    <div style={{
      flex: 1, padding: 14, paddingLeft: 16, borderRadius: 16,
      background: `linear-gradient(135deg, ${c}1a 0%, ${c}06 35%, ${CDV.surface} 100%)`,
      border: `1px solid ${c}30`, position: 'relative', overflow: 'hidden',
      boxShadow: `0 6px 18px -10px ${c}40, 0 0 0 1px ${c}10 inset`,
    }}>
      {/* Glow blob */}
      <div style={{
        position: 'absolute', top: -34, right: -34, width: 100, height: 100, borderRadius: 99,
        background: `radial-gradient(circle, ${c}55, transparent 60%)`,
        filter: 'blur(20px)', opacity: 0.55, pointerEvents: 'none',
      }} />
      {/* Barra lateral */}
      <div style={{
        position: 'absolute', left: 0, top: 12, bottom: 12, width: 3, borderRadius: 99,
        background: `linear-gradient(180deg, ${c}, ${c}40)`,
        boxShadow: `0 0 12px ${c}80`,
      }} />
      <div style={{
        position: 'relative',
        fontSize: 22, fontWeight: 700, letterSpacing: -0.4, lineHeight: 1.1,
        backgroundImage: `linear-gradient(135deg, ${CDV.text} 0%, ${c} 130%)`,
        WebkitBackgroundClip: 'text', backgroundClip: 'text',
        WebkitTextFillColor: 'transparent', color: 'transparent',
      }}>{value}</div>
      <div style={{
        position: 'relative', fontSize: 10, color: c, marginTop: 4,
        fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase',
      }}>{label}</div>
    </div>
  );
};

const GoalCard = ({ goal, onClick }) => {
  const catColor = getGoalCatColor(goal.category);
  const stepsDone = goal.etapas.filter(e => e.done).length;
  return (
    <div onClick={onClick} style={{
      padding: 18, borderRadius: 22, background: CDV.surface, border: `1px solid ${CDV.stroke}`,
      position: 'relative', overflow: 'hidden', cursor: 'pointer',
    }}>
      <div style={{
        position: 'absolute', top: -50, right: -50, width: 180, height: 180, borderRadius: 99,
        background: `radial-gradient(circle, ${catColor}22, transparent 70%)`, filter: 'blur(30px)',
      }} />
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div style={{ flex: 1, paddingRight: 12 }}>
            <Pill color={catColor} size="sm" style={{ marginBottom: 8 }}>{goal.category}</Pill>
            <div style={{ fontSize: 17, fontWeight: 600, color: CDV.text, letterSpacing: -0.2, lineHeight: 1.25 }}>{goal.title}</div>
            <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 6 }}>Prazo: {goal.deadline}</div>
          </div>
          <ProgressRing percent={goal.progress} size={54} stroke={5} color={catColor}>
            <div style={{ fontSize: 14, fontWeight: 700, color: catColor }}>{goal.progress}%</div>
          </ProgressRing>
        </div>
        <div style={{ marginTop: 14, paddingTop: 14, borderTop: `1px solid ${CDV.stroke}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 12, color: CDV.textDim }}>
            <b style={{ color: CDV.text, fontWeight: 600 }}>{stepsDone}</b>/{goal.etapas.length} etapas
          </div>
          {goal.savedReais && (
            <div style={{ fontSize: 12, color: CDV.textDim }}>
              <b style={{ color: catColor, fontWeight: 600 }}>R$ {goal.savedReais.toLocaleString('pt-BR')}</b>
              {' '}/ R$ {goal.targetReais.toLocaleString('pt-BR')}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const GoalDetail = ({ goal, onBack, onToggleStep }) => {
  const catColor = getGoalCatColor(goal.category);
  const stepsDone = goal.etapas.filter(e => e.done).length;
  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title={goal.title} subtitle={goal.category.toUpperCase()} onBack={onBack} />

      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          padding: 22, borderRadius: 22,
          background: `linear-gradient(135deg, ${catColor}28, ${catColor}08)`,
          border: `1px solid ${catColor}40`, position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 11, color: catColor, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>Progresso</div>
              <div style={{ fontSize: 38, fontWeight: 700, color: CDV.text, letterSpacing: -0.8, marginTop: 4 }}>
                {goal.progress}<span style={{ fontSize: 22, color: CDV.textDim }}>%</span>
              </div>
              <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 4 }}>Prazo: {goal.deadline}</div>
            </div>
            <ProgressRing percent={goal.progress} size={90} stroke={8} color={catColor}>
              <Icon name="target" size={28} color={catColor} />
            </ProgressRing>
          </div>
          {goal.savedReais && (
            <div style={{ marginTop: 18, paddingTop: 18, borderTop: `1px solid ${catColor}30` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <div style={{ fontSize: 12, color: CDV.textDim }}>Acumulado</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: CDV.text }}>R$ {goal.savedReais.toLocaleString('pt-BR')} / R$ {goal.targetReais.toLocaleString('pt-BR')}</div>
              </div>
              <ProgressBar percent={(goal.savedReais / goal.targetReais) * 100} color={catColor} height={6} />
            </div>
          )}
        </div>
      </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' }}>Análise da IA</div>
            <div style={{ fontSize: 13, color: CDV.text, marginTop: 4, lineHeight: 1.4 }}>
              No ritmo atual, você atinge essa meta <b>2 semanas antes do prazo</b>.
              Considere aumentar a meta em 8% para um desafio maior?
            </div>
          </div>
        </div>
      </div>

      <SectionHeader title={`Etapas (${stepsDone}/${goal.etapas.length})`} action="+ Etapa" />
      <div style={{ padding: '0 22px 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
        {goal.etapas.map((e, i) => (
          <div key={e.id} onClick={() => onToggleStep(e.id)} style={{
            padding: '12px 14px', borderRadius: 14, background: CDV.surface, border: `1px solid ${CDV.stroke}`,
            display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
          }}>
            <div style={{
              width: 26, height: 26, borderRadius: 99,
              background: e.done ? catColor : 'transparent',
              border: `1.5px solid ${e.done ? catColor : CDV.textFaint}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              fontSize: 11, fontWeight: 700, color: e.done ? '#fff' : CDV.textMuted,
            }}>{e.done ? <Icon name="check" size={14} color="#fff" /> : i + 1}</div>
            <div style={{
              flex: 1, fontSize: 14, color: e.done ? CDV.textMuted : CDV.text,
              textDecoration: e.done ? 'line-through' : 'none',
            }}>{e.title}</div>
            {e.done && <div style={{ fontSize: 10, color: catColor, fontWeight: 600 }}>+50 XP</div>}
          </div>
        ))}
      </div>
    </div>
  );
};

const NewGoalForm = ({ onSubmit, onDone }) => {
  const [title, setTitle] = React.useState('');
  const [cat, setCat] = React.useState('financeiro');
  const [deadline, setDeadline] = React.useState('6 meses');
  const canSave = title.trim().length > 0;
  const submit = () => {
    if (!canSave) return;
    if (typeof onSubmit === 'function') onSubmit({ title: title.trim(), cat, deadline });
    else if (typeof onDone === 'function') onDone();
  };
  return (
    <div style={{ padding: '12px 20px 28px' }}>
      <input value={title} onChange={e => setTitle(e.target.value)} placeholder="Ex: Comprar minha primeira moto"
        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: 8, fontSize: 12, color: CDV.brand, display: 'flex', alignItems: 'center', gap: 4 }}>
        <Icon name="sparkle" size={12} /> A IA vai dividir essa meta em etapas práticas
      </div>

      <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Categoria</div>
      <div style={{ marginTop: 8, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {[
          { id: 'financeiro', c: '#5EE3A8', label: 'Financeiro' },
          { id: 'saude',      c: '#FF7A6B', label: 'Saúde' },
          { id: 'estudo',     c: '#6FB8FF', label: 'Estudo' },
          { id: 'pessoal',    c: '#FFB547', label: 'Pessoal' },
          { id: 'viagem',     c: '#FF8FB1', label: 'Viagem' },
          { id: 'outros',     c: '#9B98A8', label: 'Outros' },
        ].map(c => (
          <button key={c.id} onClick={() => setCat(c.id)} style={{
            padding: '10px 14px', borderRadius: 99,
            background: cat === c.id ? c.c + '22' : CDV.surfaceHi,
            border: `1.5px solid ${cat === c.id ? c.c : CDV.stroke}`,
            color: cat === c.id ? c.c : CDV.textDim,
            fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          }}>{c.label}</button>
        ))}
      </div>

      <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Prazo</div>
      <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
        {['1 mês', '3 meses', '6 meses', '1 ano'].map(d => (
          <button key={d} onClick={() => setDeadline(d)} style={{
            flex: 1, height: 44, borderRadius: 12,
            background: deadline === d ? CDV.brandSoft : CDV.surfaceHi,
            border: `1.5px solid ${deadline === d ? CDV.brand : CDV.stroke}`,
            color: deadline === d ? CDV.brand : CDV.textDim,
            fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          }}>{d}</button>
        ))}
      </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 com ajuda da IA ✨</button>
    </div>
  );
};

Object.assign(window, { GoalsScreen });
