// portal-canjes.jsx — Canje tracker (patient) + Operator submission queue
const { useState, useMemo } = React;

// ── Helpers ───────────────────────────────────────────────────────────────────
function getProgramById(id) { return (window.LAB_PROGRAMS || []).find(p => p.id === id); }
function getLabById(id)     { return (window.LABS || []).find(l => l.id === id); }
function getPatientById(id) { return (window.PATIENTS || []).find(p => p.id === id); }

function programTypeLabel(buyQty, freeQty) { return `${buyQty}+${freeQty}`; }

// ── EnrollModal — browse available programs to join ───────────────────────────
function EnrollModal({ patient, enrollments, onEnroll, onClose }) {
  const C = window.C;
  const [labFilter, setLabFilter] = useState('all');
  const enrolledIds = enrollments.map(e => e.programId);
  const available = (window.LAB_PROGRAMS || []).filter(p => !enrolledIds.includes(p.id));
  const filtered = labFilter === 'all' ? available : available.filter(p => p.labId === labFilter);

  return (
    <window.Modal visible={true} onClose={onClose} title="Inscribirse en programa" height="95%">
      {/* Lab filter chips */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
        {['all', 'lafage', 'lancasco', 'denk', 'pharmaetica'].map(id => {
          const lab = id === 'all' ? null : getLabById(id);
          const active = labFilter === id;
          return (
            <button key={id} onClick={() => setLabFilter(id)} style={{
              fontSize: 11, fontWeight: 700, padding: '4px 12px', borderRadius: 9999,
              border: `1.5px solid ${active ? (lab?.color || C.primary) : C.border}`,
              background: active ? (lab?.colorLight || C.primarySurface) : C.surface,
              color: active ? (lab?.color || C.primary) : C.text2, cursor: 'pointer',
            }}>{id === 'all' ? 'Todos los labs' : lab?.name}</button>
          );
        })}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {filtered.map(prog => {
          const lab = getLabById(prog.labId);
          return (
            <div key={prog.id} style={{ background: C.surfaceWarm, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: C.text1, marginBottom: 3 }}>{prog.medicine}</div>
                  <div style={{ fontSize: 11, color: C.text3, marginBottom: 4 }}>{prog.condition}</div>
                  <window.LabBadge labId={prog.labId} />
                </div>
                <div style={{ textAlign: 'center', background: lab?.color || C.primary, color: '#fff', borderRadius: 10, padding: '6px 10px', marginLeft: 10, minWidth: 44 }}>
                  <div style={{ fontSize: 16, fontWeight: 900 }}>{programTypeLabel(prog.buyQty, prog.freeQty)}</div>
                  <div style={{ fontSize: 8, fontWeight: 700, opacity: .8 }}>PROG.</div>
                </div>
              </div>
              <button onClick={() => onEnroll(prog)} style={{
                width: '100%', padding: '8px', borderRadius: 10, border: 'none',
                background: C.primary, color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer',
              }}>+ Inscribirme</button>
            </div>
          );
        })}
        {filtered.length === 0 && <window.EmptyState icon="✓" title="Ya estás inscrito en todos los programas disponibles" />}
      </div>
    </window.Modal>
  );
}

// ── CanjeCard — single enrolled program ───────────────────────────────────────
function CanjeCard({ enrollment, onRegisterPurchase }) {
  const C = window.C;
  const prog = getProgramById(enrollment.programId);
  const lab  = getLabById(prog?.labId);
  if (!prog || !lab) return null;

  const total     = prog.buyQty;
  const logged    = enrollment.purchasesLogged;
  const pending   = enrollment.purchasesPending;
  const effective = logged + pending; // shown as total purchases
  const isReady   = enrollment.rewardsPending > 0;
  const pct       = Math.min((effective / total) * 100, 100);

  return (
    <div style={{
      background: isReady ? C.successLight : C.surface,
      border: `1.5px solid ${isReady ? C.success : C.border}`,
      borderRadius: 16, padding: 16, marginBottom: 12,
      boxShadow: '0 1px 6px rgba(8,54,47,.06)',
    }}>
      {/* Header row */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
        <div style={{ flex: 1, marginRight: 10 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: C.text1, marginBottom: 4 }}>{prog.medicine}</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            <window.LabBadge labId={prog.labId} />
            <span style={{ fontSize: 10, fontWeight: 700, color: C.text3, background: C.surfaceWarm, border: `1px solid ${C.border}`, borderRadius: 9999, padding: '2px 8px' }}>
              {programTypeLabel(prog.buyQty, prog.freeQty)}
            </span>
            {pending > 0 && (
              <span style={{ fontSize: 10, fontWeight: 700, color: C.warning, background: C.warningLight, border: `1px solid ${C.warning}`, borderRadius: 9999, padding: '2px 8px' }}>
                {pending} en espera de portal
              </span>
            )}
          </div>
        </div>
        {/* Program ratio badge */}
        <div style={{ textAlign: 'center', background: isReady ? C.success : lab.color, color: '#fff', borderRadius: 12, padding: '8px 12px', minWidth: 52 }}>
          <div style={{ fontSize: 18, fontWeight: 900 }}>{programTypeLabel(prog.buyQty, prog.freeQty)}</div>
          <div style={{ fontSize: 8, fontWeight: 700, opacity: .8 }}>CANJE</div>
        </div>
      </div>

      {/* Progress */}
      {isReady ? (
        <div style={{ background: C.success, borderRadius: 10, padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
          <span style={{ fontSize: 22 }}>✦</span>
          <div>
            <div style={{ fontSize: 13, fontWeight: 800, color: '#fff' }}>¡Canje disponible!</div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,.85)' }}>{enrollment.rewardsPending} caja{enrollment.rewardsPending > 1 ? 's' : ''} gratis lista{enrollment.rewardsPending > 1 ? 's' : ''} para recoger</div>
          </div>
        </div>
      ) : (
        <div style={{ marginBottom: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ fontSize: 12, color: C.text2 }}>
              <strong style={{ color: C.text1 }}>{effective}</strong> / {total} compras registradas
            </span>
            <span style={{ fontSize: 12, fontWeight: 700, color: lab.color }}>{total - effective > 0 ? `Falta${total - effective > 1 ? 'n' : ''} ${total - effective}` : 'Completo'}</span>
          </div>
          <window.ProgressBar value={effective} max={total} color={lab.color} height={8} />
        </div>
      )}

      {/* Condition tag */}
      <div style={{ fontSize: 11, color: C.text3, marginBottom: isReady ? 0 : 10 }}>{prog.condition}</div>

      {/* Actions */}
      {!isReady && (
        <button onClick={() => onRegisterPurchase(enrollment, prog)} style={{
          width: '100%', padding: '9px', borderRadius: 10, border: 'none',
          background: C.primarySurface, color: C.primary, fontSize: 12, fontWeight: 700, cursor: 'pointer',
        }}>
          + Registrar compra reciente
        </button>
      )}
    </div>
  );
}

// ── RegisterPurchaseModal ─────────────────────────────────────────────────────
function RegisterPurchaseModal({ enrollment, prog, patient, onConfirm, onClose }) {
  const C = window.C;
  const [date, setDate] = useState(new Date().toISOString().split('T')[0]);
  const lab = getLabById(prog?.labId);

  return (
    <window.Modal visible={true} onClose={onClose} title="Registrar compra">
      <div style={{ background: C.surfaceWarm, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14, marginBottom: 16 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: C.text1, marginBottom: 4 }}>{prog?.medicine}</div>
        <window.LabBadge labId={prog?.labId} />
        <div style={{ fontSize: 12, color: C.text3, marginTop: 6 }}>Programa {prog?.buyQty}+{prog?.freeQty} · {lab?.name}</div>
      </div>

      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: C.text2, marginBottom: 6 }}>Fecha de compra en Farmacia Santos</div>
        <input type="date" value={date} onChange={e => setDate(e.target.value)} style={{
          width: '100%', padding: '10px 14px', borderRadius: 10, border: `1.5px solid ${C.border}`,
          fontFamily: 'inherit', fontSize: 14, color: C.text1, background: C.bg,
        }} />
      </div>

      <div style={{ background: C.infoLight, border: `1px solid ${C.info}`, borderRadius: 12, padding: 12, marginBottom: 16, fontSize: 12, color: C.primaryDark, lineHeight: 1.5 }}>
        <strong>¿Cómo funciona?</strong> Un operador de la farmacia enviará esta compra al portal de {lab?.name}. Una vez confirmada, tu progreso se actualizará automáticamente.
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={onClose} style={{ flex: 1, padding: 11, borderRadius: 12, border: `1.5px solid ${C.border}`, background: C.surface, color: C.text2, fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>Cancelar</button>
        <button onClick={() => onConfirm(enrollment, date)} style={{ flex: 2, padding: 11, borderRadius: 12, border: 'none', background: C.primary, color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>✓ Registrar compra</button>
      </div>
    </window.Modal>
  );
}

// ── CanjesTab — patient-facing view ──────────────────────────────────────────
function CanjesTab({ patient, enrollments, onAddEnrollment, onRegisterPurchase }) {
  const C = window.C;
  const [showEnroll, setShowEnroll]     = useState(false);
  const [regTarget, setRegTarget]       = useState(null); // { enrollment, prog }

  const myEnrollments = enrollments.filter(e => e.customerId === patient.id);
  const readyCanjes   = myEnrollments.filter(e => e.rewardsPending > 0);
  const inProgress    = myEnrollments.filter(e => e.rewardsPending === 0);

  return (
    <div style={{ padding: '16px 16px 100px' }}>

      {/* Ready banner */}
      {readyCanjes.length > 0 && (
        <div style={{ background: C.success, borderRadius: 16, padding: '16px 18px', marginBottom: 20, display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ fontSize: 32 }}>✦</span>
          <div>
            <div style={{ fontSize: 16, fontWeight: 800, color: '#fff' }}>
              {readyCanjes.length === 1 ? '¡Tienes 1 canje listo!' : `¡Tienes ${readyCanjes.length} canjes listos!`}
            </div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,.8)', marginTop: 2 }}>Pasa a Farmacia Santos para recogerlos</div>
          </div>
        </div>
      )}

      {/* Ready canjes */}
      {readyCanjes.length > 0 && (
        <>
          <window.SectionLabel>LISTOS PARA RECOGER</window.SectionLabel>
          {readyCanjes.map(e => (
            <CanjeCard key={e.id} enrollment={e} onRegisterPurchase={(enr, prog) => setRegTarget({ enr, prog })} />
          ))}
        </>
      )}

      {/* In-progress */}
      {inProgress.length > 0 && (
        <>
          <window.SectionLabel style={{ marginTop: readyCanjes.length > 0 ? 8 : 0 }}>EN PROGRESO</window.SectionLabel>
          {inProgress.map(e => (
            <CanjeCard key={e.id} enrollment={e} onRegisterPurchase={(enr, prog) => setRegTarget({ enr, prog })} />
          ))}
        </>
      )}

      {myEnrollments.length === 0 && (
        <window.EmptyState icon="Rx" title="Sin programas activos" sub="Inscríbete en un programa de canje de laboratorio para empezar a acumular beneficios." />
      )}

      {/* Enroll CTA */}
      <button onClick={() => setShowEnroll(true)} style={{
        width: '100%', marginTop: 8, padding: '13px', borderRadius: 14,
        border: `2px dashed ${C.primaryLight}`, background: 'transparent',
        color: C.primary, fontSize: 13, fontWeight: 700, cursor: 'pointer',
      }}>
        + Inscribirme en un programa de canje
      </button>

      {/* Modals */}
      {showEnroll && (
        <EnrollModal patient={patient} enrollments={myEnrollments} onEnroll={(prog) => { onAddEnrollment(patient.id, prog); setShowEnroll(false); }} onClose={() => setShowEnroll(false)} />
      )}
      {regTarget && (
        <RegisterPurchaseModal enrollment={regTarget.enr} prog={regTarget.prog} patient={patient}
          onConfirm={(enr, date) => { onRegisterPurchase(enr.id, date); setRegTarget(null); }}
          onClose={() => setRegTarget(null)} />
      )}
    </div>
  );
}

// ── OperatorQueue — grouped submission list by lab ────────────────────────────
function OperatorQueue({ submissions, enrollments, onMarkSubmitted }) {
  const C = window.C;
  const [confirmed, setConfirmed] = useState(null);

  const pending = submissions.filter(s => !s.submittedToPortal);
  const byLab   = {};
  pending.forEach(s => {
    const prog = getProgramById(s.programId);
    if (!prog) return;
    if (!byLab[s.labId]) byLab[s.labId] = [];
    byLab[s.labId].push({ ...s, prog });
  });

  const handleMark = (sub) => {
    setConfirmed(null);
    onMarkSubmitted(sub.id);
  };

  return (
    <div style={{ padding: '16px 16px 80px' }}>
      {/* Summary */}
      <div style={{ background: C.primary, borderRadius: 16, padding: '16px 18px', marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,.7)', marginBottom: 2 }}>ENVÍOS PENDIENTES</div>
          <div style={{ fontSize: 30, fontWeight: 900, color: '#fff' }}>{pending.length}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,.6)' }}>en {Object.keys(byLab).length} portal{Object.keys(byLab).length > 1 ? 'es' : ''}</div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,.5)', marginTop: 4 }}>Última actualización: Hoy 5:00 AM</div>
        </div>
      </div>

      {pending.length === 0 && <window.EmptyState icon="✓" title="Todo al día" sub="No hay envíos pendientes en ningún portal de laboratorio." />}

      {/* Per-lab groups */}
      {Object.entries(byLab).map(([labId, items]) => {
        const lab = getLabById(labId);
        if (!lab) return null;
        return (
          <div key={labId} style={{ marginBottom: 24 }}>
            {/* Lab header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, padding: '10px 14px', background: lab.colorLight, borderRadius: 12, border: `1px solid ${lab.color}30` }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 800, color: lab.color }}>{lab.name}</div>
                <div style={{ fontSize: 11, color: lab.color + 'aa' }}>{items.length} envío{items.length > 1 ? 's' : ''} pendiente{items.length > 1 ? 's' : ''}</div>
              </div>
              <a href={lab.url} target="_blank" rel="noreferrer" style={{ fontSize: 11, fontWeight: 700, color: lab.color, textDecoration: 'none', background: lab.color + '18', border: `1px solid ${lab.color}40`, borderRadius: 8, padding: '5px 10px' }}>
                Abrir portal ↗
              </a>
            </div>

            {/* Submission rows */}
            {items.map(sub => {
              const patient = getPatientById(sub.customerId);
              const enr     = enrollments.find(e => e.id === sub.enrollmentId);
              if (!patient) return null;
              return (
                <div key={sub.id} style={{ background: C.surface, border: `1px solid ${C.border}`, borderRadius: 14, padding: 14, marginBottom: 8, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  {/* Avatar */}
                  <div style={{ width: 38, height: 38, borderRadius: '50%', background: lab.colorLight, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 800, color: lab.color, flexShrink: 0 }}>
                    {patient.iniciales}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: C.text1 }}>{patient.nombre}</div>
                    <div style={{ fontSize: 11, color: C.text3, fontFamily: 'DM Mono, monospace', marginBottom: 4 }}>{patient.dni}</div>
                    <div style={{ fontSize: 12, color: C.text2, marginBottom: 2 }}>{sub.prog.medicine}</div>
                    <div style={{ fontSize: 11, color: C.text3 }}>
                      Compra: {new Date(sub.date).toLocaleDateString('es-HN', { day: 'numeric', month: 'short' })}
                      {enr && ` · Progreso: ${enr.purchasesLogged + enr.purchasesPending}/${sub.prog.buyQty}`}
                    </div>
                  </div>
                  <button onClick={() => setConfirmed(sub)} style={{
                    flexShrink: 0, padding: '7px 12px', borderRadius: 10, border: 'none',
                    background: C.primarySurface, color: C.primary, fontSize: 11, fontWeight: 700, cursor: 'pointer',
                  }}>
                    ✓ Enviado
                  </button>
                </div>
              );
            })}
          </div>
        );
      })}

      {/* Confirm modal */}
      {confirmed && (
        <window.Modal visible={true} onClose={() => setConfirmed(null)} title="Confirmar envío al portal">
          {(() => {
            const patient = getPatientById(confirmed.customerId);
            const lab = getLabById(confirmed.labId);
            return (
              <>
                <div style={{ background: window.C.surfaceWarm, border: `1px solid ${window.C.border}`, borderRadius: 14, padding: 14, marginBottom: 16 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: window.C.text1, marginBottom: 4 }}>{confirmed.prog.medicine}</div>
                  <div style={{ fontSize: 12, color: window.C.text2 }}>{patient?.nombre} · {patient?.dni}</div>
                  <div style={{ fontSize: 11, color: window.C.text3, marginTop: 4 }}>Portal: {lab?.name} · {new Date(confirmed.date).toLocaleDateString('es-HN')}</div>
                </div>
                <div style={{ fontSize: 12, color: window.C.text2, lineHeight: 1.6, marginBottom: 16 }}>
                  ¿Confirmás que ya registraste esta compra en el portal de <strong>{lab?.name}</strong>?
                  El progreso del cliente se actualizará.
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button onClick={() => setConfirmed(null)} style={{ flex: 1, padding: 11, borderRadius: 12, border: `1.5px solid ${window.C.border}`, background: window.C.surface, color: window.C.text2, fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>Cancelar</button>
                  <button onClick={() => handleMark(confirmed)} style={{ flex: 2, padding: 11, borderRadius: 12, border: 'none', background: window.C.primary, color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>✓ Confirmar</button>
                </div>
              </>
            );
          })()}
        </window.Modal>
      )}
    </div>
  );
}

Object.assign(window, { CanjesTab, OperatorQueue });
