/* Flow-OS — Pages: Overview, Department detail, Recommendations, Reports */

// Dense HRV chart — 10× density vertical lines + dotted trend overlay
function DenseHRVChart({ data, width = 760, height = 160, accent = 'var(--green)' }) {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data) * 1.15;
  const min = Math.min(...data) * 0.7;
  const range = max - min;
  const padTop = 18;
  const padBot = 6;
  const innerH = height - padTop - padBot;
  const stepX = width / (data.length - 1);

  // moving average for trend (window 12)
  const win = 12;
  const trend = data.map((_, i) => {
    const s = Math.max(0, i - Math.floor(win / 2));
    const e = Math.min(data.length, i + Math.ceil(win / 2));
    let sum = 0;
    for (let k = s; k < e; k++) sum += data[k];
    return sum / (e - s);
  });

  const yOf = (v) => padTop + innerH - ((v - min) / range) * innerH;

  // baseline at index ~ first 20% sample mean
  const baseSamples = data.slice(0, Math.floor(data.length * 0.18));
  const baseY = yOf(baseSamples.reduce((a, b) => a + b, 0) / baseSamples.length);

  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block' }}>
      {/* baseline */}
      <line x1={0} y1={baseY} x2={width} y2={baseY}
        stroke="var(--ink-4)" strokeWidth={1} strokeDasharray="2 4" opacity={0.5} />
      <text x={width - 4} y={baseY - 4} textAnchor="end"
        fontFamily="var(--mono)" fontSize={9} fill="var(--ink-4)" letterSpacing="0.08em">BASELINE 48 ms</text>

      {/* dense vertical ticks */}
      {data.map((v, i) => {
        const x = i * stepX;
        const y = yOf(v);
        const isMidnight = i % 10 === 0; // every "day" boundary
        return (
          <line key={i} x1={x} y1={height - padBot} x2={x} y2={y}
            stroke={isMidnight ? 'var(--ink)' : 'rgba(15,15,14,0.55)'}
            strokeOpacity={isMidnight ? 0.85 : 0.55}
            strokeWidth={isMidnight ? 1.4 : 1.1}
            strokeLinecap="round" />
        );
      })}

      {/* dotted trend polyline (top overlay) */}
      <polyline
        fill="none"
        stroke={accent}
        strokeWidth={1.8}
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeDasharray="1 5"
        points={trend.map((v, i) => `${i * stepX},${yOf(v)}`).join(' ')}
      />
      {/* trend dots */}
      {trend.map((v, i) => {
        if (i % 8 !== 0) return null;
        return <circle key={i} cx={i * stepX} cy={yOf(v)} r={2.2} fill={accent} />;
      })}

      {/* current marker */}
      <circle cx={(data.length - 1) * stepX} cy={yOf(data[data.length - 1])} r={4} fill="var(--ink)" />
      <circle cx={(data.length - 1) * stepX} cy={yOf(data[data.length - 1])} r={7} fill="var(--ink)" opacity={0.15} />
    </svg>
  );
}


// =============== OVERVIEW PAGE ===============
function OverviewPage() {
  const route = useRoute();
  const [period, setPeriod] = useS('week');
  const [tab, setTab] = useS('flow');

  const flowGlobal = 64;
  const periodLabel = { day: 'HOY', week: 'ESTA SEMANA', month: 'ESTE MES', quarter: 'TRIMESTRE' };
  const heatTeams = TEAMS.slice().sort((a, b) => b.flow - a.flow);

  return (
    <div style={{ padding: '28px 32px 60px', display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Hero header */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 18, alignItems: 'flex-start' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>NEUROTROPY · {periodLabel[period]} · 138 PERSONAS · 82% OPT-IN</div>
          <div style={{ fontFamily: 'var(--serif)', fontSize: 64, lineHeight: 1.0, marginTop: 10, letterSpacing: '-0.02em' }}>Overview Panel</div>
          <div style={{ display: 'flex', gap: 12, marginTop: 18, alignItems: 'center' }}>
            <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 999 }}>
              {[
                { id: 'day', l: 'Día' }, { id: 'week', l: 'Semana' }, { id: 'month', l: 'Mes' }, { id: 'quarter', l: 'Trim.' }
              ].map(p => (
                <button key={p.id} onClick={() => setPeriod(p.id)} style={{
                  padding: '6px 14px', borderRadius: 999, border: 'none',
                  background: period === p.id ? 'var(--ink)' : 'transparent',
                  color: period === p.id ? '#fff' : 'var(--ink-3)',
                  fontSize: 12, cursor: 'pointer', fontFamily: 'var(--sans)'
                }}>{p.l}</button>
              ))}
            </div>
            <div className="pill" style={{ background: 'var(--bg-card)' }}>
              <span className="dot" style={{ background: 'var(--green)' }}></span>
              EN VIVO · sync 4 min
            </div>
            <button style={{ padding: '6px 14px', borderRadius: 999, border: '1px solid var(--line)', background: 'var(--bg-card)', fontSize: 12, fontFamily: 'var(--mono)', cursor: 'pointer' }}>📅 02 May 2026</button>
            <button onClick={() => route.go('reports')} style={{ padding: '6px 14px', borderRadius: 999, border: '1px solid var(--line)', background: 'var(--bg-card)', fontSize: 12, fontFamily: 'var(--mono)', cursor: 'pointer', marginLeft: 'auto' }}>Exportar PDF ↗</button>
          </div>
        </div>
        <InsightCard
          title="FLOW INSIGHTS"
          accent="green"
          body={<>El mes pasado, las pausas guiadas ahorraron <strong style={{ fontWeight: 600 }}>48,3 h</strong> de productividad perdida y evitaron <strong style={{ fontWeight: 600 }}>2 alertas rojas</strong>.</>}
          actionLabel="Ver detalle"
          onAction={() => route.go('reports')}
        />
      </div>

      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 14 }}>
        <FlowScoreKpi value={flowGlobal} delta={-4} onClick={() => setTab('flow')} />
        <KpiBox label="Recovery medio" value="64" unit="/100" trend={-3} sub="3 equipos < 60" status={64} />
        <KpiBox label="Equipos en riesgo" value="2" unit="de 9" sub="1 rojo · 1 amarillo" status={45} avatars />
        <KpiBox label="Ventana de flow" value="JUE" unit="ideal sprint" sub="4 equipos óptimos" status={75} />
      </div>

      {/* Tabs row */}
      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 14, width: 'fit-content' }}>
        {[
          { id: 'flow', l: 'Flow Score' },
          { id: 'recovery', l: 'Recovery' },
          { id: 'sleep', l: 'Sueño' },
          { id: 'hrv', l: 'HRV' },
          { id: 'load', l: 'Carga' }
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 16px', borderRadius: 10, border: 'none',
            background: tab === t.id ? 'var(--ink)' : 'transparent',
            color: tab === t.id ? '#fff' : 'var(--ink-3)',
            fontSize: 13, cursor: 'pointer', fontFamily: 'var(--sans)', fontWeight: 500
          }}>{t.l}</button>
        ))}
      </div>

      {/* Heatmap big card */}
      <div style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 22, padding: 28 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>MAPA DE CALOR · {tab.toUpperCase()} DIARIO · ÚLTIMAS 5 SEMANAS</div>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 28, marginTop: 6 }}>Estado por departamento</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>0</span>
            <div style={{ width: 140, height: 6, borderRadius: 3, background: 'linear-gradient(90deg, #e1473d, #e8b53a 50%, #2ea66a)' }}></div>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>100</span>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr 80px 80px', gap: 18, alignItems: 'center', paddingBottom: 8, borderBottom: '1px solid var(--line)', fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-4)', letterSpacing: '0.1em' }}>
          <span>EQUIPO</span>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(20, 1fr)', gap: 2 }}>
            <span style={{ gridColumn: '1 / span 5', textAlign: 'left' }}>S15</span>
            <span style={{ gridColumn: '6 / span 5', textAlign: 'left' }}>S16</span>
            <span style={{ gridColumn: '11 / span 5', textAlign: 'left' }}>S17</span>
            <span style={{ gridColumn: '16 / span 5', textAlign: 'left' }}>S18</span>
          </div>
          <span style={{ textAlign: 'right' }}>FLOW</span>
          <span style={{ textAlign: 'right' }}>SEM 7D</span>
        </div>

        {heatTeams.map((d, i) => {
          const seed = i * 7 + 13;
          const cells = Array.from({ length: 20 }, (_, j) => {
            const noise = ((seed + j * 17) % 100) / 100;
            const base = d.flow + (noise - 0.5) * 30;
            return Math.max(15, Math.min(95, base));
          });
          return (
            <div key={d.id} onClick={() => route.goDept(d.id)} style={{
              display: 'grid', gridTemplateColumns: '220px 1fr 80px 80px', gap: 18, alignItems: 'center',
              padding: '12px 0', borderBottom: i < heatTeams.length - 1 ? '1px solid var(--line)' : 'none',
              cursor: 'pointer', borderRadius: 4
            }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(0,0,0,0.02)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <StatusDot value={d.flow} size={10} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{d.name}{d.sub && <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}> · {d.sub}</span>}</div>
                  <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)', marginTop: 2, letterSpacing: '0.08em' }}>{d.size} PERSONAS</div>
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(20, 1fr)', gap: 2 }}>
                {cells.map((v, j) => (
                  <div key={j} className="heat-cell" style={{
                    aspectRatio: '1/1.4', background: statusColor(v).bg,
                    opacity: 0.4 + (v / 100) * 0.6
                  }}></div>
                ))}
              </div>
              <div style={{ textAlign: 'right', fontFamily: 'var(--serif)', fontSize: 22, color: statusColor(d.flow).text }}>{d.flow}</div>
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <MiniSpark data={d.trend} width={70} height={26} color={statusColor(d.flow).bg} />
              </div>
            </div>
          );
        })}
      </div>

      {/* Bottom row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
        {[
          { team: TEAMS.find(t => t.id === 'product'), label: 'Mayor riesgo' },
          { team: TEAMS.find(t => t.id === 'sales'), label: 'En vigilancia' },
          { team: TEAMS.find(t => t.id === 'eng-be'), label: 'Mejor recuperado' }
        ].map((c, i) => (
          <TeamSpotlightCard key={i} team={c.team} label={c.label} onClick={() => route.goDept(c.team.id)} />
        ))}
      </div>
    </div>
  );
}

function FlowScoreKpi({ value, delta, onClick }) {
  const c = statusColor(value);
  return (
    <div onClick={onClick} style={{
      background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 18, padding: 22,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'relative', overflow: 'hidden', cursor: 'pointer'
    }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: c.bg }}></div>
      <div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>FLOW SCORE GLOBAL</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 8 }}>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 76, lineHeight: 0.9, color: c.text }}>{value}</span>
          <span className="mono" style={{ fontSize: 12, color: delta < 0 ? 'var(--red)' : 'var(--green)' }}>{delta > 0 ? '▲' : '▼'} {Math.abs(delta)}</span>
        </div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 6 }}>vs SEMANA 17 · 68</div>
      </div>
      <FlowGauge value={value} size={170} label="" />
    </div>
  );
}

function KpiBox({ label, value, unit, trend, sub, status, avatars }) {
  const c = statusColor(status);
  return (
    <div style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 18, padding: 20, position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: c.bg }}></div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: 'var(--ink-3)', textTransform: 'uppercase' }}>{label}</span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3)" strokeWidth="1.5"><path d="M7 17 17 7M9 7h8v8"/></svg>
      </div>
      <div style={{ marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 6 }}>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 48, lineHeight: 1 }}>{value}</span>
        <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{unit}</span>
      </div>
      <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)' }}>
        <span>{sub}</span>
        {avatars ? (
          <div style={{ display: 'flex', marginLeft: 6 }}>
            {['EV', 'AM', 'JL'].map((i, k) => (
              <div key={k} style={{ marginLeft: k === 0 ? 0 : -8 }}><Avatar initials={i} size={20} /></div>
            ))}
          </div>
        ) : (
          trend !== undefined && <span className="mono" style={{ color: trend < 0 ? 'var(--red)' : 'var(--green)', fontSize: 10 }}>{trend > 0 ? '▲' : '▼'}{Math.abs(trend)}%</span>
        )}
      </div>
    </div>
  );
}

function TeamSpotlightCard({ team, label, onClick }) {
  const c = statusColor(team.flow);
  return (
    <div onClick={onClick} style={{
      background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 18, padding: 22, cursor: 'pointer',
      transition: 'transform 0.15s'
    }}
      onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="pill" style={{ background: c.bg === 'var(--red)' ? 'var(--red-soft)' : c.bg === 'var(--amber)' ? 'var(--amber-soft)' : 'var(--green-soft)', borderColor: 'transparent', color: c.text }}>
          <span className="dot" style={{ background: c.bg }}></span>
          {label}
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3)" strokeWidth="2"><path d="M7 17 17 7M9 7h8v8"/></svg>
      </div>
      <div style={{ marginTop: 16 }}>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 24 }}>{team.name}{team.sub && ` · ${team.sub}`}</div>
        <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)', marginTop: 4, letterSpacing: '0.1em' }}>{team.size} PERSONAS</div>
      </div>
      <div style={{ marginTop: 18, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)', letterSpacing: '0.1em' }}>FLOW SCORE</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 44, color: c.text, lineHeight: 1 }}>{team.flow}</span>
            <span className="mono" style={{ fontSize: 10, color: team.delta < 0 ? 'var(--red)' : 'var(--green)' }}>{team.delta > 0 ? '+' : ''}{team.delta}</span>
          </div>
        </div>
        <MiniSpark data={team.trend} width={100} height={36} color={c.bg} fill />
      </div>
    </div>
  );
}

// =============== DEPARTMENT DETAIL PAGE ===============
function DepartmentPage() {
  const route = useRoute();
  const team = TEAMS.find(t => t.id === route.deptId) || TEAMS[0];
  const c = statusColor(team.flow);
  const hrvData = [44, 48, 51, 47, 52, 49, 46, 43, 41, 44, 42, 38, 40];
  // Build 3 datasets — 7d / 30d / 90d — densified for the chart
  const seedFn = (i) => ((i * 9301 + 49297) % 233280) / 233280;
  const buildDense = (samples, density = 10) => {
    const out = [];
    for (let i = 0; i < samples.length - 1; i++) {
      for (let k = 0; k < density; k++) {
        const t = k / density;
        const interp = samples[i] * (1 - t) + samples[i + 1] * t;
        const noise = (seedFn(i * density + k) - 0.5) * 4;
        out.push(Math.max(28, interp + noise));
      }
    }
    out.push(samples[samples.length - 1]);
    return out;
  };
  // 7-day base sample (last 7 days of decline)
  const data7  = [46, 44, 43, 41, 44, 42, 40];
  // 30-day base sample (gentle drift then steeper decline last week)
  const data30 = (() => {
    const arr = [];
    for (let i = 0; i < 30; i++) {
      const baseline = 50 + Math.sin(i * 0.45) * 3;
      const drift = i < 22 ? 0 : -(i - 22) * 1.4;
      const noise = (seedFn(i + 100) - 0.5) * 3;
      arr.push(baseline + drift + noise);
    }
    return arr;
  })();
  // 90-day base sample (slow erosion)
  const data90 = (() => {
    const arr = [];
    for (let i = 0; i < 90; i++) {
      const baseline = 54 + Math.cos(i * 0.18) * 4;
      const drift = -(i / 90) * 10;
      const noise = (seedFn(i + 500) - 0.5) * 3;
      arr.push(baseline + drift + noise);
    }
    return arr;
  })();
  const PERIODS = {
    '7d':  { label: '7 DÍAS',  data: buildDense(data7, 7),  avg: 41, delta: -6,  baseline: 48, range: ['26 ABR', '4 MAY'], days: 7,  startDay: 28 },
    '30d': { label: '30 DÍAS', data: buildDense(data30, 7), avg: 47, delta: -3,  baseline: 50, range: ['3 ABR',  '4 MAY'], days: 30, startDay: 4 },
    '90d': { label: '90 DÍAS', data: buildDense(data90, 1), avg: 49, delta: -10, baseline: 54, range: ['3 FEB',  '4 MAY'], days: 90, startDay: 3 }
  };
  const [period, setPeriod] = useS('7d');
  const cur = PERIODS[period];
  const [actionApplied, setActionApplied] = useS(false);

  return (
    <div style={{ padding: '28px 32px 60px', display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Breadcrumb + title */}
      <div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
            <button onClick={() => route.back()} style={{ background: 'transparent', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)', padding: 0 }}>
              ← Volver
            </button>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>/</span>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.1em' }}>DEPARTAMENTO</span>
          </div>
          <div style={{ display: 'flex', flexShrink: 0 }}>
            {['EV', 'AM', 'JL', 'DR', 'KP'].map((i, k) => (
              <div key={k} style={{ marginLeft: k === 0 ? 0 : -10 }}><Avatar initials={i} size={32} /></div>
            ))}
            <div style={{ marginLeft: -10, width: 32, height: 32, borderRadius: '50%', background: 'var(--ink)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontFamily: 'var(--mono)', border: '1.5px solid var(--bg)' }}>+{team.size - 5}</div>
          </div>
        </div>
        <div>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }} className="dept-title-row">
              <span style={{ fontFamily: 'var(--serif)', fontSize: 64, lineHeight: 1, letterSpacing: '-0.02em' }}>{team.name}</span>
              {team.sub && <span style={{ fontFamily: 'var(--serif)', fontSize: 36, color: 'var(--ink-3)' }}>· {team.sub}</span>}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, rowGap: 10, marginTop: 14, flexWrap: 'wrap' }} className="dept-meta-row">
              <div className="pill" style={{ background: c.bg === 'var(--red)' ? 'var(--red-soft)' : c.bg === 'var(--amber)' ? 'var(--amber-soft)' : 'var(--green-soft)', borderColor: 'transparent', color: c.text, padding: '6px 12px', fontSize: 11, whiteSpace: 'nowrap', flex: '0 0 auto' }}>
                <span className="dot" style={{ background: c.bg }}></span>
                {team.flow >= 70 ? 'EN FLOW' : team.flow >= 55 ? 'CARGA ELEVADA' : 'RIESGO BURNOUT'}
              </div>
              <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', whiteSpace: 'nowrap', flex: '0 0 auto' }}>{team.size} PERSONAS · K-MIN ✓</span>
              <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', flex: '0 0 auto' }}>·</span>
              <span className="mono dept-sync-line" style={{ fontSize: 11, color: 'var(--ink-3)', whiteSpace: 'nowrap', flex: '0 0 auto', display: 'inline-flex', alignItems: 'center', gap: 6 }}><span className="dept-sync-dot" style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--green)' }}></span>SYNC HACE 4 MIN</span>
            </div>
          </div>
        </div>
      </div>

      {/* Hero recommendation */}
      {team.status !== 'green' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 18 }}>
          <div className="dept-hero-card" style={{ background: 'var(--ink)', color: '#fff', borderRadius: 22, padding: 26, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, width: 4, background: c.bg }}></div>
            <div className="mono dept-hero-label" style={{ fontSize: 10, letterSpacing: '0.14em', color: team.status === 'red' ? 'var(--red)' : 'var(--amber)' }}>
              {team.status === 'red' ? 'ALERTA ROJA · BURNOUT INMINENTE' : 'ALERTA AMARILLA · CARGA SOSTENIDA'}
            </div>
            <div className="dept-hero-headline" style={{ fontFamily: 'var(--serif)', fontSize: 36, lineHeight: 1.1, marginTop: 14, textWrap: 'balance' }}>
              {team.status === 'red'
                ? `${team.size} personas llevan 10 días con degradación sostenida. Una pausa de recuperación devolvería al equipo a zona de flow en ~14 días.`
                : `Recovery medio ${team.recovery} durante 6 días tras lanzamiento. Reducir cadencia esta semana evitaría la transición a alerta roja.`}
            </div>
            <div className="dept-hero-actions" style={{ display: 'flex', gap: 8, marginTop: 22 }}>
              <button onClick={() => setActionApplied(true)} style={{
                padding: '12px 22px', borderRadius: 12, border: 'none',
                background: actionApplied ? 'var(--green-bright)' : '#fff', color: 'var(--ink)',
                fontSize: 13, fontWeight: 500, cursor: 'pointer'
              }}>{actionApplied ? '✓ Aplicado' : 'Aplicar pausa de recuperación'}</button>
              <button onClick={() => route.go('recommendations')} style={{
                padding: '12px 22px', borderRadius: 12, border: '1px solid rgba(255,255,255,0.2)',
                background: 'transparent', color: '#fff', fontSize: 13, cursor: 'pointer'
              }}>Ver todas las opciones →</button>
            </div>
          </div>
          <InsightCard
            title="VENTANA SUGERIDA"
            accent={team.status === 'red' ? 'amber' : 'green'}
            body={team.status === 'red' ? 'Pausa de 5 días + retomar progresivamente. Sprint posible a partir del 16 may.' : 'Bloquear martes mañana. Stand-up asíncrono 2 días/sem.'}
          />
        </div>
      )}

      {/* Metrics grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        {[
          { l: 'Recovery', v: team.recovery, u: '/100', s: team.recovery, t: team.delta },
          { l: 'HRV equipo', v: 42, u: 'ms', s: 50, t: team.hrv },
          { l: 'Sueño', v: team.sleep, u: '', s: 45, t: -12 },
          { l: 'Carga', v: team.status === 'red' ? 'Alta' : team.status === 'amber' ? 'Media' : 'Normal', u: '', s: team.flow }
        ].map((m, i) => (
          <KpiBox key={i} label={m.l} value={m.v} unit={m.u} trend={m.t} status={m.s} sub={m.t !== undefined ? `vs línea base` : '7 días sostenida'} />
        ))}
      </div>

      {/* Charts section */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14 }}>
        <div style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 22, padding: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }} className="hrv-card-head">
            <div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>HRV · {cur.label}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 6, flexWrap: 'nowrap', whiteSpace: 'nowrap' }} className="hrv-headline">
                <span style={{ fontFamily: 'var(--serif)', fontSize: 48, lineHeight: 1 }}>{cur.avg}</span>
                <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>ms</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--red)', marginLeft: 8, whiteSpace: 'nowrap' }}>▼ {Math.abs(cur.delta)} ms vs baseline</span>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 10 }}>
              {['7d', '30d', '90d'].map((p) => (
                <button key={p} onClick={() => setPeriod(p)} style={{
                  padding: '4px 12px', borderRadius: 6, border: 'none',
                  background: period === p ? 'var(--ink)' : 'transparent',
                  color: period === p ? '#fff' : 'var(--ink-3)',
                  fontSize: 11, cursor: 'pointer', fontFamily: 'var(--mono)', transition: 'background 220ms, color 220ms'
                }}>{p}</button>
              ))}
            </div>
          </div>
          <div key={period} className="hrv-anim">
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 6 }}>
              <span className="mono" style={{ background: 'var(--ink)', color: '#fff', padding: '2px 7px', borderRadius: 3, fontSize: 9 }}>HOY</span>
            </div>
            <div style={{ width: '100%' }}>
              <TickBars data={cur.data} width={760} height={160} accent="var(--green)" baselineIdx={Math.floor(cur.data.length / 3)} responsive colorByValue />
            </div>
            {(() => {
              // Build day labels — 7d shows all 7, 30d shows 30 (every 3rd labeled), 90d shows weekly markers
              const days = cur.days;
              const start = cur.startDay;
              const MONTH_NAMES = ['ENE', 'FEB', 'MAR', 'ABR', 'MAY', 'JUN', 'JUL', 'AGO', 'SEP', 'OCT', 'NOV', 'DIC'];
              const showLabel = days <= 7 ? () => true : days <= 30 ? (i) => i % 3 === 0 || i === days - 1 : (i) => i % 7 === 0 || i === days - 1;
              // Compute (day, month) for each index
              const dayInfo = [];
              for (let i = 0; i < days; i++) {
                let day, m;
                if (days === 7) {
                  // Apr 28..30 then May 1..4
                  day = start + i;
                  m = 3; // April
                  if (day > 30) { day = day - 30; m = 4; }
                } else if (days === 30) {
                  // Apr 5..30 then May 1..4
                  day = 5 + i;
                  m = 3;
                  if (day > 30) { day = day - 30; m = 4; }
                } else {
                  // 90d — Feb 3 → May 4
                  day = 3 + i;
                  m = 1; // Feb
                  while (true) {
                    const dim = m === 1 ? 28 : m === 2 ? 31 : m === 3 ? 30 : 31;
                    if (day > dim) { day -= dim; m++; } else break;
                  }
                }
                dayInfo.push({ day, month: MONTH_NAMES[m] });
              }
              return (
                <div style={{ display: 'grid', gridTemplateColumns: `repeat(${days}, 1fr)`, marginTop: 8, fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-4)' }}>
                  {dayInfo.map((info, i) => {
                    const isEdge = i === 0 || i === days - 1;
                    return (
                      <span key={i} style={{ textAlign: 'center', visibility: showLabel(i) ? 'visible' : 'hidden' }}>
                        {isEdge ? `${info.day} ${info.month}` : info.day}
                      </span>
                    );
                  })}
                </div>
              );
            })()}
          </div>
        </div>

        <div style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 22, padding: 24 }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)', marginBottom: 18 }}>COMPOSICIÓN FLOW</div>
          {[
            { label: 'Recovery', value: team.recovery, weight: 35 },
            { label: 'Consistencia sueño', value: 51, weight: 25 },
            { label: 'Picos estrés', value: 72, weight: 20 },
            { label: 'Cadencia trabajo', value: 67, weight: 20 }
          ].map((m, i) => {
            const cc = statusColor(m.value);
            return (
              <div key={i} style={{ marginBottom: i === 3 ? 0 : 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13 }}>
                  <span>{m.label} <span className="mono" style={{ color: 'var(--ink-4)', fontSize: 10 }}>·{m.weight}%</span></span>
                  <span className="mono" style={{ color: cc.text, fontSize: 13 }}>{m.value}</span>
                </div>
                <div style={{ height: 6, background: 'var(--line)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ width: `${m.value}%`, height: '100%', background: cc.bg, transition: 'width 0.4s' }}></div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Other teams strip */}
      <div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)', marginBottom: 12 }}>OTROS DEPARTAMENTOS</div>
        <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 4 }}>
          {TEAMS.filter(t => t.id !== team.id).map(t => {
            const tc = statusColor(t.flow);
            return (
              <div key={t.id} onClick={() => route.goDept(t.id)} style={{
                flexShrink: 0, padding: '14px 18px', background: 'var(--bg-card)', border: '1px solid var(--line)',
                borderRadius: 14, cursor: 'pointer', minWidth: 200, display: 'flex', alignItems: 'center', gap: 12
              }}>
                <StatusDot value={t.flow} size={10} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}{t.sub && ` · ${t.sub}`}</div>
                  <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)' }}>{t.size}p · Δ{t.delta > 0 ? '+' : ''}{t.delta}</div>
                </div>
                <span style={{ fontFamily: 'var(--serif)', fontSize: 22, color: tc.text }}>{t.flow}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// =============== RECOMMENDATIONS PAGE ===============
function RecommendationsPage() {
  const route = useRoute();
  const [filter, setFilter] = useS('all');
  const [applied, setApplied] = useS({});
  const recs = [
    { id: 'r1', sev: 'red', team: TEAMS.find(t => t.id === 'product'), verdict: 'Pausa de recuperación obligatoria', why: 'HRV colectivo ↓12% sostenido durante 10 días. Recovery 58. Sleep deficit 1h 18m por persona.', actions: [
      { l: 'Cancelar reuniones no críticas hasta el viernes', impact: '+8' },
      { l: 'Posponer release v3.2 una semana', impact: '+5' },
      { l: 'Habilitar viernes off compensatorio', impact: '+4' }
    ], from: 41, to: 62, window: '8–14 días' },
    { id: 'r2', sev: 'amber', team: TEAMS.find(t => t.id === 'sales'), verdict: 'Reducir carga · revisar cadencia', why: 'Recovery medio bajo (56) durante 6 días tras lanzamiento Q2. Picos de estrés en martes y jueves.', actions: [
      { l: 'Bloquear martes mañana sin reuniones', impact: '+3' },
      { l: 'Mover stand-up a asíncrono 2 días/sem', impact: '+2' }
    ], from: 54, to: 64, window: '5–7 días' },
    { id: 'r3', sev: 'green', team: TEAMS.find(t => t.id === 'eng-be'), verdict: 'Ventana óptima para sprint intensivo', why: 'HRV +4ms vs línea base. Sueño 7h 32m. Recovery 74. Condiciones ideales.', actions: [
      { l: 'Lanzar sprint de migración esta semana', impact: '✓' },
      { l: 'Ventana de flow: jueves 9–13h', impact: '✓' }
    ], from: 78, to: 78, window: 'Lun–Jue' },
    { id: 'r4', sev: 'amber', team: TEAMS.find(t => t.id === 'cs'), verdict: 'Revisar carga emocional', why: 'HRV bajando 8% en 7 días. Sueño −22 min vs media.', actions: [
      { l: 'Sesión de descompresión grupal viernes', impact: '+2' }
    ], from: 59, to: 64, window: '3–5 días' }
  ];

  const colors = {
    red: { bg: 'var(--red)', soft: 'var(--red-soft)', l: 'CRÍTICO' },
    amber: { bg: 'var(--amber)', soft: 'var(--amber-soft)', l: 'AVISO' },
    green: { bg: 'var(--green)', soft: 'var(--green-soft)', l: 'OPORTUNIDAD' }
  };

  const filtered = filter === 'all' ? recs : recs.filter(r => r.sev === filter);

  return (
    <div style={{ padding: '28px 32px 60px', display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 18, alignItems: 'flex-start' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>MOTOR DE RECOMENDACIONES · GENERADO HOY 06:14</div>
          <div className="recs-headline" style={{ fontFamily: 'var(--serif)', fontSize: 56, lineHeight: 1.0, marginTop: 8, letterSpacing: '-0.02em', textWrap: 'balance' }}>
            {recs.length} acciones para tu organización esta semana.
          </div>
          <div className="recs-filters" style={{ display: 'flex', gap: 6, marginTop: 18, flexWrap: 'wrap' }}>
            {[
              { id: 'all', l: `Todas · ${recs.length}`, hideMob: true },
              { id: 'red', l: `Críticas (${recs.filter(r => r.sev === 'red').length})`, c: 'var(--red)' },
              { id: 'amber', l: `Aviso (${recs.filter(r => r.sev === 'amber').length})`, c: 'var(--amber)' },
              { id: 'green', l: `Oportunidad (${recs.filter(r => r.sev === 'green').length})`, c: 'var(--green)' }
            ].map(f => (
              <button key={f.id} onClick={() => setFilter(f.id)} className={f.hideMob ? 'recs-filter-all' : ''} style={{
                padding: '7px 14px', borderRadius: 999, border: '1px solid ' + (filter === f.id ? 'var(--ink)' : 'var(--line)'),
                background: filter === f.id ? 'var(--ink)' : 'var(--bg-card)',
                color: filter === f.id ? '#fff' : 'var(--ink-2)',
                fontSize: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8
              }}>
                {f.c && <span className="dot" style={{ background: f.c }}></span>}
                {f.l}
              </button>
            ))}
          </div>
        </div>
        <InsightCard
          title="IMPACTO POTENCIAL"
          accent="green"
          body={<>Aplicar las 3 acciones priorizadas elevaría el Flow Score global <strong>+11 puntos</strong> en 14 días.</>}
        />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {filtered.map(r => {
          const c = colors[r.sev];
          const isApplied = applied[r.id];
          return (
            <div key={r.id} style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 22, overflow: 'hidden', display: 'grid', gridTemplateColumns: '300px 1fr 280px' }}>
              <div style={{ padding: 24, background: c.soft, position: 'relative' }}>
                <div className="pill" style={{ background: '#fff', borderColor: 'transparent', color: c.bg, fontWeight: 600 }}>
                  <span className="dot" style={{ background: c.bg }}></span>
                  {c.l}
                </div>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 26, lineHeight: 1.1, marginTop: 14 }}>{r.team.name}{r.team.sub && ` · ${r.team.sub}`}</div>
                <div className="mono" style={{ fontSize: 9, color: 'var(--ink-3)', marginTop: 8, letterSpacing: '0.1em' }}>VENTANA · {r.window}</div>
                <div style={{ position: 'absolute', bottom: 24, left: 24, right: 24, paddingTop: 14, borderTop: '1px dashed rgba(0,0,0,0.15)' }}>
                  <div style={{ fontFamily: 'var(--serif)', fontSize: 18, lineHeight: 1.2 }}>{r.verdict}</div>
                </div>
              </div>
              <div style={{ padding: 24 }}>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>POR QUÉ</div>
                <div style={{ fontSize: 13, marginTop: 6, lineHeight: 1.5, color: 'var(--ink-2)' }}>{r.why}</div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)', marginTop: 16 }}>ACCIONES</div>
                <div style={{ marginTop: 6 }}>
                  {r.actions.map((a, j) => (
                    <div key={j} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', borderBottom: j < r.actions.length - 1 ? '1px solid var(--line)' : 'none' }}>
                      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', flex: 1 }}>
                        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 2 }}>{String(j + 1).padStart(2, '0')}</span>
                        <span style={{ fontSize: 13 }}>{a.l}</span>
                      </div>
                      <span className="mono" style={{ fontSize: 10, padding: '3px 8px', background: c.soft, color: c.bg, borderRadius: 4, fontWeight: 600 }}>{a.impact}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div style={{ padding: 24, background: 'var(--bg)', borderLeft: '1px solid var(--line)', display: 'flex', flexDirection: 'column' }}>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>PROYECCIÓN · 14D</div>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14 }}>
                  <div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)' }}>HOY</div>
                    <div style={{ fontFamily: 'var(--serif)', fontSize: 38, lineHeight: 1, color: statusColor(r.from).text }}>{r.from}</div>
                  </div>
                  <svg width="80" height="36" viewBox="0 0 80 36">
                    <path d={`M 5 ${36 - r.from * 0.32} Q 40 ${36 - (r.from + r.to) / 2 * 0.36 - 4} 75 ${36 - r.to * 0.32}`} stroke={c.bg} strokeWidth="1.5" fill="none" strokeDasharray="3 3" />
                    <circle cx="5" cy={36 - r.from * 0.32} r="3" fill="var(--ink)" />
                    <circle cx="75" cy={36 - r.to * 0.32} r="3" fill={c.bg} />
                  </svg>
                  <div style={{ textAlign: 'right' }}>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)' }}>POST</div>
                    <div style={{ fontFamily: 'var(--serif)', fontSize: 38, lineHeight: 1, color: statusColor(r.to).text }}>{r.to}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
                  <button onClick={() => setApplied(a => ({ ...a, [r.id]: !isApplied }))} style={{
                    flex: 1, padding: '11px 14px', borderRadius: 10,
                    background: isApplied ? 'var(--green-bright)' : 'var(--ink)', color: isApplied ? 'var(--ink)' : '#fff',
                    border: 'none', fontSize: 12, fontWeight: 500, cursor: 'pointer'
                  }}>{isApplied ? '✓ Aplicado' : 'Aplicar'}</button>
                  <button onClick={() => route.goDept(r.team.id)} style={{
                    padding: '11px 14px', borderRadius: 10, background: 'transparent', border: '1px solid var(--line)',
                    fontSize: 12, cursor: 'pointer'
                  }}>Detalle</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// =============== REPORTS PAGE ===============
function ReportsPage() {
  return (
    <div style={{ padding: '28px 32px 60px' }}>
      <div style={{ marginBottom: 24 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>INFORMES EJECUTIVOS · ARCHIVO</div>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 56, lineHeight: 1.0, marginTop: 8 }}>Informes semanales</div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <div style={{ transform: 'scale(0.95)', transformOrigin: 'top center' }}>
          <ExecutiveReport />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OverviewPage, DepartmentPage, RecommendationsPage, ReportsPage });
