/* ============================================================
   REPORTE EJECUTIVO PDF — vista imprimible
   Resumen · Hallazgos · Gráficas · Áreas críticas · Plan de acción
   Exporta: ScreenReport
   ============================================================ */
const IHP = window.IH;

function ScreenReport({ filters, onBack }) {
  const f = filters || { area: 'Todas', sucursal: 'Todas', puesto: 'Todos', periodo: 'Mes actual' };
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const fecha = new Date().toLocaleDateString('es-MX', { day: '2-digit', month: 'long', year: 'numeric' });

  React.useEffect(() => {
    IHA.getDashboardReport(f)
      .then(d => { setData(d); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--paper-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div className="mono" style={{ fontSize: 13, color: 'var(--ink-3)', letterSpacing: '0.08em' }}>Generando reporte…</div>
      </div>
    );
  }

  if (!data) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--paper-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ color: 'var(--risk)', fontSize: 14, marginBottom: 16 }}>Error al cargar los datos del reporte.</div>
          <button className="btn btn-ghost" onClick={onBack}>← Volver al panel</button>
        </div>
      </div>
    );
  }

  const avg = data.scores;
  const areaMap = data.heatmap;
  const dist = data.distribution;
  const rank = data.ranking;
  const reco = data.recommendations;
  const evolIdx = data.summary.evolIndex;
  const diag = { dominant: data.summary.dominant, secondary: data.summary.secondary };
  const list = { length: data.summary.total };
  const critical = [...rank].reverse().slice(0, 2);

  return (
    <div style={{ background: 'var(--paper-2)', minHeight: '100vh' }}>
      <div className="no-print" style={{ position: 'sticky', top: 0, zIndex: 10, background: 'var(--paper)', borderBottom: '1px solid var(--hair)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 40px' }}>
        <button className="btn btn-ghost" onClick={onBack} style={{ fontSize: 13 }}>← Volver al panel</button>
        <span className="eyebrow">Vista de reporte · listo para imprimir</span>
        <button className="btn btn-primary" onClick={() => window.print()} style={{ fontSize: 13 }}>Imprimir / Guardar PDF</button>
      </div>

      <div className="report-pages" style={{ maxWidth: 880, margin: '0 auto', padding: '32px 0 80px' }}>

        {/* —— PÁGINA 1 —— */}
        <div className="rpage">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', borderBottom: '2px solid var(--ink)', paddingBottom: 20, marginBottom: 28 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Reporte ejecutivo · Diagnóstico conductual</div>
              <h1 className="serif" style={{ fontSize: 34, fontWeight: 600, margin: 0, lineHeight: 1.05 }}>Radiografía organizacional</h1>
              <div className="mono" style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 8 }}>
                {f.area} · {f.sucursal} · {f.periodo}
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <Brand small />
              <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)', marginTop: 10 }}>{fecha}</div>
            </div>
          </div>

          {/* resumen ejecutivo */}
          <SectionTitle n="01" title="Resumen ejecutivo" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 14, marginBottom: 22 }}>
            <MiniStat label="Evaluados" value={list.length} />
            <MiniStat label="Índice evolución" value={evolIdx + '/100'} accent="var(--gold)" />
            <MiniStat label="Predominante" value={IHP.byId[diag.dominant].name} accent={IHP.byId[diag.dominant].hex} />
            <MiniStat label="Área líder" value={rank[0]?.area || '—'} accent="var(--good)" />
          </div>
          <p className="serif" style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--ink)', margin: '0 0 8px' }}>
            La organización opera hoy con un índice de evolución de <strong>{evolIdx}/100</strong>. El arquetipo que predomina es <strong style={{ color: IHP.byId[diag.dominant].hex }}>{IHP.byId[diag.dominant].name}</strong>, seguido de {(diag.secondary || []).map(s => IHP.byId[s].name).join(' y ')}. {rank[0] && critical[0] && `El área más evolucionada es ${rank[0].area} (${rank[0].evol}/100), mientras que ${critical[0].area} (${critical[0].evol}/100) concentra la mayor necesidad de intervención.`}
          </p>

          {/* radar + distribución */}
          <SectionTitle n="02" title="Mapa conductual promedio" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, alignItems: 'center', marginBottom: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Radar size={300} series={[{ scores: avg, color: 'var(--gold)', fillOpacity: 0.12 }]} />
            </div>
            <div>
              <AxisLegend scores={avg} />
            </div>
          </div>
        </div>

        {/* —— PÁGINA 2 —— */}
        <div className="rpage">
          <SectionTitle n="03" title="Hallazgos por área · mapa de calor" />
          <div style={{ marginBottom: 26 }}>
            <Heatmap areaMap={areaMap} />
          </div>

          <SectionTitle n="04" title="Ranking de evolución" />
          <div style={{ marginBottom: 26 }}>
            <EvolRanking rows={rank} />
          </div>

          <SectionTitle n="05" title="Áreas críticas" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            {critical.map(c => {
              const d = IHP.diagnose(c.scores);
              return (
                <div key={c.area} style={{ border: '1px solid var(--hair)', borderLeft: '3px solid var(--risk)', borderRadius: 8, padding: 18 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                    <span className="serif" style={{ fontSize: 18, fontWeight: 600 }}>{c.area}</span>
                    <span className="mono" style={{ fontSize: 12, color: 'var(--risk)', fontWeight: 600 }}>{c.evol}/100</span>
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>
                    Gobernada por <strong style={{ color: IHP.byId[d.dominant].hex }}>{IHP.byId[d.dominant].name}</strong>. n={c.n} colaboradores. Requiere intervención prioritaria sobre los arquetipos de riesgo.
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* —— PÁGINA 3 —— */}
        <div className="rpage">
          <SectionTitle n="06" title="Recomendaciones y plan de acción" />
          <RecoSection reco={reco} />

          <div style={{ marginTop: 30 }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Plan de acción sugerido · 90 días</div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ borderBottom: '1.5px solid var(--ink)' }}>
                  <th style={{ textAlign: 'left', padding: '8px 6px', fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 500 }}>Horizonte</th>
                  <th style={{ textAlign: 'left', padding: '8px 6px', fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 500 }}>Foco</th>
                  <th style={{ textAlign: 'left', padding: '8px 6px', fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 500 }}>Acción</th>
                </tr>
              </thead>
              <tbody>
                {planRows(reco).map((r, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid var(--hair)' }}>
                    <td style={{ padding: '11px 6px', fontWeight: 600, whiteSpace: 'nowrap' }}>{r.h}</td>
                    <td style={{ padding: '11px 6px' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ width: 8, height: 8, borderRadius: 8, background: r.color }}></span>{r.foco}
                      </span>
                    </td>
                    <td style={{ padding: '11px 6px', color: 'var(--ink-2)' }}>{r.accion}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div style={{ marginTop: 40, paddingTop: 16, borderTop: '1px solid var(--hair)', display: 'flex', justifyContent: 'space-between' }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>Ingeniería Humana Empresarial · Documento confidencial</span>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{fecha}</span>
          </div>
        </div>
      </div>

      <style>{`
        .rpage { background:#fff; border:1px solid var(--hair); border-radius:6px; padding:48px 52px; margin-bottom:24px; box-shadow:var(--shadow); }
        @media print {
          @page { size: A4; margin: 14mm; }
          body { background:#fff !important; }
          .report-pages { max-width:none; padding:0; }
          .rpage { border:none; box-shadow:none; border-radius:0; padding:0 0 10mm; margin:0; page-break-after:always; }
          .rpage:last-child { page-break-after:auto; }
        }
      `}</style>
    </div>
  );
}

function planRows(reco) {
  const rows = [];
  (reco.urgente || []).slice(0, 2).forEach(r => rows.push({ h: '0–30 días', foco: IHP.byId[r.archetype].name, accion: r.text, color: 'var(--risk)' }));
  (reco.importante || []).slice(0, 2).forEach(r => rows.push({ h: '30–60 días', foco: IHP.byId[r.archetype].name, accion: r.text, color: 'var(--warn)' }));
  (reco.mejora || []).slice(0, 2).forEach(r => rows.push({ h: '60–90 días', foco: IHP.byId[r.archetype].name, accion: r.text, color: 'var(--good)' }));
  if (!rows.length) rows.push({ h: '0–90 días', foco: 'Cultura', accion: 'Sostener el monitoreo trimestral del mapa conductual.', color: 'var(--gold)' });
  return rows;
}

function SectionTitle({ n, title }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, margin: '0 0 18px' }}>
      <span className="mono" style={{ fontSize: 12, color: 'var(--gold)', fontWeight: 600 }}>{n}</span>
      <h2 className="serif" style={{ fontSize: 22, fontWeight: 600, margin: 0 }}>{title}</h2>
      <div style={{ flex: 1, height: 1, background: 'var(--hair)' }}></div>
    </div>
  );
}
function MiniStat({ label, value, accent }) {
  return (
    <div style={{ background: 'var(--panel-soft)', border: '1px solid var(--hair)', borderRadius: 8, padding: '14px 16px' }}>
      <div className="eyebrow" style={{ fontSize: 9.5, marginBottom: 8 }}>{label}</div>
      <div className="serif" style={{ fontSize: 22, fontWeight: 600, color: accent || 'var(--ink)', lineHeight: 1 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { ScreenReport });
