// Gráficos (CSS/SVG simples) + vistas Resumen y Reportes
function StackedBars({ months, keys }) {
  const max = Math.max(4, ...months.map(m => m.total));
  const nice = Math.ceil(max / 4) * 4;
  return (
    <div>
      <div className="ga-bars">
        <div className="ga-bars-grid">{[4, 3, 2, 1, 0].map(i => <span key={i} />)}</div>
        {months.map(m => (
          <div className="ga-bar" key={m.m} title={`${m.m}: ${m.total} solicitudes`}>
            <span className="ga-bar-n">{m.total}</span>
            <div className="ga-bar-stack" style={{ height: (m.total / nice * 100) + '%' }}>
              {keys.map(k => m.by[k] ? <span key={k} style={{ height: (m.by[k] / m.total * 100) + '%', background: S.STATUS[k].color }} /> : null)}
            </div>
          </div>
        ))}
      </div>
      <div className="ga-bar-x">{months.map(m => <span key={m.m}>{m.m}</span>)}</div>
    </div>
  );
}

function Donut({ by, total }) {
  let acc = 0;
  const segs = S.STATUSES.map(s => { const from = acc; acc += total ? by[s.id] / total * 360 : 0; return `${s.color} ${from}deg ${acc}deg`; });
  return (
    <div className="ga-donut">
      <div className="ga-donut-c" style={{ background: total ? `conic-gradient(${segs.join(',')})` : 'var(--gray-100)' }}>
        <span className="ga-donut-hole" /><div><b className="tnum">{total}</b><small>solicitudes</small></div>
      </div>
      <div className="ga-donut-l">
        {S.STATUSES.map(s => <div key={s.id}><i style={{ background: s.color }} />{s.label}<b className="tnum">{by[s.id]}</b><em className="tnum">{total ? Math.round(by[s.id] / total * 100) : 0}%</em></div>)}
      </div>
    </div>
  );
}

function ProvBars({ prov, onPick }) {
  const max = Math.max(1, ...prov.map(p => p.n));
  return (
    <div className="ga-hbars">
      {prov.map(p => (
        <div className="ga-hbar" key={p.p} style={{ cursor: onPick ? 'pointer' : 'default' }} onClick={() => onPick && onPick(p.p)}>
          <span>{p.p}</span>
          <div className="ga-hbar-t"><span style={{ width: (p.n / max * 100) + '%' }} /></div>
          <b className="tnum">{p.n}</b>
        </div>
      ))}
    </div>
  );
}

function LineChart({ points, color = '#2245B3', unit = '', yMax }) {
  const W = 600, H = 200, P = { l: 34, r: 12, t: 16, b: 26 };
  const vals = points.map(p => p.v).filter(v => v != null);
  const max = yMax || Math.max(1, Math.ceil(Math.max(...vals, 1) * 1.2));
  const x = i => P.l + (points.length === 1 ? (W - P.l - P.r) / 2 : i * (W - P.l - P.r) / (points.length - 1));
  const y = v => H - P.b - (v / max) * (H - P.t - P.b);
  const pts = points.map((p, i) => p.v == null ? null : [x(i), y(p.v)]).filter(Boolean);
  const d = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = pts.length ? d + ` L ${pts[pts.length - 1][0]} ${H - P.b} L ${pts[0][0]} ${H - P.b} Z` : '';
  return (
    <svg className="ga-line" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" role="img">
      {[0, .25, .5, .75, 1].map(t => <g key={t}>
        <line x1={P.l} x2={W - P.r} y1={y(max * t)} y2={y(max * t)} stroke="#ECEEF2" strokeDasharray={t ? '3 4' : ''} />
        <text x={P.l - 8} y={y(max * t) + 4} fontSize="10.5" fill="#7A8399" textAnchor="end" fontFamily="Poppins">{Math.round(max * t)}</text>
      </g>)}
      <path d={area} fill={color} opacity=".08" />
      <path d={d} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
      {points.map((p, i) => <g key={i}>
        {p.v != null && <circle cx={x(i)} cy={y(p.v)} r="4" fill="#fff" stroke={color} strokeWidth="2.2" vectorEffect="non-scaling-stroke"><title>{`${p.l}: ${p.v.toFixed ? p.v.toFixed(1) : p.v}${unit}`}</title></circle>}
        <text x={x(i)} y={H - 6} fontSize="10.5" fill="#7A8399" textAnchor="middle" fontFamily="Poppins">{p.l}</text>
      </g>)}
    </svg>
  );
}

// ---------- Resumen ----------
function DashboardView({ reqs, user, go, openReq }) {
  const st = computeStats(reqs);
  const stale = S.stale(reqs).sort((a, b) => a.updatedAt.localeCompare(b.updatedAt));
  const mine = reqs.filter(r => r.assignee === user.id && !['aprobada', 'rechazada'].includes(r.status));
  const recent = reqs.slice(0, 6);
  const K = ({ id, label, v, sub, hero, color, filter }) => (
    <button className={'ga-kpi' + (hero ? ' hero' : '') + (filter === undefined ? ' static' : '')} onClick={() => filter !== undefined && go('solicitudes', filter)}>
      <span className="ga-kpi-k">{color && <i style={{ background: color }} />}{label}</span>
      <span className="ga-kpi-v tnum">{v}</span>
      {sub && <span className="ga-kpi-s">{sub}</span>}
    </button>
  );
  const pct = n => st.total ? Math.round(n / st.total * 100) + '% del total' : '—';
  return (
    <>
      <div className="ga-kpis">
        <K hero label="Total de solicitudes" v={st.total} sub="Desde enero 2026" filter={{}} />
        <K label="Nuevas" v={st.by.recibida} sub={pct(st.by.recibida)} color={S.STATUS.recibida.color} filter={{ status: 'recibida' }} />
        <K label="En revisión" v={st.by.revision} sub={pct(st.by.revision)} color={S.STATUS.revision.color} filter={{ status: 'revision' }} />
        <K label="Pendientes de información" v={st.by.pendiente} sub={pct(st.by.pendiente)} color={S.STATUS.pendiente.color} filter={{ status: 'pendiente' }} />
        <K label="Aprobadas" v={st.by.aprobada} sub={pct(st.by.aprobada)} color={S.STATUS.aprobada.color} filter={{ status: 'aprobada' }} />
        <K label="Rechazadas" v={st.by.rechazada} sub={pct(st.by.rechazada)} color={S.STATUS.rechazada.color} filter={{ status: 'rechazada' }} />
        <K label="Tiempo promedio de resolución" v={<>{st.avgDays.toFixed(1)}<small>días</small></>} sub={`${st.resolved} resueltas`} />
      </div>

      <div className="ga-grid2">
        <div className="ga-card">
          <div className="ga-card-h"><div><h2>Solicitudes recibidas por mes</h2><p>2026 · color según estado actual</p></div>
            <div className="ga-legend">{S.STATUSES.map(s => <span key={s.id}><i style={{ background: s.color }} />{s.short || s.label}</span>)}</div></div>
          <div className="ga-card-b"><StackedBars months={st.months} keys={S.STATUSES.map(s => s.id)} /></div>
        </div>
        <div className="ga-card">
          <div className="ga-card-h"><div><h2>Requieren atención</h2><p>Abiertas sin movimiento por más de {S.db.settings.rules.pendingHours} h</p></div>
            {stale.length > 0 && <span className="pill" style={{ color: 'var(--red-ink)', background: 'var(--red-50)' }}>{stale.length}</span>}</div>
          <div className="ga-card-b">
            {stale.length === 0 ? <div className="ga-empty" style={{ padding: 24 }}><b>Todo al día</b>No hay solicitudes atrasadas.</div> :
              <div className="ga-list">
                {stale.slice(0, 5).map(r => (
                  <div className="ga-li" key={r.id} onClick={() => openReq(r.id)}>
                    <StatusPill id={r.status} short />
                    <div className="ga-li-t"><b>{r.negocio.name}</b><span>{r.id} · {r.assignee ? S.userName(r.assignee) : 'Sin asignar'}</span></div>
                    <span className="ga-li-r">{GFmt.rel(r.updatedAt)}</span>
                  </div>
                ))}
                {stale.length > 5 && <button className="btn btn-text btn-sm" style={{ alignSelf: 'flex-start', marginTop: 8, marginLeft: -10 }} onClick={() => go('solicitudes', { stale: true })}>Ver las {stale.length} <Icon name="arrowRight" size={15} /></button>}
              </div>}
          </div>
        </div>
      </div>

      <div className="ga-grid3">
        <div className="ga-card">
          <div className="ga-card-h"><h2>Distribución por estado</h2></div>
          <div className="ga-card-b"><Donut by={st.by} total={st.total} /></div>
        </div>
        <div className="ga-card">
          <div className="ga-card-h"><h2>Solicitudes por provincia</h2></div>
          <div className="ga-card-b"><ProvBars prov={st.prov} onPick={p => go('solicitudes', { prov: p })} /></div>
        </div>
        <div className="ga-card">
          <div className="ga-card-h"><div><h2>Asignadas a mí</h2><p>{mine.length} abiertas</p></div></div>
          <div className="ga-card-b">
            {mine.length === 0 ? <div className="ga-empty" style={{ padding: 24 }}><b>Sin pendientes</b>No tenés solicitudes abiertas asignadas.</div> :
              <div className="ga-list">{mine.slice(0, 5).map(r => (
                <div className="ga-li" key={r.id} onClick={() => openReq(r.id)}>
                  <div className="ga-li-t"><b>{r.negocio.name}</b><span>{r.id} · {GFmt.rel(r.updatedAt)}</span></div>
                  <StatusPill id={r.status} short />
                </div>))}</div>}
          </div>
        </div>
      </div>

      <div className="ga-card">
        <div className="ga-card-h"><h2>Ingresos recientes</h2><button className="btn btn-text btn-sm" onClick={() => go('solicitudes', {})}>Ver todas <Icon name="arrowRight" size={15} /></button></div>
        <div className="ga-card-b" style={{ paddingTop: 8 }}>
          <div className="ga-list">{recent.map(r => (
            <div className="ga-li" key={r.id} onClick={() => openReq(r.id)}>
              <span className="mono" style={{ fontSize: 12.5, color: 'var(--blue)', fontWeight: 600, width: 118, flexShrink: 0 }}>{r.id}</span>
              <div className="ga-li-t"><b>{r.negocio.name}{r.demo && <span className="demo-tag" style={{ fontSize: 10, fontWeight: 600, color: '#8A5A00', background: 'var(--yellow-50)', border: '1px solid var(--yellow-100)', padding: '1px 6px', borderRadius: 4, marginLeft: 6 }}>DEMO</span>}</b><span>{r.responsable.firstName} {r.responsable.lastName} · {r.negocio.provincia}</span></div>
              <span className="ga-hide-sm" style={{ fontSize: 12, color: 'var(--gray-500)' }}>{GFmt.dateTime(r.createdAt)}</span>
              <StatusPill id={r.status} short />
            </div>))}</div>
        </div>
      </div>
    </>
  );
}

// ---------- Reportes ----------
function ReportsView({ reqs, user, toast }) {
  const [range, setRange] = React.useState('all');
  const [prov, setProv] = React.useState('');
  const filtered = reqs.filter(r => {
    if (prov && r.negocio.provincia !== prov) return false;
    if (range === 'all') return true;
    const m = new Date(r.createdAt).getMonth();
    const last = 9;
    return range === 'q' ? m >= last - 2 : range === 'h' ? m >= last - 5 : true;
  });
  const st = computeStats(filtered);
  const months = range === 'q' ? st.months.slice(-3) : range === 'h' ? st.months.slice(-6) : st.months;
  const apr = st.by.aprobada, rej = st.by.rechazada, res = apr + rej;
  return (
    <>
      <div className="ga-card">
        <div className="ga-filters" style={{ borderBottom: 'none' }}>
          <div className="ga-chips" style={{ padding: 0, border: 'none' }}>
            {[['all', 'Todo 2026'], ['h', 'Últimos 6 meses'], ['q', 'Últimos 3 meses']].map(([k, l]) => <button key={k} className={'ga-chip' + (range === k ? ' on' : '')} onClick={() => setRange(k)}>{l}</button>)}
          </div>
          <select className="select" value={prov} onChange={e => setProv(e.target.value)}><option value="">Todas las provincias</option>{PROVS.map(p => <option key={p}>{p}</option>)}</select>
          <div style={{ marginLeft: 'auto' }}><ExportMenu rows={filtered} user={user} toast={toast} /></div>
        </div>
      </div>

      <div className="ga-kpis" style={{ gridTemplateColumns: 'repeat(4,minmax(0,1fr))' }}>
        <div className="ga-kpi static"><span className="ga-kpi-k">Solicitudes en el período</span><span className="ga-kpi-v tnum">{st.total}</span></div>
        <div className="ga-kpi static"><span className="ga-kpi-k"><i style={{ background: S.STATUS.aprobada.color }} />Aprobadas</span><span className="ga-kpi-v tnum">{apr}</span><span className="ga-kpi-s">{res ? Math.round(apr / res * 100) : 0}% de las resueltas</span></div>
        <div className="ga-kpi static"><span className="ga-kpi-k"><i style={{ background: S.STATUS.rechazada.color }} />Rechazadas</span><span className="ga-kpi-v tnum">{rej}</span><span className="ga-kpi-s">{res ? Math.round(rej / res * 100) : 0}% de las resueltas</span></div>
        <div className="ga-kpi static"><span className="ga-kpi-k">Tiempo promedio de gestión</span><span className="ga-kpi-v tnum">{st.avgDays.toFixed(1)}<small>días</small></span><span className="ga-kpi-s">Desde ingreso hasta resolución</span></div>
      </div>

      <div className="ga-grid2">
        <div className="ga-card">
          <div className="ga-card-h"><div><h2>Evolución mensual de solicitudes</h2><p>Ingresos por mes</p></div></div>
          <div className="ga-card-b"><LineChart points={months.map(m => ({ l: m.m, v: m.total }))} /></div>
        </div>
        <div className="ga-card">
          <div className="ga-card-h"><h2>Distribución por estado</h2></div>
          <div className="ga-card-b"><Donut by={st.by} total={st.total} /></div>
        </div>
      </div>

      <div className="ga-grid2">
        <div className="ga-card">
          <div className="ga-card-h"><div><h2>Aprobadas vs. rechazadas por mes</h2><p>Según mes de ingreso</p></div>
            <div className="ga-legend"><span><i style={{ background: S.STATUS.aprobada.color }} />Aprobadas</span><span><i style={{ background: S.STATUS.rechazada.color }} />Rechazadas</span></div></div>
          <div className="ga-card-b"><StackedBars months={months.map(m => ({ ...m, total: m.by.aprobada + m.by.rechazada }))} keys={['aprobada', 'rechazada']} /></div>
        </div>
        <div className="ga-card">
          <div className="ga-card-h"><div><h2>Tiempo promedio de gestión</h2><p>Días por mes de resolución</p></div></div>
          <div className="ga-card-b"><LineChart points={months.map(m => ({ l: m.m, v: m.avg }))} color="#B8530F" unit=" días" /></div>
        </div>
      </div>

      <div className="ga-card">
        <div className="ga-card-h"><h2>Solicitudes por provincia</h2></div>
        <div className="ga-card-b">
          <div className="ga-table-wrap" style={{ display: 'block' }}>
            <table className="ga-table" style={{ minWidth: 640 }}>
              <thead><tr><th>Provincia</th><th>Total</th>{S.STATUSES.map(s => <th key={s.id}>{s.short || s.label}</th>)}<th>Tasa de aprobación</th></tr></thead>
              <tbody>{PROVS.map(p => {
                const rr = filtered.filter(r => r.negocio.provincia === p);
                const c = id => rr.filter(r => r.status === id).length;
                const a = c('aprobada'), j = c('rechazada');
                return <tr key={p} style={{ cursor: 'default' }}><td className="strong">{p}</td><td className="tnum"><b>{rr.length}</b></td>{S.STATUSES.map(s => <td key={s.id} className="tnum muted">{c(s.id)}</td>)}<td className="tnum">{a + j ? Math.round(a / (a + j) * 100) + '%' : '—'}</td></tr>;
              })}</tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { DashboardView, ReportsView, LineChart, Donut, StackedBars, ProvBars });
