// ─── Expedientes · tarjetas del detalle ─────────────────────────────
// Las piezas presentacionales del detalle de expediente: PartyCard (parte en
// modo lectura), MetaCol (label+value), DocSection (acordeón de documento del
// pipeline — TAMBIÉN lo consume screens-finanzas.jsx vía window.DocSection) y
// ExpedienteDocumentos (los 7 acordeones del pipeline armados desde el
// expediente resuelto). Extraídas de screens-detail.jsx en P6 al partirlo
// (detalle.jsx quedaba >400 líneas con ellas adentro). P6 también MATA acá
// PipelineProgress (0 renders en todo el repo, verificado por grep — muerto
// del mapa). Expone a window: PartyCard, DocSection, MetaCol,
// ExpedienteDocumentos. Consume Icon* (ui/icons.jsx), formatDate (dominio/
// formato.js), STATUS_CONFIG (dominio/pipeline.js).
//
// EXCEPCIÓN DE TECHO (~330 líneas, regla ~250/400 duro): un solo tema (las
// tarjetas del detalle de expediente); DocSection solo ya son ~170 líneas de
// estados visuales (vacío/completado/agregar-más/deshabilitado) — partirlo
// más separaría variantes del MISMO acordeón en archivos distintos.

const { useState: _useStateDC } = React;

// ─── Party card (Paciente / Médico / Entidad, modo lectura) ──
function PartyCard({ icon: Icon, eyebrow, primary, lines = [] }) {
  return (
    <div className="rounded-xl p-4" style={{
      background: 'color-mix(in oklab, var(--surface) 55%, transparent)',
      border: '1px solid color-mix(in oklab, var(--border) 50%, transparent)'
    }}>
      <div className="flex items-center gap-2.5 mb-3">
        <span className="inline-flex items-center justify-center rounded-lg"
        style={{
          width: 28, height: 28,
          background: 'color-mix(in oklab, var(--accent) 12%, transparent)',
          color: 'var(--accent)'
        }}>
          <Icon size={14} />
        </span>
        <p className="text-[10.5px] font-bold uppercase tracking-[0.12em]" style={{ color: 'var(--muted-foreground)' }}>
          {eyebrow}
        </p>
      </div>
      <p className="text-[15px] font-extrabold tracking-tight" style={{ color: 'var(--foreground)' }}>
        {primary}
      </p>
      <div className="mt-2 space-y-1">
        {lines.map((line, i) =>
        <p key={i} className="text-[12px]" style={{ color: 'var(--muted-foreground)' }}>
            {line}
          </p>
        )}
      </div>
    </div>);

}

// ─── Meta column (label uppercase + value) ──
function MetaCol({ label, value }) {
  return (
    <div className="space-y-1">
      <p className="text-[10px] font-bold uppercase tracking-[0.12em]" style={{ color: 'var(--muted-foreground)' }}>
        {label}
      </p>
      <p className="text-[13px] font-bold" style={{ color: 'var(--foreground)' }}>
        {value}
      </p>
    </div>);

}

// ─── Doc-section accordion ───────────────────────
function DocSection({ step, label, status, documents = [], emptyCta, addMoreCta, onAdd, onOpenDoc, code, disabled = false }) {
  const [open, setOpen] = _useStateDC(true);
  const isCompleted = status === 'COMPLETADO';

  return (
    <div className="rounded-2xl bg-card animate-fade-in-up" style={{
      border: '1px solid color-mix(in oklab, var(--border) 55%, transparent)',
      boxShadow: 'var(--shadow-card)'
    }}>
      {/* Header */}
      <button
        onClick={() => setOpen(!open)}
        className="flex w-full items-center justify-between gap-3 px-4 sm:px-5 py-4 text-left cursor-pointer transition-colors rounded-2xl"
        onMouseEnter={(e) => e.currentTarget.style.background = 'color-mix(in oklab, var(--surface) 40%, transparent)'}
        onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>

        <div className="flex items-center gap-3 sm:gap-4 min-w-0">
          <span className="inline-flex items-center justify-center rounded-full text-[11.5px] font-extrabold flex-shrink-0"
          style={{
            width: 30, height: 30,
            background: isCompleted ?
            'color-mix(in oklab, var(--accent) 14%, transparent)' :
            'color-mix(in oklab, var(--muted-foreground) 10%, transparent)',
            color: isCompleted ? 'var(--accent)' : 'var(--muted-foreground)'
          }}>
            {step}
          </span>
          <div className="flex flex-col gap-0.5 min-w-0">
            <span className="text-[13.5px] font-extrabold uppercase tracking-wide truncate" style={{ color: 'var(--foreground)' }}>
              {label}
            </span>
            <span className="text-[10.5px] font-bold uppercase tracking-[0.1em]"
            style={{ color: isCompleted ? 'var(--accent)' : 'var(--warning)' }}>
              {status}
            </span>
          </div>
        </div>
        <div className="flex items-center gap-3 flex-shrink-0">
          {code &&
          <span className="hidden sm:inline text-[12px] font-mono font-bold" style={{ color: 'var(--muted-foreground)' }}>
              {code}
            </span>
          }
          <span style={{ color: 'var(--muted-foreground)' }}>
            {open ? <IconChevronDown size={16} /> : <IconChevronRight size={16} />}
          </span>
        </div>
      </button>

      {/* Content */}
      {open &&
      <div className="px-5 pb-5 space-y-2" style={{ borderTop: '1px solid color-mix(in oklab, var(--border) 45%, transparent)' }}>
          <div className="pt-4 space-y-2">
            {documents.map((doc, i) =>
          <button
            key={i}
            onClick={disabled ? undefined : () => doc.openKey && onOpenDoc && onOpenDoc(doc.openKey)}
            aria-disabled={disabled}
            className={`w-full flex items-center gap-4 rounded-xl px-4 py-3.5 text-left transition-colors group ${disabled ? 'is-disabled' : 'cursor-pointer'}`}
            style={{
              background: 'color-mix(in oklab, var(--surface) 40%, transparent)',
              border: '1px solid color-mix(in oklab, var(--border) 40%, transparent)',
              opacity: disabled ? 0.6 : 1
            }}
            onMouseEnter={(e) => {
              if (disabled) return;
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--accent) 40%, var(--border))';
              e.currentTarget.style.background = 'color-mix(in oklab, var(--accent) 4%, var(--card))';
            }}
            onMouseLeave={(e) => {
              if (disabled) return;
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--border) 40%, transparent)';
              e.currentTarget.style.background = 'color-mix(in oklab, var(--surface) 40%, transparent)';
            }}>

                <span className="inline-flex items-center justify-center rounded-lg flex-shrink-0"
            style={{
              width: 38, height: 38,
              background: 'color-mix(in oklab, var(--accent) 10%, transparent)',
              color: 'var(--accent)'
            }}>
                  <IconFileText size={17} />
                </span>
                <div className="flex-1 min-w-0">
                  <p className="text-[11.5px] font-mono font-bold tracking-wide uppercase" style={{ color: 'var(--accent)' }}>
                    {doc.numero}
                  </p>
                  <p className="text-[13px] font-bold mt-0.5" style={{ color: 'var(--foreground)' }}>
                    {doc.titulo}
                  </p>
                  {doc.fecha &&
              <p className="text-[10.5px] font-bold uppercase tracking-[0.08em] mt-1" style={{ color: 'var(--muted-foreground)' }}>
                      Emitido el {formatDate(doc.fecha)}
                    </p>
              }
                </div>
                <span className="flex-shrink-0 transition-all" style={{ color: 'var(--muted-foreground)' }}>
                  <IconArrowUpRight size={16} />
                </span>
              </button>
          )}
            {documents.length > 0 && addMoreCta && !disabled &&
          <button
            onClick={onAdd}
            className="flex w-full items-center gap-2.5 rounded-xl px-4 py-3 text-left text-[12.5px] font-bold transition-colors cursor-pointer"
            style={{ border: '1px dashed color-mix(in oklab, var(--border) 75%, transparent)', color: 'var(--muted-foreground)' }}
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--accent) 55%, var(--border))';
              e.currentTarget.style.color = 'var(--accent)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--border) 75%, transparent)';
              e.currentTarget.style.color = 'var(--muted-foreground)';
            }}>
                <IconPlus size={14} />
                {addMoreCta}
              </button>
          }
            {documents.length === 0 && isCompleted &&
          <button
            onClick={disabled ? undefined : onAdd}
            aria-disabled={disabled}
            className={`flex w-full items-center gap-2.5 rounded-xl px-4 py-3.5 text-left text-[12.5px] font-medium transition-colors group ${disabled ? 'is-disabled' : 'cursor-pointer'}`}
            style={{ border: '1px dashed color-mix(in oklab, var(--border) 70%, transparent)', color: 'var(--muted-foreground)' }}
            onMouseEnter={(e) => {
              if (disabled) return;
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--accent) 45%, var(--border))';
              e.currentTarget.style.background = 'color-mix(in oklab, var(--accent) 4%, var(--card))';
            }}
            onMouseLeave={(e) => {
              if (disabled) return;
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--border) 70%, transparent)';
              e.currentTarget.style.background = 'transparent';
            }}>
                <IconCheck size={14} style={{ color: 'var(--accent)' }} />
                <span className="flex-1">Registrado en el expediente · documento sin digitalizar</span>
                <span className="flex-shrink-0" style={{ color: 'var(--muted-foreground)' }}>
                  <IconArrowUpRight size={16} />
                </span>
              </button>
          }
            {documents.length === 0 && !isCompleted && emptyCta &&
          <button
            onClick={disabled ? undefined : onAdd}
            aria-disabled={disabled}
            className={`flex w-full items-center gap-3 rounded-xl px-4 py-4 text-[13px] font-semibold transition-colors ${disabled ? 'is-disabled' : 'cursor-pointer'}`}
            style={{
              border: '1px dashed color-mix(in oklab, var(--border) 80%, transparent)',
              color: 'var(--muted-foreground)',
              opacity: disabled ? 0.6 : 1
            }}
            onMouseEnter={(e) => {
              if (disabled) return;
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--accent) 60%, var(--border))';
              e.currentTarget.style.color = 'var(--accent)';
            }}
            onMouseLeave={(e) => {
              if (disabled) return;
              e.currentTarget.style.borderColor = 'color-mix(in oklab, var(--border) 80%, transparent)';
              e.currentTarget.style.color = 'var(--muted-foreground)';
            }}>

                <IconPlus size={15} />
                {emptyCta}
              </button>
          }
          </div>
        </div>
      }
    </div>);

}

// ─── Los 7 acordeones del pipeline ───────────────────────────────
// `exp` viene YA resuelto (MicosResolveExpedienteDocs — camino genérico único,
// P6). `status` es el estado mostrado (el borrador si se está editando).
function ExpedienteDocumentos({ exp, status, onOpenSubview }) {
  // pipeline strip indices: 0 INICIO, 1 PRESUPUESTO, 2 OC, 3 REMITO, 4 DOC, 5 FACTURA, 6 RECIBO
  const stripStep = (STATUS_CONFIG[status] || STATUS_CONFIG.INICIADO).step;
  // Coherencia estado↔documentos: si el expediente ya pasó por ese paso, el
  // documento se considera COMPLETADO aunque no tengamos el archivo digitalizado.
  const stepStatus = (sectionStep) => stripStep >= sectionStep ? 'COMPLETADO' : 'PENDIENTE';

  return (
    <>
      {/* FIX (P15, H2): `code`/`numero` mostraban `PRE-${numero}` a mano, dropeando el `L-`
          de un presupuesto/OC/remito legacy — ahora el publicId real de la fila. Ídem OC/Remito abajo. */}
      <DocSection
        step={1}
        label="Presupuesto"
        status={exp.presupuesto ? 'COMPLETADO' : stepStatus(1)}
        code={exp.presupuesto ? exp.presupuesto.publicId : null}
        documents={exp.presupuesto ? [{
          numero: exp.presupuesto.publicId,
          titulo: 'Presupuesto inicial',
          fecha: exp.presupuesto.fechaEmision,
          openKey: 'presupuesto'
        }] : []}
        emptyCta="Crear presupuesto"
        onOpenDoc={onOpenSubview}
        onAdd={() => onOpenSubview && onOpenSubview('presupuesto')} />

      <DocSection
        step={2}
        label="Orden de Compra"
        status={exp.ordenCompra ? 'COMPLETADO' : stepStatus(2)}
        code={exp.ordenCompra ? exp.ordenCompra.publicId : null}
        documents={exp.ordenCompra ? [{
          numero: exp.ordenCompra.publicId,
          titulo: `OC de ${exp.entidad?.razonSocial || (exp.particular && exp.particular.nombre ? exp.particular.nombre + ' ' + exp.particular.apellido : 'cliente')}`,
          fecha: exp.ordenCompra.fechaEmision,
          openKey: 'orden-compra'
        }] : []}
        emptyCta="Crear orden de compra"
        onOpenDoc={onOpenSubview}
        onAdd={() => onOpenSubview && onOpenSubview('orden-compra')} />

      <DocSection
        step={3}
        label="Remito"
        status={exp.remito ? 'COMPLETADO' : stepStatus(3)}
        code={exp.remito ? exp.remito.publicId : null}
        documents={exp.remito ? [{
          numero: exp.remito.publicId,
          titulo: 'Remito de entrega',
          fecha: exp.remito.fechaEmision,
          openKey: 'remito'
        }] : []}
        emptyCta="Emitir remito"
        onOpenDoc={onOpenSubview}
        onAdd={() => onOpenSubview && onOpenSubview('remito')} />

      <DocSection
        step={4}
        label="Documentación médica"
        status={(exp.documentacionMedica || []).length > 0 ? 'COMPLETADO' : stepStatus(4)}
        documents={(exp.documentacionMedica || []).length > 0 ? [{
          numero: 'DOC-MED',
          titulo: `${exp.documentacionMedica.length} archivo${exp.documentacionMedica.length === 1 ? '' : 's'} adjunto${exp.documentacionMedica.length === 1 ? '' : 's'}`,
          openKey: 'documentacion-medica'
        }] : []}
        emptyCta="Adjuntar documentos médicos"
        onOpenDoc={onOpenSubview}
        onAdd={() => onOpenSubview && onOpenSubview('documentacion-medica')} />

      <DocSection
        step={5}
        label="Facturas"
        status={(exp.facturas || []).length > 0 ? 'COMPLETADO' : stepStatus(5)}
        code={(exp.facturas || []).length > 1 ? `${exp.facturas.length} facturas` : null}
        documents={(exp.facturas || []).map((f, i) => ({
          numero: `FAC-${f.tipoFactura}-${String(f.puntoVenta).padStart(4, '0')}-${f.numero}`,
          titulo: `Factura ${f.tipoFactura}`,
          fecha: f.fechaEmision,
          openKey: `factura:${i}`,
        }))}
        emptyCta="Emitir factura"
        addMoreCta="Emitir otra factura"
        onOpenDoc={onOpenSubview}
        onAdd={() => onOpenSubview && onOpenSubview(`factura:${(exp.facturas || []).length}`)} />

      <DocSection
        step={6}
        label="Recibo"
        status={exp.recibo ? 'COMPLETADO' : stepStatus(6)}
        code={exp.recibo ? (exp.recibo.numeroComprobante || exp.recibo.publicId) : null}
        documents={exp.recibo ? [{
          // numeroComprobante no es columna real (whitelist de /api/recibos) — para
          // recibos reales cae al publicId, nunca a un placeholder vacío.
          numero: exp.recibo.numeroComprobante || exp.recibo.publicId,
          titulo: 'Recibo de cobro',
          fecha: exp.recibo.fechaCobro,
          openKey: 'recibo'
        }] : []}
        emptyCta="Registrar cobro"
        onOpenDoc={onOpenSubview}
        onAdd={() => onOpenSubview && onOpenSubview('recibo')} />

      <DocSection
        step={7}
        label="Documentación extra"
        status={(exp.documentacionExtra || []).length > 0 ? 'COMPLETADO' : 'PENDIENTE'}
        documents={(exp.documentacionExtra || []).length > 0 ? [{
          numero: 'DOC-EXTRA',
          titulo: `${exp.documentacionExtra.length} archivo${exp.documentacionExtra.length === 1 ? '' : 's'} adjunto${exp.documentacionExtra.length === 1 ? '' : 's'}`,
          openKey: 'documentacion-extra'
        }] : []}
        emptyCta="Adjuntar documentación adicional"
        onOpenDoc={onOpenSubview}
        onAdd={() => onOpenSubview && onOpenSubview('documentacion-extra')} />
    </>);

}

Object.assign(window, { PartyCard, DocSection, MetaCol, ExpedienteDocumentos });
