/* pages/Sop.jsx — SOP / Procedimiento Operativo Estándar.
   The functional source of truth for M1: every critical workflow the app supports,
   written as step-by-step onboarding + reference for the front office. Bilingual. */
(function () {
  const { t } = window.RZH;
  const D = window.RZDATA;
  const CUR = D.MONTHS[D.CUR];
  const NSTU = D.totals.total;

  // Each workflow: id · icon · which screen · when to use · numbered steps. (es/en)
  const FLOWS = [
    { id:'registrar', ico:'💵',
      es:{ t:'Registrar un pago', where:'Libro de Pago', when:'Cuando un acudiente paga matrícula, costos o una pensión.',
        steps:['En el Libro de Pago, busque al estudiante (barra de búsqueda) o use el botón verde «Registrar Pago».',
          'Haga clic en la casilla del mes pendiente (en rojo) del estudiante. Se abre la ventana de registro.',
          'Paso 1 — Método: elija Efectivo o Transferencia.',
          'Paso 2 — Registrar: escriba la referencia (transferencia) o el N° de recibo de caja (efectivo) y la fecha; confirme.',
          'Paso 3 — Recibo: aparece el recibo. Use «Imprimir» para entregarlo al acudiente. La casilla del mes queda en verde y el saldo baja.'] },
      en:{ t:'Register a payment', where:'Payment Ledger', when:'When a guardian pays enrollment, fees, or a monthly tuition.',
        steps:['In the Payment Ledger, find the student (search bar) or click the green “Register Payment” button.',
          'Click the student’s outstanding month cell (shown in red). The register window opens.',
          'Step 1 — Method: choose Cash or Transfer.',
          'Step 2 — Record: enter the reference (transfer) or cash-receipt # (cash) and the date; confirm.',
          'Step 3 — Receipt: the receipt appears. Use “Print” to hand it to the guardian. The month cell turns green and the balance drops.'] } },

    { id:'recibo', ico:'🧾',
      es:{ t:'Ver e imprimir un recibo', where:'Libro de Pago',
        when:'Para reimprimir el comprobante de un mes ya pagado.',
        steps:['Haga clic en una casilla de mes en verde (ya pagado).','Se abre el recibo en modo solo lectura: N° de recibo, medio, referencia, fecha y conciliación.','Pulse «Imprimir». Se imprime únicamente el recibo (sin el resto de la pantalla).'] },
      en:{ t:'View & print a receipt', where:'Payment Ledger',
        when:'To reprint the proof of an already-paid month.',
        steps:['Click any green (paid) month cell.','The receipt opens read-only: receipt #, method, reference, date, and reconciliation.','Press “Print”. Only the receipt prints (not the rest of the screen).'] } },

    { id:'buscar', ico:'🔎',
      es:{ t:'Buscar un estudiante o familia', where:'Libro de Pago',
        when:'Para ubicar rápido a un estudiante, un acudiente o todos los hermanos.',
        steps:['Escriba el nombre del estudiante o del acudiente en la barra de búsqueda.','Filtre por Grado o por Estado (al día, mora 1, mora 2+, sin matrícula).','Use las Vistas rápidas (Mora 1+, Mora 2+) o active «Familias» para agrupar a los hermanos por acudiente.','Haga clic en el nombre para abrir la ficha del estudiante.'] },
      en:{ t:'Find a student or family', where:'Payment Ledger',
        when:'To quickly locate a student, a guardian, or all siblings.',
        steps:['Type the student or guardian name in the search bar.','Filter by Grade or by Status (current, 1-month late, 2+ late, no enrollment).','Use the Quick views (Late 1+, Late 2+) or turn on “Households” to group siblings by guardian.','Click a name to open the student’s file.'] } },

    { id:'leer', ico:'🎨',
      es:{ t:'Leer el libro y las convenciones', where:'Libro de Pago',
        when:'Para entender los colores y las cifras de la tabla.',
        steps:['Verde = mes pagado. Rojo = mes pendiente. Amarillo = mes en curso ('+CUR+'). Gris = meses futuros (aún no se deben).','Cada casilla de mes muestra el valor de la pensión en COP.','«Saldo en mora» suma solo lo vencido a la fecha; los meses futuros NO cuentan como mora.','La fila inferior muestra el total mostrado, la mora en vista y cuántos están al día.'] },
      en:{ t:'Read the ledger & legend', where:'Payment Ledger',
        when:'To understand the colors and figures in the table.',
        steps:['Green = paid month. Red = outstanding month. Yellow = current month ('+CUR+'). Grey = future months (not yet due).','Each month cell shows the tuition amount in COP.','“Overdue balance” sums only what is past due to date; future months do NOT count as overdue.','The bottom row shows the rows displayed, overdue in view, and how many are current.'] } },

    { id:'columnas', ico:'▦',
      es:{ t:'Mostrar columnas y vistas', where:'Libro de Pago',
        when:'Para simplificar la tabla o enfocarse en un mes.',
        steps:['Pulse «Mostrar columnas» (arriba a la derecha de la tabla).','Marque o desmarque las columnas; o elija una vista predefinida (Completa, Cobro de morosos, Pagos del mes, Resumen).','Para ver un solo mes use el menú «Todos los meses» (los meses NO se controlan desde Mostrar columnas).','Haga clic en el encabezado de una columna para ordenar.'] },
      en:{ t:'Columns & preset views', where:'Payment Ledger',
        when:'To simplify the table or focus on one month.',
        steps:['Click “Show columns” (top-right of the table).','Check or uncheck columns; or pick a preset (Full, Collections, Monthly payments, Summary).','To see a single month use the “All Months” menu (months are NOT controlled from Show columns).','Click a column header to sort.'] } },

    { id:'whatsapp', ico:'🟢',
      es:{ t:'Enviar un recordatorio por WhatsApp', where:'Panel derecho (WhatsApp)',
        when:'Para cobrar mora o avisar a uno o varios acudientes.',
        steps:['Para uno: abra la ficha o seleccione la casilla del estudiante → el panel derecho muestra al destinatario.','Para varios: marque las casillas de la tabla → el panel suma a los destinatarios.','Revise el desglose: elegibles (con opt-in) · sin opt-in · no emparejados. Solo se envía a los elegibles.','Elija la plantilla (Cobro/Utilidad), revise el texto y pulse «Enviar».'] },
      en:{ t:'Send a WhatsApp reminder', where:'Right panel (WhatsApp)',
        when:'To collect overdue balances or notify one or more guardians.',
        steps:['For one: open the file or tick the student’s checkbox → the right panel shows the recipient.','For many: tick rows in the table → the panel adds them as recipients.','Check the breakdown: eligible (opted-in) · no opt-in · not paired. Only eligible recipients are sent to.','Pick the template (Billing/Utility), review the text, and press “Send”.'] } },

    { id:'mensajes', ico:'💬',
      es:{ t:'Atender el Centro de Mensajes', where:'Centro de Mensajes',
        when:'Para responder las preguntas de los acudientes durante el día.',
        steps:['Las conversaciones se ordenan por prioridad: mora primero.','Abra una conversación: verá el hilo y la ficha de la familia (saldo, estudiantes, opt-in).','Use una plantilla o escriba; la IA redacta pero nunca inventa montos (los toma del libro).','Adjunte el botón «Pagar ahora» y envíe (solo si la familia tiene opt-in de utilidad).'] },
      en:{ t:'Work the Message Center', where:'Message Center',
        when:'To answer guardians’ questions through the day.',
        steps:['Conversations are sorted by priority: overdue first.','Open a conversation: you see the thread and the family profile (balance, students, opt-in).','Use a template or type; the AI drafts but never invents amounts (it reads them from the ledger).','Attach the “Pay now” button and send (only if the family has utility opt-in).'] } },

    { id:'conciliar', ico:'✓',
      es:{ t:'Conciliar un pago', where:'Recibo / Ficha',
        when:'Para que cada pago tenga su factura y su comprobante.',
        steps:['Cada pago requiere la factura ClausERP más el comprobante del medio: efectivo → recibo de caja; transferencia → N° de comprobante.','Al registrar, capture la referencia/recibo; el recibo muestra «Conciliado ✓».','Si falta el dato, queda «Pendiente» hasta que se vincule.','La fuente de verdad contable sigue siendo ClausERP.'] },
      en:{ t:'Reconcile a payment', where:'Receipt / File',
        when:'So every payment has its invoice and its proof.',
        steps:['Each payment needs the ClausERP invoice plus the method proof: cash → cash-receipt #; transfer → voucher #.','When recording, capture the reference/receipt; the receipt then shows “Reconciled ✓”.','If the datum is missing, it stays “Pending” until linked.','The accounting source of truth remains ClausERP.'] } },

    { id:'datos', ico:'📤',
      es:{ t:'Exportar e importar (CSV)', where:'Libro de Pago / Configuración',
        when:'Para llevar los datos a Excel o cargar una actualización.',
        steps:['Pulse «Importar / Exportar» (arriba) o vaya a Configuración → Datos.','Exportar descarga el libro como CSV (se abre en Excel).','Importar permite cargar un CSV (representado en esta vista previa).','La integración real es con SINAI / ClausERP; esta vista no los reemplaza.'] },
      en:{ t:'Export & import (CSV)', where:'Payment Ledger / Settings',
        when:'To take the data to Excel or load an update.',
        steps:['Click “Import / Export” (top) or go to Settings → Data.','Export downloads the ledger as CSV (opens in Excel).','Import lets you load a CSV (depicted in this preview).','The real integration is with SINAI / ClausERP; this view does not replace them.'] } },

    { id:'hoy', ico:'📅',
      es:{ t:'Cierre de caja — Pagos de hoy', where:'Panel izquierdo',
        when:'Para revisar lo recibido en el día.',
        steps:['En el panel izquierdo, la sección «Pagos de hoy» lista los pagos recientes.','Haga clic en cualquier pago para abrir su recibo.','Verifique medio y referencia de cada uno contra la caja física.'] },
      en:{ t:'Day close — Today’s payments', where:'Left panel',
        when:'To review what came in during the day.',
        steps:['In the left panel, the “Today’s payments” section lists recent payments.','Click any payment to open its receipt.','Check each one’s method and reference against the physical cash box.'] } },
  ];

  function Flow({ f, lang, n }) {
    const c = f[lang];
    return (
      <section className="sop-card" id={'sop-' + f.id}>
        <div className="sop-card-hd">
          <span className="sop-num">{n}</span>
          <span className="sop-ico" aria-hidden="true">{f.ico}</span>
          <div className="sop-card-ttl">
            <h3>{c.t}</h3>
            <span className="sop-where">{c.where}</span>
          </div>
        </div>
        <p className="sop-when"><b>{t(lang,'Cuándo','When')}:</b> {c.when}</p>
        <ol className="sop-steps">{c.steps.map((s, i) => <li key={i}>{s}</li>)}</ol>
      </section>
    );
  }

  function Sop({ lang }) {
    const scrollTo = (id) => { const el = document.getElementById('sop-' + id); if (el) el.scrollIntoView({ behavior:'smooth', block:'start' }); };
    return (
      <div className="pg sop-pg" data-screen-label="SOP">
        <h1 className="page-title" style={{ marginBottom: 4 }}>{t(lang,'Procedimiento Operativo Estándar','Standard Operating Procedure')}
          <small>{t(lang,'Guía de operación del Libro de Pago · M1 · la fuente de verdad de los flujos','Payment-Ledger operating guide · M1 · the source of truth for the workflows')}</small>
        </h1>

        <div className="card sop-intro">
          <p>{t(lang,
            'Esta guía explica, paso a paso, los flujos críticos que la aplicación soporta hoy (M1). Sirve para capacitar a una secretaria nueva y como referencia diaria. Cada flujo indica dónde se hace y cuándo se usa.',
            'This guide explains, step by step, the critical workflows the app supports today (M1). Use it to train a new secretary and as a daily reference. Each workflow states where it happens and when to use it.')}</p>
          <div className="sop-index">
            {FLOWS.map((f) => (
              <button type="button" key={f.id} className="sop-chip" onClick={() => scrollTo(f.id)}>
                <span aria-hidden="true">{f.ico}</span> {f[lang].t}
              </button>
            ))}
          </div>
        </div>

        <div className="sop-grid">
          {FLOWS.map((f, i) => <Flow key={f.id} f={f} lang={lang} n={i + 1} />)}
        </div>

        <p className="rz-modal-note" style={{ textAlign:'left', marginTop:4 }}>{t(lang,
          'Vista previa con datos 100% ficticios ('+NSTU+' estudiantes). La contabilidad oficial vive en ClausERP; los envíos de WhatsApp están representados, no activos.',
          'Preview with 100% fabricated data ('+NSTU+' students). Official accounting lives in ClausERP; WhatsApp sends are depicted, not live.')}</p>
      </div>
    );
  }
  window.Sop = Sop;
})();
