/* global React */

const { useState: useStateT } = React;

// ---------------- KPI Card ----------------
function KpiCard({ icon, label, num, sub, tone, gauge }) {
  const I = window.Icons;
  return (
    <div className={`kpi${tone ? ' is-' + tone : ''}`}>
      <div className="kpi__head">
        <div className="kpi__icon">{React.createElement(I[icon], { size: 16 })}</div>
        <div className="kpi__label">{label}</div>
      </div>
      <div className="kpi__num-row">
        <div className="kpi__num">{num}</div>
        {gauge != null && <KpiArc value={gauge} tone={tone} />}
      </div>
      {sub && <div className="kpi__sub">{sub}</div>}
    </div>
  );
}

// Small SVG arc for % gauges
function KpiArc({ value, tone }) {
  const r = 22, c = 2 * Math.PI * r;
  const offset = c * (1 - value / 100);
  const color =
    tone === 'ok' ? 'var(--sem-success)' :
    tone === 'warn' ? 'var(--sem-warning-bg)' :
    tone === 'danger' ? 'var(--sem-danger)' :
    'var(--cgr-primary)';
  return (
    <svg width="54" height="54" viewBox="0 0 54 54">
      <circle cx="27" cy="27" r={r} fill="none" stroke="var(--cgr-border)" strokeWidth="4" />
      <circle
        cx="27" cy="27" r={r}
        fill="none" stroke={color} strokeWidth="4" strokeLinecap="round"
        strokeDasharray={c}
        strokeDashoffset={offset}
        transform="rotate(-90 27 27)"
      />
    </svg>
  );
}

// ---------------- Mecanismo Stacked Bar ----------------
function MecanismoStacked({ items }) {
  return (
    <div className="mech-stack">
      {items.map(m => {
        const okPct = (m.ok / m.total) * 100;
        const prPct = (m.partial / m.total) * 100;
        const bdPct = (m.bad / m.total) * 100;
        return (
          <div className="mech-stack__row" key={m.id}>
            <div className="mech-stack__head">
              <strong>{m.label}</strong>
              <span className="mech-stack__total mono">{m.total}</span>
            </div>
            <div className="mech-stack__bar">
              <span className="seg is-ok"     style={{ width: okPct + '%' }} title={`Cumplidos ${m.ok}`}></span>
              <span className="seg is-warn"   style={{ width: prPct + '%' }} title={`Parciales ${m.partial}`}></span>
              <span className="seg is-danger" style={{ width: bdPct + '%' }} title={`No cumplidos ${m.bad}`}></span>
            </div>
            <div className="mech-stack__legend">
              <span><span className="dot-status is-ok"></span>{m.ok}</span>
              <span><span className="dot-status is-warn"></span>{m.partial}</span>
              <span><span className="dot-status is-danger"></span>{m.bad}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---------------- Horizontal Inst Bar Chart ----------------
function InstBars({ items, max }) {
  return (
    <div className="inst-bars">
      {items.slice(0, 6).map(it => {
        const w = (it.total / max) * 100;
        const tone = it.cumpl >= 75 ? 'is-ok' : it.cumpl >= 55 ? 'is-warn' : 'is-danger';
        return (
          <div className="inst-bars__row" key={it.inst}>
            <div className="inst-bars__label" title={it.inst}>{it.inst}</div>
            <div className="inst-bars__track">
              <span className="inst-bars__fill" style={{ width: w + '%' }}></span>
              <span className="inst-bars__total mono">{it.total}</span>
            </div>
            <div className={`inst-bars__cumpl ${tone} mono`}>{it.cumpl}%</div>
          </div>
        );
      })}
    </div>
  );
}

// ---------------- Sparkline (evolution) ----------------
function Sparkline({ data, w = 320, h = 100 }) {
  if (!data.length) return null;
  const pad = 4;
  const min = Math.min(...data.map(d => d.v)) - 4;
  const max = Math.max(...data.map(d => d.v)) + 4;
  const step = (w - pad * 2) / (data.length - 1);
  const pts = data.map((d, i) => {
    const x = pad + i * step;
    const y = h - pad - ((d.v - min) / (max - min)) * (h - pad * 2);
    return [x, y];
  });
  const pathD = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const areaD = pathD + ` L${pts[pts.length - 1][0]} ${h - pad} L${pts[0][0]} ${h - pad} Z`;
  const last = pts[pts.length - 1];
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" width="100%" height={h}>
      <defs>
        <linearGradient id="spark-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(45,74,138,0.18)" />
          <stop offset="100%" stopColor="rgba(45,74,138,0.00)" />
        </linearGradient>
      </defs>
      <path d={areaD} fill="url(#spark-fill)" />
      <path d={pathD} fill="none" stroke="var(--cgr-primary)" strokeWidth="1.75" strokeLinejoin="round" />
      <circle cx={last[0]} cy={last[1]} r="3.5" fill="var(--cgr-primary)" stroke="#fff" strokeWidth="1.5" />
    </svg>
  );
}

// ---------------- Filter chip / select ----------------
function FilterSelect({ icon, label, value }) {
  const I = window.Icons;
  return (
    <button type="button" className="filter-select">
      {icon && <span className="filter-select__icon">{React.createElement(I[icon], { size: 14 })}</span>}
      <span className="filter-select__label">{label}:</span>
      <strong>{value}</strong>
      <I.ChevronDown size={14} />
    </button>
  );
}

// ---------------- Status pill mapping ----------------
function StatusPill({ estado }) {
  const I = window.Icons;
  const map = {
    ok:      { cls: 'is-ok',     icon: 'CheckCircle2', label: 'Cumplido' },
    partial: { cls: 'is-warn',   icon: 'AlertCircle',  label: 'Parcial' },
    bad:     { cls: 'is-danger', icon: 'XCircle',      label: 'No cumplido' },
    overdue: { cls: 'is-dark',   icon: 'AlertTriangle',label: 'Vencido s/avance' },
  };
  const s = map[estado] || map.partial;
  return (
    <span className={`status ${s.cls}`}>
      {React.createElement(I[s.icon], { size: 11 })}
      {s.label}
    </span>
  );
}

// ---------------- TABLERO SCREEN ----------------
function TableroScreen({ onOpenDetalle }) {
  const I = window.Icons;
  const [filter, setFilter] = useStateT('todos');
  const compromisos = window.COMPROMISOS;
  const maxInst = Math.max(...window.INST_RANKING.map(i => i.total));

  return (
    <div data-screen-label="03 Tablero de Control">
      {/* Page header */}
      <div className="page-head">
        <div>
          <div className="page-head__eyebrow">CGR · Dirección de Análisis de Datos</div>
          <h1 className="page-head__title">Tablero de Control</h1>
          <p className="page-head__sub">
            Estado consolidado del cumplimiento país en los tres mecanismos —
            MESICIC, UNCAC y OCDE — actualizado al 21 de mayo de 2026.
          </p>
        </div>
        <div className="page-head__actions">
          <button type="button" className="btn btn--secondary">
            <I.Filter size={14} /> Filtros avanzados
          </button>
          <button type="button" className="btn btn--secondary">
            <I.Download size={14} /> Exportar
          </button>
          <button type="button" className="btn btn--primary">
            <I.Sparkles size={14} /> Generar reporte
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="filters">
        <FilterSelect icon="Globe"       label="Mecanismo"  value="Todos" />
        <FilterSelect icon="Building2"   label="Institución" value="Todas las 47" />
        <FilterSelect icon="CheckCircle2" label="Estado"    value="Todos" />
        <FilterSelect icon="Calendar"    label="Período"    value="2024 — 2026" />
        <div className="filters__spacer"></div>
        <button type="button" className="filter-clear">Limpiar filtros</button>
      </div>

      {/* KPI bento */}
      <div className="kpi-grid">
        <KpiCard
          icon="ListChecks"
          label="Total compromisos activos"
          num="527"
          sub="118 MESICIC · 156 UNCAC · 253 OCDE"
        />
        <KpiCard
          icon="Sparkles"
          label="Cumplimiento global"
          num="62%"
          sub="+4 pts respecto al trimestre anterior"
          gauge={62}
        />
        <KpiCard
          icon="CheckCircle2"
          label="Cumplidos"
          num="184"
          sub="34.9% del total activo"
          tone="ok"
          gauge={35}
        />
        <KpiCard
          icon="AlertCircle"
          label="Parcialmente cumplidos"
          num="248"
          sub="47.1% — zona gris prioritaria"
          tone="warn"
          gauge={47}
        />
        <KpiCard
          icon="XCircle"
          label="No cumplidos"
          num="78"
          sub="14.8% — requieren plan de acción"
          tone="danger"
          gauge={15}
        />
        <KpiCard
          icon="AlertTriangle"
          label="Vencidos sin avance"
          num="17"
          sub="Plazo superado · D+1 o más"
          tone="dark"
        />
      </div>

      {/* Charts row */}
      <div className="charts">
        <div className="card chart-card">
          <div className="card__head">
            <h3>Distribución por mecanismo</h3>
            <span className="meta">3 mecanismos activos</span>
          </div>
          <div className="card__body">
            <MecanismoStacked items={window.MECANISMO_DIST} />
          </div>
        </div>

        <div className="card chart-card">
          <div className="card__head">
            <h3>Top 6 instituciones con más compromisos</h3>
            <button type="button" className="section-head__link">Ver todas <I.ArrowRight size={11} /></button>
          </div>
          <div className="card__body">
            <InstBars items={window.INST_RANKING} max={maxInst} />
          </div>
        </div>

        <div className="card chart-card chart-card--narrow">
          <div className="card__head">
            <h3>Evolución del cumplimiento</h3>
            <span className="meta">17 meses</span>
          </div>
          <div className="card__body">
            <div className="evo-big">
              <div className="evo-big__num">62%</div>
              <div className="evo-big__delta">↑ 21 pts vs. ene 2025</div>
            </div>
            <Sparkline data={window.EVO_SERIES} h={70} />
          </div>
        </div>
      </div>

      {/* Tabla principal */}
      <div className="card table-card">
        <div className="card__head">
          <div>
            <h3>Compromisos · vista detallada</h3>
            <div className="meta">Mostrando {compromisos.length} de 527 · ordenados por proximidad de vencimiento</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button type="button" className="btn btn--ghost">
              <I.Eye size={14} /> Columnas
            </button>
            <button type="button" className="btn btn--secondary">
              <I.Download size={14} /> Exportar tabla
            </button>
          </div>
        </div>
        <div className="table-wrap">
          <table className="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Recomendación</th>
                <th>Mecanismo</th>
                <th>Institución responsable</th>
                <th>Vence</th>
                <th>Estado</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {compromisos.map(c => (
                <tr key={c.id} onClick={() => onOpenDetalle && onOpenDetalle(c.id)}>
                  <td className="mono">{c.id}</td>
                  <td className="cell-title">{c.text}</td>
                  <td>
                    <span className={`mech-tag mech-tag--${c.mecanismo.toLowerCase()}`}>{c.mecanismo}</span>
                    <span className="cell-sub">{c.ronda}</span>
                  </td>
                  <td>{c.inst}</td>
                  <td className="mono">
                    {c.vence}
                    <div className={`cell-sub${c.d < 0 ? ' is-overdue' : c.d <= 3 ? ' is-soon' : ''}`}>
                      {c.d < 0 ? `D+${Math.abs(c.d)} (vencido)` : c.d === 0 ? 'Hoy' : `D-${c.d}`}
                    </div>
                  </td>
                  <td><StatusPill estado={c.estado} /></td>
                  <td>
                    <button type="button" className="row-cta" onClick={(e) => { e.stopPropagation(); onOpenDetalle && onOpenDetalle(c.id); }}>
                      <I.ChevronRight size={14} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="table-foot">
          <span className="meta">Página 1 de 44 · 12 por página</span>
          <div className="pager">
            <button type="button" className="pager__btn" disabled>‹</button>
            <button type="button" className="pager__btn is-active">1</button>
            <button type="button" className="pager__btn">2</button>
            <button type="button" className="pager__btn">3</button>
            <span className="pager__sep">…</span>
            <button type="button" className="pager__btn">44</button>
            <button type="button" className="pager__btn">›</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TableroScreen, StatusPill });
