/* ============================================================
   AGENDA — Dashboard (indicadores calculados de dados reais)
   ============================================================ */
const { Icon: I1, Avatar: Av, Badge: Bdg, Button: Btn, Checkbox: Cbx } = window;

function Dashboard(ctx) {
  const { terms, appts, services, team, clients, tasks, transactions, openNewAppt, openAppt, statusMap, money, settings, user, businessType } = ctx;
  const DB = window.DB;
  const todayISO = DB.iso(DB.today);
  const todays = appts.filter(a => a.date === todayISO).sort((a, b) => window.timeToMin(a.start) - window.timeToMin(b.start));
  const active = todays.filter(a => a.status !== 'cancelado');

  const txToday = transactions.filter(t => t.date === todayISO && t.value > 0);
  const revToday = txToday.reduce((s, t) => s + t.value, 0);
  const pendingSum = transactions.filter(t => t.status === 'pendente' && t.value > 0).reduce((s, t) => s + t.value, 0);
  const confirmed = active.filter(a => a.status === 'confirmado').length;
  const confRate = active.length ? Math.round(confirmed / active.length * 100) : 0;
  const nowMin = new Date().getHours() * 60 + new Date().getMinutes();
  const nextAppt = active.find(a => window.timeToMin(a.start) >= nowMin && (a.status === 'confirmado' || a.status === 'pendente'));

  const hour = new Date().getHours();
  const greet = hour < 12 ? 'Bom dia' : hour < 18 ? 'Boa tarde' : 'Boa noite';
  const dateStr = DB.today.toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' });
  const userName = ((user && (user.name || user.login)) || settings.user_name || 'Secretaria').split(' ')[0];

  const cli = (id) => clients.find(c => c.id === id);
  const svc = (id) => services.find(s => s.id === id);
  const pro = (id) => team.find(p => p.id === id);

  // comparação com ontem
  const yCount = appts.filter(a => a.date === DB.iso(DB.addDays(-1)) && a.status !== 'cancelado').length;
  const dy = active.length - yCount;
  // clientes novos nos últimos 7 dias
  const newClients = clients.filter(c => c.createdAt && (Date.now() - new Date(String(c.createdAt).replace(' ', 'T')).getTime()) < 7 * 86400e3).length;

  const kpis = [
    { lbl: terms.appt + 's hoje', val: active.length, ic: 'calendar', color: 'var(--ev-blue)', bg: 'var(--ev-blue-bg)', delta: (dy >= 0 ? '+' : '') + dy, up: dy >= 0, since: 'vs. ontem' },
    { lbl: 'Faturamento hoje', val: money(revToday).replace(',00', ''), ic: 'wallet', color: 'var(--ev-green)', bg: 'var(--ev-green-bg)', delta: txToday.length + '', up: true, since: 'lançamentos' },
    { lbl: 'Taxa de confirmação', val: confRate + '%', ic: 'check2', color: 'var(--ev-teal)', bg: 'var(--ev-teal-bg)', delta: confirmed + '/' + active.length, up: true, since: 'confirmados' },
    { lbl: terms.clients.toLowerCase() + ' novos', val: newClients, ic: 'users', color: 'var(--ev-cyan)', bg: 'var(--ev-cyan-bg)', delta: '+' + newClients, up: true, since: 'últimos 7 dias' },
  ];

  // ocupação da semana (seg–dom) a partir dos agendamentos reais
  const weekStart = (() => { const d = new Date(DB.today); const wd = (d.getDay() + 6) % 7; d.setDate(d.getDate() - wd); return d; })();
  const weekCounts = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(weekStart); d.setDate(weekStart.getDate() + i);
    const k = DB.iso(d);
    return appts.filter(a => a.date === k && a.status !== 'cancelado').length;
  });
  const weekTotal = weekCounts.reduce((s, v) => s + v, 0);
  const maxWeek = Math.max(1, ...weekCounts);
  const occ = weekCounts.map(v => Math.round(v / maxWeek * 100));
  const todayIdx = (DB.today.getDay() + 6) % 7;

  const openTasks = tasks.filter(t => !t.done);
  const pendCount = active.filter(a => a.status === 'pendente').length;

  // ocupação da área/pessoas do segmento hoje
  const proLoad = team.filter(p => !p.archived).map(p => {
    const c = active.filter(a => a.proId === p.id).length;
    return { ...p, count: c, pct: Math.min(100, c * 22) };
  });

  return (
    <div className="content-inner fadein">
      {/* header */}
      <div className="row between wrap" style={{ marginBottom: 20, gap: 14 }}>
        <div>
          <h1 style={{ fontSize: 24 }}>{greet}, {userName} 👋</h1>
          <div className="muted" style={{ fontSize: 13.5, marginTop: 3, textTransform: 'capitalize' }}>{dateStr} · {active.length} {terms.appt.toLowerCase()}s na agenda</div>
        </div>
        <div className="row" style={{ gap: 10 }}>
          <Btn variant="outline" icon="zap" disabled={pendCount === 0} onClick={ctx.confirmAllToday}>Confirmar todos</Btn>
          <Btn variant="primary" icon="plus" onClick={() => openNewAppt()}>{['Aula', 'Consulta', 'Sessão'].includes(terms.appt) ? 'Nova' : 'Novo'} {terms.appt.toLowerCase()}</Btn>
        </div>
      </div>

      {/* KPIs */}
      <div className="kpi-grid" style={{ marginBottom: 16 }}>
        {kpis.map((k, i) => (
          <div className="card kpi" key={i}>
            <div className="top">
              <div className="ic" style={{ background: k.bg, color: k.color }}><I1 name={k.ic} size={19} /></div>
              <div className="lbl">{k.lbl}</div>
            </div>
            <div className="val">{k.val}</div>
            <div className={'delta ' + (k.up ? 'up' : 'down')}>
              <I1 name={k.up ? 'trendUp' : 'trendDown'} size={14} stroke={2.4} />{k.delta}
              <span className="since">{k.since}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="grid-2">
        {/* Agenda de hoje */}
        <div className="card" style={{ display: 'flex', flexDirection: 'column' }}>
          <div className="card-head">
            <div style={{ flex: 1 }}>
              <h3>Agenda de hoje</h3>
              <div className="sub">{active.length} {terms.appt.toLowerCase()}s · {confirmed} confirmados</div>
            </div>
            {nextAppt && <Bdg cls="blue" dot>Próximo {nextAppt.start}</Bdg>}
          </div>
          <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 0, maxHeight: 470, overflowY: 'auto' }}>
            {todays.length === 0 && <div className="muted" style={{ fontSize: 13, padding: '18px 4px' }}>Nenhum {terms.appt.toLowerCase()} para hoje. Clique em "Novo" para criar o primeiro.</div>}
            {todays.map((a, idx) => {
              const c = cli(a.clientId), s = a.manualServiceName ? { name: a.manualServiceName, price: a.manualServicePrice || 0, color: 'violet' } : svc(a.serviceId), p = pro(a.proId);
              if (!s || !p) return null;
              const clientLabel = String(a.clientLabel || a.clientName || (c ? c.name : '')).trim();
              const proLabel = p.name.replace('Dra. ', '');
              const hasClientLabel = clientLabel !== '';
              const titleLabel = hasClientLabel ? clientLabel : (businessType === 'escritorio' ? s.name : `Sem ${terms.client.toLowerCase()} informado`);
              const detailLabel = hasClientLabel || businessType !== 'escritorio' ? `${s.name} \u00b7 ${proLabel}` : proLabel;
              const st = statusMap[a.status];
              const isNext = nextAppt && a.id === nextAppt.id;
              return (
                <div key={a.id}>
                  <div className="tl-item">
                    <div className="tl-time">{a.start}<small>{window.apptEnd(a)}</small></div>
                    <div className="tl-card" style={{ '--c': DB.colorValue(p.color), opacity: a.status === 'cancelado' ? .55 : 1, boxShadow: isNext ? '0 0 0 1.5px var(--primary)' : '' }}
                      onClick={() => openAppt(a)}>
                      <Av initials={titleLabel ? titleLabel.split(' ').map(x => x[0]).slice(0, 2).join('') : '--'} color={p.color} size={36} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{titleLabel}</div>
                        <div className="muted" style={{ fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{detailLabel}</div>
                      </div>
                      <Bdg cls={st.cls} dot>{st.label}</Bdg>
                    </div>
                  </div>
                  {idx < todays.length - 1 && <div style={{ height: 8, marginLeft: 27 }}><div className="tl-line" style={{ height: '100%' }} /></div>}
                </div>
              );
            })}
          </div>
        </div>

        {/* right column */}
        <div className="stack">
          {/* tarefas */}
          <div className="card">
            <div className="card-head">
              <div style={{ flex: 1 }}><h3>Tarefas de hoje</h3><div className="sub">{openTasks.length} pendentes</div></div>
              <button className="iconbtn" style={{ width: 32, height: 32 }} title="Nova tarefa" onClick={() => ctx.go('tarefas')}><I1 name="plus" size={16} /></button>
            </div>
            <div className="card-pad" style={{ paddingTop: 4, paddingBottom: 8 }}>
              {tasks.slice(0, 5).map(t => (
                <div className="lrow" key={t.id} style={{ padding: '9px 2px' }}>
                  <Cbx on={t.done} onClick={() => ctx.toggleTask(t.id, !t.done)} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, textDecoration: t.done ? 'line-through' : 'none', color: t.done ? 'var(--text-3)' : 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.text}</div>
                    <div className="muted" style={{ fontSize: 11.5 }}>{t.due}</div>
                  </div>
                  {t.prio === 'alta' && !t.done && <span className="badge red" style={{ height: 20 }}>Alta</span>}
                </div>
              ))}
            </div>
          </div>

          {/* ocupação da área/pessoas do segmento */}
          <div className="card">
            <div className="card-head"><div style={{ flex: 1 }}><h3>Ocupação - {terms.pros}</h3><div className="sub">Hoje</div></div></div>
            <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
              {proLoad.map(p => (
                <div className="row" key={p.id} style={{ gap: 11 }}>
                  <Av initials={p.initials} color={p.color} size={30} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="row between" style={{ marginBottom: 5 }}>
                      <span style={{ fontSize: 12.5, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name.replace('Dra. ', '')}</span>
                      <span className="muted mono" style={{ fontSize: 11.5 }}>{p.count} ag.</span>
                    </div>
                    <div className="bar"><i style={{ width: p.pct + '%', background: `var(--ev-${p.color})` }} /></div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* bottom: semana + resumo financeiro */}
      <div className="grid-3" style={{ marginTop: 16 }}>
        <div className="card card-pad">
          <div className="row between" style={{ marginBottom: 14 }}>
            <div><div style={{ fontSize: 13.5, fontWeight: 600 }}>Volume da semana</div><div className="muted" style={{ fontSize: 12 }}>Agendamentos por dia</div></div>
            <Bdg cls="green" dot>{weekTotal} na semana</Bdg>
          </div>
          <div className="spark" style={{ height: 64 }}>
            {occ.map((v, i) => <i key={i} className={i === todayIdx ? 'hot' : ''} style={{ height: Math.max(6, v) + '%' }} title={weekCounts[i] + ' agendamentos'} />)}
          </div>
          <div className="row between muted" style={{ fontSize: 10.5, marginTop: 7 }}>
            {['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'].map(d => <span key={d}>{d}</span>)}
          </div>
        </div>

        {ctx.user && ctx.user.hasFinance && ctx.user.isPrimaryAdmin && (
          <div className="card card-pad">
            <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 3 }}>Resumo financeiro</div>
            <div className="muted" style={{ fontSize: 12, marginBottom: 14 }}>Hoje</div>
            <div className="row between" style={{ marginBottom: 10 }}>
              <span className="row" style={{ gap: 8, fontSize: 12.5 }}><span className="d" style={{ width: 8, height: 8, borderRadius: 99, background: 'var(--success)' }} />Receitas</span>
              <span className="mono" style={{ fontWeight: 600, color: 'var(--success)' }}>{money(revToday)}</span>
            </div>
            <div className="row between" style={{ marginBottom: 10 }}>
              <span className="row" style={{ gap: 8, fontSize: 12.5 }}><span className="d" style={{ width: 8, height: 8, borderRadius: 99, background: 'var(--text-3)' }} />A receber</span>
              <span className="mono" style={{ fontWeight: 600 }}>{money(pendingSum)}</span>
            </div>
            <hr className="divider" style={{ margin: '12px 0' }} />
            <div className="row between">
              <span style={{ fontSize: 13, fontWeight: 600 }}>Saldo do dia</span>
              <span className="mono" style={{ fontWeight: 700, fontSize: 16, fontFamily: 'var(--font-display)' }}>{money(revToday)}</span>
            </div>
          </div>
        )}

        <div className="card card-pad" style={{ background: 'linear-gradient(150deg, var(--primary), #6b84ff)', color: '#fff', border: 'none', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', right: -30, top: -30, width: 140, height: 140, borderRadius: 99, background: 'rgba(255,255,255,.1)' }} />
          <div style={{ position: 'relative' }}>
            <div className="row" style={{ gap: 8, marginBottom: 10 }}><I1 name="zap" size={18} /><span style={{ fontSize: 13, fontWeight: 600, opacity: .9 }}>Ações rápidas</span></div>
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4, fontFamily: 'var(--font-display)' }}>
              {pendCount > 0 ? `Tem ${pendCount} confirmações pendentes` : 'Tudo confirmado por hoje 🎉'}
            </div>
            <div style={{ fontSize: 12.5, opacity: .85, marginBottom: 16 }}>Envie lembretes por WhatsApp para reduzir faltas.</div>
            <button className="btn" style={{ background: 'rgba(255,255,255,.18)', color: '#fff', backdropFilter: 'blur(4px)' }}
              onClick={() => {
                const first = active.find(a => a.status === 'pendente');
                const c = first && cli(first.clientId);
                if (c) window.waOpen(c.phone, `Olá, ${c.name.split(' ')[0]}! Passando para confirmar seu horário de hoje às ${first.start}. Podemos confirmar?`);
                else ctx.toast('Nenhuma confirmação pendente hoje', 'check');
              }}>
              <I1 name="whatsapp" size={16} /> Enviar lembretes
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
