// Drilling module: wraps the sub-views.

function DrillingModule({ sub }) {
  if (sub === 'info') return <DrillingInfoView />;
  if (sub === 'reporte') return <ParteModule />; // existing "Parte diario" component
  if (sub === 'mantenimiento') return <MantenimientoModule />;
  if (sub === 'telemetria') return <TelemetriaModule />; // WellData-style viewer
  if (sub === 'guardia') return <ShiftHandoverView area="Drilling" />;
  return <DrillingInfoView />;
}

// -------- Información general del pozo --------
function DrillingInfoView() {
  const well = {
    nombreEquipo: 'Rig-1 · NETTO',
    tipoPozo: 'Direccional (J-shape)',
    bloque: 'Bloque Loma Campana',
    provincia: 'San Juan, Argentina',
    profundidadMD: 2500,
    profundidadActual: 1897,
    diasProgramados: 62,
    diasTranscurridos: 41,
    equipoPerforacion: 'Rig Optima DE-500',
    contratista: 'Servicios Patagónicos S.A.',
    proyecto: 'Proyecto NETTO-4H',
    nombrePozo: 'NETTO-4H',
    lat: -31.5375,
    lon: -68.5364,
    spudDate: '2026-02-10',
  };

  const progreso = Math.round((well.profundidadActual / well.profundidadMD) * 100);
  const progDias = Math.round((well.diasTranscurridos / well.diasProgramados) * 100);

  return (
    <div className="view-in space-y-5">
      {/* Hero */}
      <Card
        className="relative overflow-hidden text-white border-slate-900"
        style={{
          background:
            'radial-gradient(800px 300px at 100% -20%, rgba(235,107,30,.22), transparent 60%),linear-gradient(180deg,#1B2535 0%,#131C2A 100%)',
        }}
      >
        <CardContent className="pt-6">
          <div className="flex items-start justify-between flex-wrap gap-4">
            <div>
              <div className="text-[10.5px] font-semibold text-slate-400 uppercase tracking-widest">
                Pozo activo
              </div>
              <div className="flex items-baseline gap-3 mt-2">
                <div className="text-[36px] font-extrabold tracking-tight leading-none">
                  {well.nombrePozo}
                </div>
                <Badge variant="emerald">
                  <span className="h-1.5 w-1.5 rounded-full bg-emerald live-dot" /> Perforando
                </Badge>
              </div>
              <div className="text-[13px] text-slate-300 mt-1.5">
                {well.proyecto} · {well.contratista}
              </div>
            </div>
            <div className="flex items-center gap-3">
              <Button
                variant="outline"
                size="sm"
                className="bg-white/5 border-white/15 text-white hover:bg-white/10"
              >
                <Icon name="edit" size={12} /> Editar
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="bg-white/5 border-white/15 text-white hover:bg-white/10"
              >
                <Icon name="download" size={12} /> Exportar ficha
              </Button>
            </div>
          </div>

          <div className="grid grid-cols-2 lg:grid-cols-4 gap-6 mt-6 pt-5 border-t border-white/10">
            <div>
              <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
                Profundidad
              </div>
              <div className="mt-1.5 flex items-baseline gap-1.5">
                <span className="text-[26px] font-extrabold tnum">
                  {well.profundidadActual.toLocaleString('es-AR')}
                </span>
                <span className="text-[13px] text-slate-400">
                  / {well.profundidadMD.toLocaleString('es-AR')} m MD
                </span>
              </div>
              <div className="mt-2 h-1.5 rounded-full bg-white/10 overflow-hidden">
                <div className="h-full bg-amber rounded-full" style={{ width: `${progreso}%` }} />
              </div>
              <div className="text-[11px] text-slate-400 mt-1 tnum">{progreso}% del MD total</div>
            </div>
            <div>
              <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
                Días
              </div>
              <div className="mt-1.5 flex items-baseline gap-1.5">
                <span className="text-[26px] font-extrabold tnum">{well.diasTranscurridos}</span>
                <span className="text-[13px] text-slate-400">/ {well.diasProgramados} d</span>
              </div>
              <div className="mt-2 h-1.5 rounded-full bg-white/10 overflow-hidden">
                <div
                  className="h-full bg-slate-300 rounded-full"
                  style={{ width: `${progDias}%` }}
                />
              </div>
              <div className="text-[11px] text-slate-400 mt-1 tnum">Spud: {well.spudDate}</div>
            </div>
            <div>
              <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
                Tipo de pozo
              </div>
              <div className="mt-1.5 text-[15px] font-semibold">{well.tipoPozo}</div>
              <div className="text-[11px] text-slate-400 mt-1">Trayectoria planificada</div>
            </div>
            <div>
              <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-widest">
                Ubicación
              </div>
              <div className="mt-1.5 text-[15px] font-semibold">{well.bloque}</div>
              <div className="text-[11px] text-slate-400 mt-1">{well.provincia}</div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Data grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>Información general</CardTitle>
            <CardDescription>Ficha técnica del pozo y equipamiento.</CardDescription>
          </CardHeader>
          <CardContent className="pt-0">
            <dl className="grid grid-cols-2 gap-y-3 gap-x-6 text-[13px]">
              <InfoRow label="Nombre del pozo" value={well.nombrePozo} />
              <InfoRow label="Proyecto" value={well.proyecto} />
              <InfoRow label="Nombre del equipo" value={well.nombreEquipo} />
              <InfoRow label="Equipo de perforación" value={well.equipoPerforacion} />
              <InfoRow label="Contratista" value={well.contratista} />
              <InfoRow label="Tipo de pozo" value={well.tipoPozo} />
              <InfoRow label="Bloque" value={well.bloque} />
              <InfoRow label="Provincia" value={well.provincia} />
              <InfoRow
                label="Profundidad final MD"
                value={`${well.profundidadMD.toLocaleString('es-AR')} m`}
              />
              <InfoRow label="Días programados" value={`${well.diasProgramados} días`} />
            </dl>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Posición geográfica</CardTitle>
            <CardDescription>Coordenadas de boca de pozo.</CardDescription>
          </CardHeader>
          <CardContent className="pt-0">
            {/* Map placeholder */}
            <div
              className="relative h-48 rounded-lg overflow-hidden border border-border"
              style={{
                background:
                  'repeating-linear-gradient(45deg, #F1F5F9, #F1F5F9 10px, #E2E8F0 10px, #E2E8F0 20px)',
              }}
            >
              <div className="absolute inset-0 bg-gradient-to-br from-slate-50/40 to-transparent" />
              <svg className="absolute inset-0 w-full h-full" viewBox="0 0 300 200">
                <path
                  d="M 20 120 Q 80 60 140 100 T 280 80"
                  stroke="#94A3B8"
                  strokeWidth="1.5"
                  fill="none"
                  strokeDasharray="4 3"
                />
                <path
                  d="M 20 160 Q 100 130 200 150 T 280 130"
                  stroke="#94A3B8"
                  strokeWidth="1.5"
                  fill="none"
                  strokeDasharray="4 3"
                  opacity=".6"
                />
              </svg>
              <div className="absolute" style={{ left: '55%', top: '45%' }}>
                <div className="relative -translate-x-1/2 -translate-y-1/2">
                  <div className="absolute inset-0 h-8 w-8 rounded-full bg-amber/30 -translate-x-1/2 -translate-y-1/2 live-dot" />
                  <div className="h-6 w-6 rounded-full bg-amber border-2 border-white shadow flex items-center justify-center text-white">
                    <Icon name="drill" size={11} />
                  </div>
                </div>
              </div>
              <div className="absolute top-2 right-2 bg-white/90 backdrop-blur rounded-md px-2 py-1 text-[10px] font-semibold text-ink border border-border shadow-card mono">
                {well.lat.toFixed(4)}°, {well.lon.toFixed(4)}°
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3 mt-3 text-[12px]">
              <div>
                <div className="text-[10px] text-muted uppercase tracking-wider">Latitud</div>
                <div className="mono font-semibold tnum mt-0.5">{well.lat}°</div>
              </div>
              <div>
                <div className="text-[10px] text-muted uppercase tracking-wider">Longitud</div>
                <div className="mono font-semibold tnum mt-0.5">{well.lon}°</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Trajectory diagram */}
      <Card>
        <CardHeader>
          <div className="flex items-baseline justify-between">
            <div>
              <CardTitle>Trayectoria del pozo</CardTitle>
              <CardDescription>Perfil MD vs TVD · vista de proyección vertical.</CardDescription>
            </div>
            <div className="flex items-center gap-3 text-[11px] text-muted">
              <span className="flex items-center gap-1.5">
                <span className="inline-block w-4 h-[2px] bg-amber" />
                Perforado
              </span>
              <span className="flex items-center gap-1.5">
                <span className="inline-block w-4 border-t-2 border-dashed border-slate-400" />
                Planificado
              </span>
            </div>
          </div>
        </CardHeader>
        <CardContent className="pt-0">
          <TrajectorySvg currentMD={well.profundidadActual} totalMD={well.profundidadMD} />
        </CardContent>
      </Card>
    </div>
  );
}

function InfoRow({ label, value }) {
  return (
    <div className="border-b border-border pb-2.5 last:border-0">
      <dt className="text-[10.5px] font-semibold text-muted uppercase tracking-wider">{label}</dt>
      <dd className="text-[13.5px] font-medium text-ink mt-1">{value}</dd>
    </div>
  );
}

function TrajectorySvg({ currentMD, totalMD }) {
  // J-shape trajectory: vertical → build → tangent
  const w = 900;
  const h = 280;
  const top = 20;
  const left = 60;
  const right = w - 30;
  const bottom = h - 30;
  // Planned path coordinates (x = horizontal displacement, y = depth)
  const planned = [
    { md: 0, x: 0, y: 0 },
    { md: 800, x: 0, y: 800 }, // vertical section
    { md: 1400, x: 180, y: 1320 }, // build
    { md: 2000, x: 520, y: 1580 }, // tangent
    { md: 2500, x: 940, y: 1720 }, // lateral landing
  ];
  const maxY = 1800;
  const maxX = 1000;
  const P = (x, y) => [left + (x / maxX) * (right - left), top + (y / maxY) * (bottom - top)];
  const planPath = `M ${planned
    .map((p) =>
      P(p.x, p.y)
        .map((v) => v.toFixed(1))
        .join(','),
    )
    .join(' L ')}`;

  // Actual (perforated) path — up to currentMD
  const actual = [];
  for (const p of planned) {
    if (p.md <= currentMD) actual.push(p);
    else {
      // interpolate last segment
      const prev = actual[actual.length - 1];
      const t = (currentMD - prev.md) / (p.md - prev.md);
      actual.push({
        md: currentMD,
        x: prev.x + (p.x - prev.x) * t,
        y: prev.y + (p.y - prev.y) * t,
      });
      break;
    }
  }
  const actPath = `M ${actual
    .map((p) =>
      P(p.x, p.y)
        .map((v) => v.toFixed(1))
        .join(','),
    )
    .join(' L ')}`;
  const [bx, by] = P(actual[actual.length - 1].x, actual[actual.length - 1].y);

  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full h-64">
      {/* grid */}
      {[0, 500, 1000, 1500, 1800].map((d) => {
        const y = top + (d / maxY) * (bottom - top);
        return (
          <g key={`g${d}`}>
            <line x1={left} y1={y} x2={right} y2={y} stroke="#E2E8F0" />
            <text
              x={left - 8}
              y={y + 3}
              fontSize="9"
              textAnchor="end"
              fill="#94A3B8"
              className="tnum"
            >
              {d}
            </text>
          </g>
        );
      })}
      <text
        x={left - 44}
        y={top + 6}
        fontSize="9"
        fill="#64748B"
        transform={`rotate(-90, ${left - 44}, ${top + 6})`}
      >
        TVD (m)
      </text>
      {[0, 250, 500, 750, 1000].map((x) => {
        const xp = left + (x / maxX) * (right - left);
        return (
          <g key={`xg${x}`}>
            <line x1={xp} y1={top} x2={xp} y2={bottom} stroke="#E2E8F0" strokeDasharray="2 3" />
            <text
              x={xp}
              y={bottom + 14}
              fontSize="9"
              textAnchor="middle"
              fill="#94A3B8"
              className="tnum"
            >
              {x}
            </text>
          </g>
        );
      })}
      <text x={(left + right) / 2} y={bottom + 26} fontSize="9" textAnchor="middle" fill="#64748B">
        Desplazamiento horizontal (m)
      </text>

      {/* surface */}
      <line x1={left} y1={top} x2={right} y2={top} stroke="#94A3B8" strokeWidth="2" />
      <text x={left - 8} y={top + 3} fontSize="9" textAnchor="end" fill="#1A2332" fontWeight="700">
        Sup.
      </text>

      {/* planned */}
      <path d={planPath} stroke="#94A3B8" strokeWidth="2" strokeDasharray="6 4" fill="none" />
      {/* actual */}
      <path
        d={actPath}
        stroke="#EB6B1E"
        strokeWidth="3"
        fill="none"
        strokeLinecap="round"
        strokeLinejoin="round"
      />

      {/* bit */}
      <circle cx={bx} cy={by} r="14" fill="#EB6B1E" opacity="0.15" />
      <circle cx={bx} cy={by} r="6" fill="#EB6B1E" stroke="#fff" strokeWidth="2" />
      <text x={bx + 12} y={by + 4} fontSize="11" fontWeight="700" fill="#1A2332">
        MD {currentMD.toLocaleString('es-AR')} m
      </text>

      {/* casing annotations */}
      {[
        { md: 800, label: 'Cañería 9⅝"' },
        { md: 1400, label: 'Liner 7"' },
      ].map((c, i) => {
        const pt = planned.find((p) => p.md === c.md);
        if (!pt) return null;
        const [cx, cy] = P(pt.x, pt.y);
        return (
          <g key={i}>
            <circle cx={cx} cy={cy} r="3" fill="#1A2332" />
            <text x={cx + 6} y={cy - 4} fontSize="9" fill="#475569">
              {c.label}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

Object.assign(window, { DrillingModule, DrillingInfoView, InfoRow });
