// ========== Welcome + Dashboard ==========
const { Avatar, Icon, Sparkline, TagPill, Currency,
        fmtBRL, fmtBRLShort, pct, pctFine, MONTH_NAMES_PT } = window.FinUtils;

function Welcome({ users, onPick }) {
  return (
    <div className="welcome">
      <div className="welcome-inner">
        <div className="hstack" style={{ justifyContent: 'center', marginBottom: 24 }}>
          <div className="brand-mark" style={{ width: 44, height: 44, fontSize: 18 }}>f</div>
          <span className="brand-name" style={{ fontSize: 28 }}>Finanças</span>
        </div>
        <h1>Bem-vindos <em>de volta</em>.</h1>
        <p className="sub">Quem está por aqui agora? Escolha seu perfil para ver seu fluxo e o que é compartilhado.</p>
        <div className="user-picks">
          {users.map(u => (
            <button key={u.id} className={`user-pick ${u.name.toLowerCase()}`} onClick={() => onPick(u)}>
              <Avatar user={u} size="lg" />
              <div>
                <div className="name">{u.name}</div>
                <div className="role">abrir meu fluxo</div>
              </div>
            </button>
          ))}
        </div>
        <div style={{ marginTop: 48, fontSize: 12, color: 'var(--text-mute)' }}>
          dados locais · sem senha
        </div>
      </div>
    </div>
  );
}

function Dashboard({ state, setState }) {
  const { user, txs, users, tags, history, goals, subs, assets, investmentTarget } = state;

  const currentMonth = new Date().toISOString().slice(0, 7);
  const monthTxs  = txs.filter(t => t.date.startsWith(currentMonth) && (t.userId === user.id || t.shared));
  const income    = monthTxs.filter(t => t.type === 'income').reduce((s,t) => s + t.amount, 0);
  const invested  = monthTxs.filter(t => t.type === 'saving').reduce((s,t) => s + t.amount, 0);
  const expense   = monthTxs.filter(t => t.type === 'expense').reduce((s,t) => s + t.amount, 0);
  const balance   = income - expense - invested;
  const investRate = income > 0 ? invested / income : 0;
  const invTarget  = investmentTarget ?? 0.25;
  const daysInMonth = new Date().getDate();
  const dailyAvg  = daysInMonth > 0 ? expense / daysInMonth : 0;

  const bars = history.slice();
  if (bars.length > 0) {
    bars[bars.length - 1] = { month: currentMonth, income, expenses: expense + invested };
  }
  const maxBar = Math.max(...bars.map(b => Math.max(b.income || 0, b.expenses || 0)), 1);

  const tagTotals = {};
  monthTxs.filter(t => t.type === 'expense').forEach(t => {
    (t.tags && t.tags.length ? t.tags : [12]).forEach(tid => {
      tagTotals[tid] = (tagTotals[tid] || 0) + t.amount / (t.tags && t.tags.length ? t.tags.length : 1);
    });
  });
  const topTags = Object.entries(tagTotals)
    .map(([tid, v]) => ({ tag: tags.find(t => t.id === +tid), value: Math.round(v) }))
    .filter(x => x.tag)
    .sort((a, b) => b.value - a.value)
    .slice(0, 6);
  const tagSum = topTags.reduce((s, t) => s + t.value, 0) || 1;

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="dim" style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
            {MONTH_NAMES_PT[new Date().getMonth()].toLowerCase()} · semana {Math.ceil(new Date().getDate() / 7)}
          </div>
          <h1 className="page-title">Oi, {user.name.toLowerCase()}.</h1>
          <div className="page-subtitle">
            Você tem <strong className="num" style={{ color: 'var(--text)' }}>{fmtBRL(balance)}</strong> de saldo este mês · {pctFine(investRate)} investido.
          </div>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={() => setState(s => ({ ...s, showAdd: true }))}>
            <Icon name="plus" size={14}/> Nova transação
          </button>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi">
          <div className="kpi-label"><span className="kpi-dot" style={{ background: 'var(--income)' }}/> Entradas · mês</div>
          <div className="kpi-value"><Currency cents={income} /></div>
          <div className="kpi-meta"><span className="delta up"><Icon name="arrowUp" size={10}/> mês atual</span></div>
          <Sparkline data={bars.map(h => h.income || 0)} color="var(--income)" />
        </div>
        <div className="kpi">
          <div className="kpi-label"><span className="kpi-dot" style={{ background: 'var(--expense)' }}/> Saídas · mês</div>
          <div className="kpi-value"><Currency cents={expense} /></div>
          <div className="kpi-meta"><span className="muted">média diária {fmtBRL(dailyAvg)}</span></div>
          <Sparkline data={bars.map(h => h.expenses || 0)} color="var(--expense)" />
        </div>
        <div className="kpi">
          <div className="kpi-label"><span className="kpi-dot" style={{ background: 'var(--accent)' }}/> Taxa de investimento</div>
          <div className="kpi-value display num" style={{ fontSize: 46, color: investRate >= invTarget ? 'var(--income)' : undefined }}>{pct(investRate)}</div>
          <div className="kpi-meta">
            <span className={investRate >= invTarget ? 'delta up' : 'muted'}>meta {pct(invTarget)}</span>
            <span>{fmtBRL(invested)} investidos</span>
          </div>
        </div>
        <div className="kpi">
          <div className="kpi-label"><span className="kpi-dot" style={{ background: 'var(--c-moradia)' }}/> Patrimônio</div>
          <div className="kpi-value"><Currency cents={assets.reduce((s,a) => s + a.value, 0)} /></div>
          <div className="kpi-meta"><span className="delta up"><Icon name="arrowUp" size={10}/> últimos 6 meses</span></div>
          <Sparkline data={assets[0] ? assets[0].history.map((_, i) => assets.reduce((s, a) => s + (a.history[i] || 0), 0)) : []} color="var(--c-moradia)" />
        </div>
      </div>

      <div className="grid-3" style={{ marginBottom: 'var(--s4)' }}>
        <div className="card">
          <div className="card-head">
            <h3 className="card-title-lg">Receita vs despesa</h3>
            <div className="chip-select"><button className="active">6 meses</button></div>
          </div>
          <BarsChart bars={bars} max={maxBar} />
        </div>
        <div className="card">
          <div className="card-head">
            <h3 className="card-title-lg">Onde foi</h3>
          </div>
          <div className="vstack" style={{ gap: 14 }}>
            {topTags.length === 0 && <p className="muted" style={{ fontSize: 13, textAlign: 'center', padding: '16px 0' }}>Sem despesas no mês</p>}
            {topTags.map(({ tag, value }) => {
              const share = value / tagSum;
              return (
                <div key={tag.id}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13 }}>
                    <div className="hstack" style={{ gap: 8 }}>
                      <span style={{ fontSize: 16 }}>{tag.icon}</span>
                      <span style={{ fontWeight: 500 }}>{tag.name}</span>
                    </div>
                    <span className="num" style={{ fontWeight: 600 }}>{fmtBRL(value)}</span>
                  </div>
                  <div className="progress">
                    <div className="progress-fill" style={{ width: `${Math.max(4, share * 100)}%`, background: tag.color }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div className="grid-2">
        <div className="card">
          <div className="card-head">
            <h3 className="card-title-lg">Metas</h3>
            <button className="btn btn-ghost" onClick={() => setState(s => ({ ...s, view: 'goals' }))} style={{ padding: '4px 8px', fontSize: 11 }}>Ver todas</button>
          </div>
          <div className="vstack" style={{ gap: 18 }}>
            {goals.slice(0, 3).map(g => {
              const ratio = Math.min(1, g.current / g.target);
              return (
                <div key={g.id}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                    <div className="hstack">
                      <div className="goal-icon" style={{ background: `color-mix(in oklch, ${g.color} 18%, white)`, width: 32, height: 32, fontSize: 15 }}>{g.icon}</div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{g.name}</div>
                        <div className="muted" style={{ fontSize: 11 }}>{fmtBRLShort(g.current)} de {fmtBRLShort(g.target)}</div>
                      </div>
                    </div>
                    <div className="num display" style={{ fontSize: 22 }}>{pct(ratio)}</div>
                  </div>
                  <div className="progress">
                    <div className="progress-fill" style={{ width: `${ratio*100}%`, background: g.color }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div className="card">
          <div className="card-head">
            <h3 className="card-title-lg">Assinaturas ativas</h3>
            <button className="btn btn-ghost" onClick={() => setState(s => ({ ...s, view: 'subs' }))} style={{ padding: '4px 8px', fontSize: 11 }}>Gerenciar</button>
          </div>
          <div className="vstack" style={{ gap: 10 }}>
            {subs.filter(s => s.active && (s.ownerId === user.id || s.shared)).slice(0, 5).map(s => {
              const tag = tags.find(t => t.id === s.tag);
              const owner = users.find(u => u.id === s.ownerId);
              if (!tag || !owner) return null;
              return (
                <div key={s.id} className="hstack" style={{ justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--border)' }}>
                  <div className="hstack">
                    <div style={{ width: 32, height: 32, borderRadius: 8, display: 'grid', placeItems: 'center', background: `color-mix(in oklch, ${tag.color} 15%, white)`, fontSize: 14 }}>{tag.icon}</div>
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 13 }}>{s.name}</div>
                      <div className="muted" style={{ fontSize: 11 }}>todo dia {s.day} · {owner.name}</div>
                    </div>
                  </div>
                  <div className="num" style={{ fontWeight: 600, fontSize: 13 }}>{fmtBRL(s.amount)}</div>
                </div>
              );
            })}
            <div className="hstack" style={{ justifyContent: 'space-between', paddingTop: 6 }}>
              <span className="muted" style={{ fontSize: 12 }}>Total mensal</span>
              <span className="num display" style={{ fontSize: 20 }}>{fmtBRL(subs.filter(s => s.active && !s.cardLinked && (s.ownerId === user.id || s.shared)).reduce((t, s) => t + s.amount, 0))}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function BarsChart({ bars, max }) {
  const H = 200;
  if (!bars || bars.length === 0) return null;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${bars.length}, 1fr)`, gap: 12, alignItems: 'end', height: H + 28 }}>
        {bars.map((b, i) => {
          const [, m] = (b.month || '').split('-');
          const inc = ((b.income || 0) / max) * H;
          const exp = ((b.expenses || 0) / max) * H;
          const isLast = i === bars.length - 1;
          return (
            <div key={b.month} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div className="num muted" style={{ fontSize: 10, height: 12 }}>
                {isLast ? fmtBRLShort((b.income || 0) - (b.expenses || 0)) : ''}
              </div>
              <div style={{ display: 'flex', alignItems: 'end', gap: 3, height: H, width: '100%', justifyContent: 'center' }}>
                <div style={{ width: '38%', height: inc, background: isLast ? 'var(--income)' : 'color-mix(in oklch, var(--income) 30%, white)', borderRadius: '6px 6px 0 0' }}/>
                <div style={{ width: '38%', height: exp, background: isLast ? 'var(--expense)' : 'color-mix(in oklch, var(--expense) 30%, white)', borderRadius: '6px 6px 0 0' }}/>
              </div>
              <div style={{ fontSize: 11, color: isLast ? 'var(--text)' : 'var(--text-mute)', fontWeight: isLast ? 600 : 500, textTransform: 'capitalize' }}>
                {m ? MONTH_NAMES_PT[+m - 1].toLowerCase() : ''}
              </div>
            </div>
          );
        })}
      </div>
      <div className="hstack" style={{ justifyContent: 'center', gap: 20, marginTop: 18, fontSize: 11, color: 'var(--text-mute)' }}>
        <span className="hstack" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--income)', borderRadius: 3 }}/> Entradas</span>
        <span className="hstack" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--expense)', borderRadius: 3 }}/> Saídas</span>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.Welcome = Welcome;
