// Module: Resumen ejecutivo (condensed port of the executive dashboard)

function ResumenModule() {
  const { state } = useStore();
  const [period, setPeriod] = useState('month');

  return (
    <div className="view-in space-y-5">
      {/* Top toolbar */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <Badge variant="amber">Reporte de operación</Badge>
          <span className="text-[12px] text-muted tnum">2026-03-01 → 2026-03-31 · Marzo 2026</span>
        </div>
        <div className="flex items-center gap-2">
          <Tabs
            value={period}
            onChange={setPeriod}
            options={[
              { value: 'month', label: 'Mes' },
              { value: 'quarter', label: 'Trimestre' },
              { value: '90d', label: '90 días' },
            ]}
          />
          <Button variant="outline" size="sm">
            <Icon name="download" size={12} /> Exportar PDF
          </Button>
          <Button variant="primary" size="sm">
            <Icon name="send" size={12} /> Enviar al cliente
          </Button>
        </div>
      </div>

      {/* Hero row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <Card
          className="lg:col-span-2 relative overflow-hidden text-white border-slate-900"
          style={{
            background:
              'radial-gradient(1200px 400px at 120% -20%, rgba(235,107,30,.22), transparent 60%),linear-gradient(180deg,#1B2535 0%,#131C2A 100%)',
          }}
        >
          <CardContent className="pt-6">
            <div className="text-[10.5px] font-semibold text-slate-400 uppercase tracking-widest">
              Metros perforados en el mes
            </div>
            <div className="flex items-end gap-3 mt-4">
              <div className="text-[84px] font-extrabold leading-none tracking-tight tnum">847</div>
              <div className="text-[22px] font-semibold text-slate-400 mb-2">m</div>
            </div>
            <div className="flex gap-8 mt-5 flex-wrap">
              <div>
                <div className="text-[14px] font-semibold tnum text-emerald-300">
                  <span className="text-[10px]">▲</span> 18% vs febrero
                </div>
                <div className="text-[10.5px] text-slate-500 uppercase tracking-wider mt-1">
                  719 m → 847 m
                </div>
              </div>
              <div>
                <div className="text-[14px] font-semibold tnum text-amber">
                  +127 m sobre proyección
                </div>
                <div className="text-[10.5px] text-slate-500 uppercase tracking-wider mt-1">
                  Proyectado 720 m
                </div>
              </div>
              <div>
                <div className="text-[14px] font-semibold tnum text-slate-200">Pico 42 m / día</div>
                <div className="text-[10.5px] text-slate-500 uppercase tracking-wider mt-1">
                  22 de marzo
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-5">
            <div className="text-[10.5px] font-semibold text-muted uppercase tracking-widest">
              Horas de operación
            </div>
            <div className="text-[44px] font-extrabold tracking-tight tnum mt-3 leading-none">
              194 <span className="text-[20px] text-muted font-medium">h</span>
            </div>
            <div className="text-[12px] text-muted mt-2">de 744 h · 26% efectividad</div>
            <div className="h-2 rounded-full bg-slate-100 overflow-hidden mt-4">
              <div className="h-full bg-amber rounded-full" style={{ width: '26%' }} />
            </div>
            <div className="grid grid-cols-3 gap-3 mt-5 pt-4 border-t border-border">
              <div>
                <div className="text-[14px] font-bold tnum">27/31</div>
                <div className="text-[10.5px] text-muted">días op.</div>
              </div>
              <div>
                <div className="text-[14px] font-bold tnum">4</div>
                <div className="text-[10.5px] text-muted">sin actividad</div>
              </div>
              <div>
                <div className="text-[14px] font-bold tnum text-red">8h 52m</div>
                <div className="text-[10.5px] text-muted">gaps</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* KPI strip */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard
          label="ROP promedio"
          value="4.4"
          unit="m/h"
          note={
            <>
              <span className="text-emerald font-semibold">▲ 0.6</span> vs feb · requiere depth
              sensor
            </>
          }
          tag="pendiente"
          tagColor="amber"
        />
        <KpiCard
          label="Profundidad actual"
          value="1.897"
          unit="m"
          note="76% del objetivo Q1"
          tag="pendiente"
          tagColor="amber"
        />
        <KpiCard
          label="Caudal de bomba"
          value="96"
          unit="lts/min"
          note="Operación normal"
          tag="sensor"
          tagColor="emerald"
        />
        <KpiCard
          label="Eventos operativos"
          value="58"
          unit=""
          note={
            <>
              <span className="text-emerald font-semibold">▼ 18%</span> vs feb · alta presión /
              torque
            </>
          }
          tag="derivado"
          tagColor="default"
        />
      </div>

      {/* Progress + chart */}
      <Card>
        <CardContent className="pt-5">
          <div className="flex items-end justify-between flex-wrap gap-2">
            <div>
              <div className="text-[14px] font-semibold">
                Objetivo Q1 2026{' '}
                <span className="text-muted font-normal ml-1">· 1.897 m de 2.500 m</span>
              </div>
              <div className="text-[12px] text-muted mt-1">
                Proyección cierre Q1: <b className="text-emerald">2.650 m (106%)</b> · 603 m
                restantes
              </div>
            </div>
            <div className="text-[32px] font-extrabold text-amber tnum leading-none">
              76<span className="text-[16px] text-muted font-semibold">%</span>
            </div>
          </div>
          <div className="mt-4 h-3.5 bg-slate-100 rounded-full border border-border overflow-hidden">
            <div
              className="h-full rounded-full flex items-center justify-end pr-2 text-[10px] font-bold text-white"
              style={{ width: '76%', background: 'linear-gradient(90deg,#EB6B1E,#F28E42)' }}
            >
              76%
            </div>
          </div>

          <div className="mt-5">
            <div className="flex gap-4 text-[11.5px] text-muted mb-2">
              <span>
                <span className="inline-block w-4 h-[2px] bg-amber align-middle mr-1.5" />
                Acumulado real
              </span>
              <span>
                <span className="inline-block w-4 border-t-2 border-dashed border-slate-400 align-middle mr-1.5" />
                Ritmo objetivo
              </span>
              <span className="ml-auto text-slate-400">31 días · marzo 2026</span>
            </div>
            <CumulativeChart />
          </div>
        </CardContent>
      </Card>

      {/* Two-col: week bars + shift efficiency */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Card>
          <CardHeader>
            <div className="flex items-baseline justify-between">
              <CardTitle>Metros perforados por semana</CardTitle>
              <span className="text-[11px] text-muted">Total 847 m</span>
            </div>
          </CardHeader>
          <CardContent>
            <WeekBars />
          </CardContent>
        </Card>
        <Card>
          <CardHeader>
            <div className="flex items-baseline justify-between">
              <CardTitle>Eficiencia por turno</CardTitle>
              <span className="text-[11px] text-muted">% horas productivas</span>
            </div>
          </CardHeader>
          <CardContent>
            <ShiftEfficiency />
          </CardContent>
        </Card>
      </div>

      {/* Highlights */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <Highlight
          title="Lo bueno"
          color="emerald"
          items={[
            <>
              <b>Avance 76%</b> sobre objetivo Q1, proyección 106%
            </>,
            <>
              ROP promedio <b>+16%</b> mes a mes (3.8 → 4.4 m/h)
            </>,
            <>
              Pico de <b>42 m/día</b> el 22 de marzo
            </>,
            <>
              <b>4 días</b> adicionales operativos vs febrero
            </>,
          ]}
        />
        <Highlight
          title="A revisar"
          color="amber"
          items={[
            <>
              Turno <b>noche 18–24</b> rinde ~20% menos que tarde
            </>,
            <>
              <b>12 eventos</b> de alta presión sin resolver
            </>,
            <>
              Gap de captura acumulado <b>8h 52m</b>
            </>,
            <>
              Cambio de aceite del motor principal <b>vencido</b>
            </>,
          ]}
        />
        <Highlight
          title="Siguiente período"
          color="slate"
          items={[
            <>
              Cerrar los <b>603 m</b> restantes del objetivo Q1
            </>,
            'Plan de acción para turno nocturno',
            'Investigar causa de picos de presión recurrentes',
            <>
              Reponer <b>mangueras de alta presión</b> (crítico)
            </>,
          ]}
        />
      </div>

      {/* Detail table */}
      <Card>
        <CardHeader>
          <CardTitle>Detalle mes vs mes anterior</CardTitle>
        </CardHeader>
        <div className="overflow-x-auto">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="bg-slate-50 text-[10.5px] font-semibold text-muted uppercase tracking-wider">
                <th className="text-left px-5 py-2.5">Métrica</th>
                <th className="text-right px-5 py-2.5">Marzo 2026</th>
                <th className="text-right px-5 py-2.5">Febrero 2026</th>
                <th className="text-right px-5 py-2.5">Variación</th>
              </tr>
            </thead>
            <tbody>
              {[
                ['Metros perforados', '847 m', '719 m', '+18%', 'up'],
                ['Horas de operación efectiva', '194 h', '189 h', '+3%', 'up'],
                ['ROP promedio', '4.4 m/h', '3.8 m/h', '+16%', 'up'],
                ['Días operativos', '27 / 31', '23 / 28', '+4 días', 'up'],
                ['Eventos operativos', '58', '71', '−18%', 'up'],
                ['Gaps de captura > 1h', '2', '3', '−1', 'up'],
                ['Caudal bomba promedio', '96 lts/min', '93 lts/min', '+3%', 'neu'],
              ].map((r, i) => (
                <tr key={i} className="border-t border-border">
                  <td className="px-5 py-3">{r[0]}</td>
                  <td className="px-5 py-3 text-right tnum font-medium">{r[1]}</td>
                  <td className="px-5 py-3 text-right tnum text-muted">{r[2]}</td>
                  <td
                    className={cn(
                      'px-5 py-3 text-right tnum font-semibold',
                      r[4] === 'up' ? 'text-emerald' : r[4] === 'down' ? 'text-red' : 'text-muted',
                    )}
                  >
                    {r[3]}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function KpiCard({ label, value, unit, note, tag, tagColor }) {
  return (
    <Card className="relative">
      <CardContent className="pt-5">
        <div className="flex items-center justify-between">
          <div className="text-[10.5px] font-semibold text-muted uppercase tracking-widest">
            {label}
          </div>
          <Badge variant={tagColor}>{tag}</Badge>
        </div>
        <div className="mt-3">
          <span className="text-[30px] font-bold tracking-tight tnum">{value}</span>
          {unit && <span className="text-[14px] text-muted font-medium ml-1">{unit}</span>}
        </div>
        <div className="text-[11.5px] text-muted mt-2 leading-snug">{note}</div>
      </CardContent>
    </Card>
  );
}

function Highlight({ title, color, items }) {
  const colors = {
    emerald: 'border-l-emerald',
    amber: 'border-l-amber',
    slate: 'border-l-slate-400',
  };
  const bullet = {
    emerald: 'bg-emerald',
    amber: 'bg-amber',
    slate: 'bg-slate-300',
  };
  return (
    <Card className={cn('border-l-4', colors[color])}>
      <CardContent className="pt-5">
        <h4 className="text-[11.5px] font-bold uppercase tracking-wider mb-3">{title}</h4>
        <ul className="space-y-2.5">
          {items.map((it, i) => (
            <li key={i} className="flex gap-2.5 text-[13px] leading-snug">
              <span className={cn('mt-1.5 h-1.5 w-1.5 rounded-full shrink-0', bullet[color])} />
              <span>{it}</span>
            </li>
          ))}
        </ul>
      </CardContent>
    </Card>
  );
}

function CumulativeChart() {
  // 31-day cumulative vs target
  const data = [
    22, 48, 71, 95, 118, 140, 165, 195, 228, 261, 289, 314, 340, 372, 408, 445, 485, 522, 555, 588,
    625, 667, 711, 748, 780, 805, 825, 833, 840, 845, 847,
  ];
  const w = 1000;
  const h = 200;
  const pad = { l: 32, r: 12, t: 10, b: 22 };
  const maxY = 900;
  const x = (i) => pad.l + (i / (data.length - 1)) * (w - pad.l - pad.r);
  const y = (v) => pad.t + (1 - v / maxY) * (h - pad.t - pad.b);
  const line = data
    .map((v, i) => `${(i ? 'L' : 'M') + x(i).toFixed(1)},${y(v).toFixed(1)}`)
    .join(' ');
  const area = `${line} L${x(data.length - 1).toFixed(1)},${h - pad.b} L${pad.l},${h - pad.b} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full h-56">
      <defs>
        <linearGradient id="cumG" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#EB6B1E" stopOpacity=".25" />
          <stop offset="100%" stopColor="#EB6B1E" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 225, 450, 675, 900].map((v, i) => (
        <g key={i}>
          <line x1={pad.l} y1={y(v)} x2={w - pad.r} y2={y(v)} stroke="#E2E8F0" strokeWidth="1" />
          <text
            x={pad.l - 6}
            y={y(v) + 3}
            fontSize="10"
            textAnchor="end"
            fill="#94A3B8"
            className="tnum"
          >
            {v}
          </text>
        </g>
      ))}
      <line
        x1={pad.l}
        y1={y(0)}
        x2={w - pad.r}
        y2={y(900)}
        stroke="#94A3B8"
        strokeWidth="1.5"
        strokeDasharray="5 4"
      />
      <path d={area} fill="url(#cumG)" />
      <path d={line} fill="none" stroke="#EB6B1E" strokeWidth="2.5" strokeLinejoin="round" />
      <circle cx={x(30)} cy={y(847)} r="4" fill="#EB6B1E" stroke="#fff" strokeWidth="2" />
      <text
        x={x(30) - 6}
        y={y(847) - 8}
        fontSize="11"
        fontWeight="700"
        fill="#1A2332"
        textAnchor="end"
      >
        847 m
      </text>
      {[1, 6, 11, 16, 21, 26, 31].map((d) => (
        <text key={d} x={x(d - 1)} y={h - 6} fontSize="10" textAnchor="middle" fill="#94A3B8">
          {d}
        </text>
      ))}
    </svg>
  );
}

function WeekBars() {
  const weeks = [
    ['Sem 1', 193, '1–7 mar'],
    ['Sem 2', 162, '8–14 mar'],
    ['Sem 3', 212, '15–21 mar'],
    ['Sem 4', 280, '22–31 mar'],
  ];
  const max = 300;
  return (
    <svg viewBox="0 0 540 240" className="w-full h-56">
      {[0, 100, 200, 300].map((v, i) => (
        <g key={i}>
          <line
            x1="40"
            y1={210 - (v / max) * 180}
            x2="520"
            y2={210 - (v / max) * 180}
            stroke="#E2E8F0"
          />
          <text
            x="34"
            y={214 - (v / max) * 180}
            fontSize="10"
            textAnchor="end"
            fill="#94A3B8"
            className="tnum"
          >
            {v}
          </text>
        </g>
      ))}
      {weeks.map(([n, v, s], i) => {
        const bx = 60 + i * 120;
        const bw = 80;
        const bh = (v / max) * 180;
        const by = 210 - bh;
        return (
          <g key={n}>
            <rect x={bx} y={by} width={bw} height={bh} fill="#EB6B1E" rx="3" />
            <text
              x={bx + bw / 2}
              y={by - 6}
              fontSize="12"
              fontWeight="700"
              fill="#1A2332"
              textAnchor="middle"
              className="tnum"
            >
              {v}
            </text>
            <text x={bx + bw / 2} y="228" fontSize="11" fill="#64748B" textAnchor="middle">
              {n}
            </text>
            <text x={bx + bw / 2} y="240" fontSize="9" fill="#94A3B8" textAnchor="middle">
              {s}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

function ShiftEfficiency() {
  const shifts = [
    ['Mañana', '06–12', 25.1, '#EB6B1E'],
    ['Tarde', '12–18', 26.8, '#047857'],
    ['Noche', '00–06', 24.2, '#EB6B1E'],
    ['Noche', '18–24', 21.3, '#F59E0B'],
  ];
  return (
    <svg viewBox="0 0 540 250" className="w-full h-56">
      {shifts.map((s, i) => {
        const y = 30 + i * 55;
        const w = (s[2] / 30) * 300;
        return (
          <g key={i}>
            <text x="150" y={y + 12} fontSize="12" textAnchor="end" fill="#1A2332" fontWeight="500">
              {s[0]}
            </text>
            <text x="150" y={y + 26} fontSize="10" textAnchor="end" fill="#94A3B8">
              {s[1]}
            </text>
            <rect x="170" y={y} width="300" height="22" fill="#F1F5F9" rx="3" />
            <rect x="170" y={y} width={w} height="22" fill={s[3]} rx="3" />
            <text
              x={170 + w - 10}
              y={y + 15}
              fontSize="11"
              fontWeight="700"
              fill="#fff"
              textAnchor="end"
            >
              {s[2].toFixed(1)}%{i === 1 ? ' ★' : ''}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

Object.assign(window, { ResumenModule });
