/* ============================================================
   AI4Colegios UI Kit — Ledger.jsx
   The center "Payment Book": KPI strip · unified toolbar (search /
   grade / status / vista / quick-view chips) · context strip ·
   the Excel-faithful ledger table (bands, sticky cols, status pills,
   press-an-unpaid-cell-to-register, conciliación dot).
   ============================================================ */
(function () {
  const { Import, Export, Search, WhatsApp, Check } = window.Icons;
  const { t, money } = window.RZH;
  const D = window.RZDATA;

  /* ---------- KPI strip ---------- */
  function KpiStrip({ lang }) {
    const T = D.totals;
    const tiles = [
      { lbl: t(lang, 'Recaudo año a la fecha', 'Year-to-date collections'), val: '$ ' + money(T.recaudoYTD), tag: 'COP' },
      { lbl: t(lang, 'Mora pendiente', 'Outstanding balance'), val: '$ ' + money(T.moraPendiente), tag: 'COP', cls: 'warn' },
      { lbl: t(lang, 'Estudiantes al día', 'Students current'), val: T.alDia + ' ' + t(lang, 'de', 'of') + ' ' + T.total, cls: 'good' },
      { lbl: t(lang, 'En mora 1+ mes', 'Overdue 1+ month'), val: T.enMora, cls: 'warn' },
      { lbl: t(lang, 'Total estudiantes', 'Total students'), val: T.total },
    ];
    return (
      <div className="stats">
        {tiles.map((s, i) => (
          <div key={i} className={'stat ' + (s.cls || '')}>
            <div className="lbl">{s.lbl}</div>
            <div className="val">{s.val}{s.tag && <span className="currency-tag">{s.tag}</span>}</div>
          </div>
        ))}
      </div>
    );
  }

  /* ---------- Toolbar ---------- */
  const QUICK = [
    { id: 'all', es: 'Todos', en: 'All' },
    { id: 'good', es: 'Al día', en: 'Current' },
    { id: 'mora', es: 'En mora', en: 'Overdue' },
    { id: 'mora2', es: 'Mora 2+ meses', en: '2+ months' },
  ];
  function Toolbar({ lang, query, setQuery, quick, setQuick, byFamily, setByFamily }) {
    return (
      <div className="toolbar">
        <div className="search-wrap">
          <Search className="search-ico" />
          <input value={query} onChange={(e) => setQuery(e.target.value)}
            placeholder={t(lang, 'Buscar por estudiante o acudiente', 'Find by student or guardian')} />
        </div>
        <select aria-label={t(lang, 'Grado', 'Grade')}><option>{t(lang, 'Todos los grados', 'All grades')}</option></select>
        <select aria-label={t(lang, 'Estado', 'Status')}><option>{t(lang, 'Todos los estados', 'All statuses')}</option></select>
        <span className="qv-label">{t(lang, 'Vistas rápidas', 'Quick views')}</span>
        {QUICK.map((q) => (
          <button key={q.id} type="button" className={'qv-chip' + (quick === q.id ? ' active' : '')}
            aria-pressed={quick === q.id} onClick={() => setQuick(q.id)}>{t(lang, q.es, q.en)}</button>
        ))}
        <button type="button" className={'qv-chip fam-chip' + (byFamily ? ' active' : '')}
          aria-pressed={byFamily} onClick={() => setByFamily(!byFamily)}>👪 {t(lang, 'Por familia', 'By family')}</button>
        <span className="spacer" />
        <button type="button" className="btn-ghost-mini vista-btn">▦ {t(lang, 'Vista', 'View')} : {t(lang, 'Completa', 'Full')} <span className="vista-count">25/25</span> ▾</button>
      </div>
    );
  }

  /* ---------- Status pill ---------- */
  const PILL = {
    good:   { cls: 'good',   es: 'AL DÍA',         en: 'CURRENT' },
    mora1:  { cls: 'mora1',  es: 'MORA 1 MES',     en: '1 MONTH LATE' },
    mora2:  { cls: 'mora2',  es: 'MORA 2+ MESES',  en: '2+ MONTHS LATE' },
    mora3:  { cls: 'mora2',  es: 'MORA 2+ MESES',  en: '2+ MONTHS LATE' },
    pagado: { cls: 'pagado', es: 'PAGADO',         en: 'PAID' },
  };
  function Pill({ status, lang }) {
    const p = PILL[status] || PILL.good;
    return <span className={'pill ' + p.cls}>{t(lang, p.es, p.en)}</span>;
  }

  /* ---------- Money / month cell ---------- */
  function MonthCell({ state, current, onPress, lang }) {
    const pressable = state === 'mora' || state === 'future' || state === 'empty';
    const cls = ['money', 'cell'];
    if (state === 'paid') cls.push('paid');
    else if (state === 'mora') cls.push('mora');
    else if (state === 'future') cls.push('future');
    if (current) cls.push('current-month-col');
    return (
      <td className={cls.join(' ')}
        role={pressable ? 'button' : undefined} tabIndex={pressable ? 0 : undefined}
        onClick={pressable ? onPress : undefined}
        onKeyDown={pressable ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onPress(); } } : undefined}
        title={state === 'paid' ? t(lang, 'Ya pagado', 'Already paid') : (pressable ? t(lang, 'Presione para registrar', 'Press to register') : '')}>
        {state === 'paid' ? '✓' : state === 'mora' ? '—' : ''}
      </td>
    );
  }

  /* ---------- Conciliación dot ---------- */
  function ConcilDot({ kind, lang }) {
    const map = { done: { c: 'done', s: '✓' }, pending: { c: 'pending', s: '•' }, na: { c: 'na', s: '—' } };
    const m = map[kind] || map.na;
    return <span className={'concil-dot ' + m.c} title={t(lang, 'Conciliación', 'Reconciliation')}>{m.s}</span>;
  }

  /* ---------- The table ---------- */
  function LedgerTable({ lang, rows, selected, onToggleRow, onToggleAll, allChecked, someChecked, onPressCell, onName, onWhatsApp }) {
    const MB = D.MONTHS, CUR = D.CUR;
    return (
      <div className="sheet">
        <table className="libro">
          <caption className="fee-cap">
            <div className="fee-inner">
              <span className="fee-label">{t(lang, 'Tarifas por nivel', 'Fees by level')}:</span>
              <span className="fee-item">{t(lang, 'Preescolar', 'Preschool')} <strong>$ 170,000</strong></span>
              <span className="fee-item">{t(lang, 'Primaria', 'Primary')} <strong>$ 165,000</strong></span>
              <span className="fee-item">{t(lang, 'Bachillerato', 'High school')} <strong>$ 180,000</strong></span>
              <span className="fee-note">· {t(lang, 'pensión mensual · COP', 'monthly tuition · COP')}</span>
            </div>
          </caption>
          <thead>
            <tr className="band-row">
              <th className="selcol band-id" colSpan={1}></th>
              <th className="band-id" colSpan={4}>{t(lang, 'Identidad', 'Identity')}</th>
              <th className="band-pay" colSpan={4}>{t(lang, 'Valor a pagar', 'Amount due')}</th>
              <th className="band-paid" colSpan={MB.length + 3}>{t(lang, 'Pagos realizados', 'Payments made')}</th>
              <th className="band-saldo" colSpan={2}>{t(lang, 'Saldo', 'Balance')}</th>
              <th className="band-acc" colSpan={1}>{t(lang, 'Acciones', 'Actions')}</th>
            </tr>
            <tr className="head-row">
              <th className="selcol sticky-0">
                <input type="checkbox" aria-label={t(lang, 'Seleccionar todo', 'Select all')}
                  checked={allChecked} ref={(el) => { if (el) el.indeterminate = someChecked && !allChecked; }}
                  onChange={onToggleAll} />
              </th>
              <th className="sticky-1 col-no">No</th>
              <th className="sticky-2 col-nm">{t(lang, 'Nombres', 'Names')}</th>
              <th className="sticky-3 col-gr">{t(lang, 'Grado', 'Grade')}</th>
              <th className="col-st">{t(lang, 'Estado', 'Status')}</th>
              <th className="money">{t(lang, 'Matrícula', 'Enrollment')}</th>
              <th className="money">{t(lang, 'Costos', 'Fees')}</th>
              <th className="money">{t(lang, 'Pensión/mes', 'Tuition/mo')}</th>
              <th className="money">{t(lang, 'Total año', 'Year total')}</th>
              <th className="money">{t(lang, 'Mat.✓', 'Enr.✓')}</th>
              <th className="money">{t(lang, 'Cos.✓', 'Fee✓')}</th>
              {MB.map((m, i) => <th key={m} className={'money mcol' + (i === CUR ? ' current-month' : '')}>{m}</th>)}
              <th className="money">{t(lang, 'Tot. pagado', 'Total paid')}</th>
              <th className="money">{t(lang, 'Debió pagar', 'Should have paid')}</th>
              <th className="money col-saldo">{t(lang, 'Saldo en mora', 'Overdue balance')}</th>
              <th className="col-acc">WhatsApp</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((s) => {
              const sel = selected.has(s.no);
              return (
                <tr key={s.no} className={sel ? 'row-selected' : ''}>
                  <td className="selcol sticky-0">
                    <input type="checkbox" checked={sel} onChange={() => onToggleRow(s.no)}
                      aria-label={t(lang, 'Seleccionar ', 'Select ') + s.nombres} />
                  </td>
                  <td className="sticky-1 col-no">{s.no}</td>
                  <td className="sticky-2 col-nm">
                    <button type="button" className="name-link" onClick={() => onName(s)}>{s.nombres}</button>
                    {s.famIdx != null && <span className="fam-count" title={t(lang, 'Hermanos', 'Siblings')}>⌂{D.fams[s.famIdx].members.length}</span>}
                  </td>
                  <td className="sticky-3 col-gr">{s.grado}</td>
                  <td className="col-st"><Pill status={s.status} lang={lang} /></td>
                  <td className="money auto">{money(s.matricula)}</td>
                  <td className="money auto">{money(s.costos)}</td>
                  <td className="money auto">{money(s.pension)}</td>
                  <td className="money auto">{money(s.totalAno)}</td>
                  <td className={'money ' + (s.matriculaPaid ? 'paid' : 'mora')}>{s.matriculaPaid ? '✓' : '—'}</td>
                  <td className={'money ' + (s.costosPaid ? 'paid' : 'mora')}>{s.costosPaid ? '✓' : '—'}</td>
                  {s.cells.map((c, i) => (
                    <MonthCell key={i} state={c} current={i === CUR} lang={lang}
                      onPress={() => onPressCell(s, MB[i])} />
                  ))}
                  <td className="money auto strong">{money(s.totalPagado)}</td>
                  <td className="money auto">{money(s.debioPagar)}</td>
                  <td className={'money col-saldo ' + (s.saldoMora > 0 ? 'mora' : '')}>{s.saldoMora > 0 ? money(s.saldoMora) : '0'}</td>
                  <td className="col-acc">
                    <ConcilDot kind={s.concil} lang={lang} />
                    <button type="button" className="action-wa" onClick={() => onWhatsApp(s)} title="WhatsApp"><WhatsApp /></button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }

  window.Ledger = { KpiStrip, Toolbar, LedgerTable };
})();
