// Documents module — list, side panel, templates subtab, signature modal
const { useState: _doc_useState, useEffect: _doc_useEffect, useRef: _doc_useRef } = React;

const DOC_TYPES = {
  contrato:      { label: 'Contrato laboral',         icon: 'IconDoc',     color: 'navy' },
  otrosi:        { label: 'Otrosí',                   icon: 'IconDoc',     color: 'navy' },
  reglamento:    { label: 'Reglamento interno',       icon: 'IconBook',    color: 'navy' },
  politica:      { label: 'Política',                 icon: 'IconShield',  color: 'navy' },
  acta:          { label: 'Acta',                     icon: 'IconCheck',   color: 'navy' },
  certificacion: { label: 'Certificación laboral',    icon: 'IconStar',    color: 'navy' },
  paz:           { label: 'Paz y salvo',              icon: 'IconCheck',   color: 'green' },
  acuerdo:       { label: 'Acuerdo confidencialidad', icon: 'IconShield',  color: 'navy' },
  autorizacion:  { label: 'Autorización',             icon: 'IconDoc',     color: 'navy' },
};

const STATE_META_DOC = {
  signed:   { label: 'Firmado',         pill: 'green',     dot: 'var(--green-600)'  },
  pending:  { label: 'Pendiente firma', pill: 'amber',     dot: 'var(--amber-600)'  },
  expired:  { label: 'Vencido',         pill: 'rose',      dot: 'var(--rose-600)'   },
  expiring: { label: 'Por vencer',      pill: 'amber-soft',dot: '#854D0E'           },
  void:     { label: 'Anulado',         pill: 'navy',      dot: 'var(--text-muted)' },
};

const DOCS = [
  { id: 'd-127', type: 'contrato', emp: { name: 'María Fernanda López', initials: 'ML' }, generated: '01/05/2026 10:30', state: 'pending',
    signers: [
      { name: 'María F. López', signed: false, role: 'Colaborador' },
      { name: 'Carlos Gómez',   signed: true,  role: 'Rep. Legal',  signedAt: '01/05/2026 14:00' },
    ],
    validity: 'Vigente · sin vencimiento',
    hash: 'a4f2c1e89b7d3f5e26c8d4b1a9f3e7c5d8b2a4f6e9c1d3b5a7f8e0c2d4b6a9f1' },
  { id: 'd-126', type: 'reglamento', emp: { name: 'Andrés Felipe Mejía', initials: 'AM' }, generated: '01/05/2026 10:31', state: 'pending',
    signers: [
      { name: 'Andrés Mejía', signed: false, role: 'Colaborador' },
    ],
    validity: 'Vigente',
    hash: 'b7e3d8a1f9c4e2b6d8a3f5e7c9b1d4f6e8a2c5b7d9e1f3a5b7c9d2e4f6a8b1d3' },
  { id: 'd-125', type: 'contrato', emp: { name: 'Diego Andrés Toro', initials: 'DT' }, generated: '20/04/2026 09:14', state: 'signed',
    signers: [
      { name: 'Diego Toro',     signed: true, role: 'Colaborador', signedAt: '20/04/2026 16:22' },
      { name: 'Carlos Gómez',   signed: true, role: 'Rep. Legal',  signedAt: '20/04/2026 17:08' },
    ],
    validity: 'Indefinido',
    hash: 'c2a1f4e7b9d3a5c8e2f6b4d1a9c3e5f7b8d2a6c4e8f1b3d5a7c9e2f4b6d8a1c3' },
  { id: 'd-124', type: 'certificacion', emp: { name: 'Patricia Gómez Lara', initials: 'PG' }, generated: '03/05/2026 11:00', state: 'signed',
    signers: [
      { name: 'Carolina Restrepo', signed: true, role: 'RRHH', signedAt: '03/05/2026 11:00' },
    ],
    validity: '30 días',
    hash: 'd5b8c2f9a3e7d1b4c6f8a2e5d7b9c1f3a5e7d9b2c4f6a8e1d3b5c7f9a2e4d6b8' },
  { id: 'd-123', type: 'paz', emp: { name: 'Sandra Milena Vargas', initials: 'SV' }, generated: '28/04/2026 16:42', state: 'signed',
    signers: [
      { name: 'Sandra Vargas', signed: true, role: 'Colaborador', signedAt: '28/04/2026 17:10' },
      { name: 'Patricia Gómez', signed: true, role: 'RRHH',       signedAt: '28/04/2026 17:30' },
    ],
    validity: 'Documento histórico',
    hash: 'e1d4a7c2b5f9e3d6a8c1f4b7e9d2a5c8f1b4e7d9a2c5f8b1e4d7a9c2f5b8e1d4' },
  { id: 'd-122', type: 'politica', emp: { name: 'Laura Camila Suárez', initials: 'LS' }, generated: '24/04/2026 09:00', state: 'expired',
    signers: [
      { name: 'Laura Suárez', signed: false, role: 'Colaborador' },
    ],
    validity: 'Vencido · 6 días',
    hash: 'f8a2d5c1e4b7f9a3d6c8e2b5f7a9d2c4e6b8f1a3d5c7e9b2f4a6d8c1e3b5f7a9' },
  { id: 'd-121', type: 'acuerdo', emp: { name: 'Andrés Felipe Mejía', initials: 'AM' }, generated: '01/05/2026 10:32', state: 'pending',
    signers: [
      { name: 'Andrés Mejía',   signed: false, role: 'Colaborador' },
      { name: 'Carlos Gómez',   signed: false, role: 'Rep. Legal' },
    ],
    validity: 'Vigente',
    hash: 'a9c3f6b1d4e7a2c5f8b1e4d7a9c2f5b8e1d4a7c2b5f9e3d6a8c1f4b7e9d2a5c8' },
  { id: 'd-120', type: 'otrosi', emp: { name: 'Diego Andrés Toro', initials: 'DT' }, generated: '15/04/2026 14:20', state: 'expiring',
    signers: [
      { name: 'Diego Toro',     signed: true, role: 'Colaborador', signedAt: '15/04/2026 18:00' },
      { name: 'Carlos Gómez',   signed: true, role: 'Rep. Legal',  signedAt: '16/04/2026 09:30' },
    ],
    validity: 'Vence en 12 días',
    hash: 'b4f7e2c5d8a1b4f7e2c5d8a1b4f7e2c5d8a1b4f7e2c5d8a1b4f7e2c5d8a1b4f7' },
  { id: 'd-128', type: 'autorizacion', emp: { name: 'Andrés Felipe Mejía', initials: 'AM' }, generated: '02/05/2026 09:10', state: 'signed',
    signers: [
      { name: 'Andrés Mejía', signed: true, role: 'Colaborador', signedAt: '02/05/2026 09:15' },
    ],
    validity: 'Vigente',
    hash: 'c8f3a6d1b4e7c2a5f8b1d4e7a9c2f5b8d1a4c7e9b2d5f8a1c4e7b9d2a5c8f1e4' },
  { id: 'd-129', type: 'certificacion', emp: { name: 'Andrés Felipe Mejía', initials: 'AM' }, generated: '03/05/2026 08:40', state: 'pending',
    signers: [
      { name: 'Andrés Mejía', signed: false, role: 'Colaborador' },
    ],
    validity: '30 días',
    hash: 'e2b5f8a1d4c7b9e3f6a2d5c8b1e4f7a9d3c6b8e1f4a7d2c5b9e3f6a1d4c8b2e5' },
];

// Timeline events for selected doc (using d-127 — the pending contract)
const TIMELINE_BY_DOC = {
  'd-127': [
    { kind: 'generated', icon: 'IconDoc', label: 'Documento generado', detail: '01/05/2026 10:30 · por Carolina Restrepo (RRHH)' },
    { kind: 'sent',  icon: 'IconExternal',  label: 'Enviado al firmante', detail: '01/05/2026 10:31 · email a maria.lopez@atica.co' },
    { kind: 'viewed', icon: 'IconExternal', label: 'Visto', detail: '02/05/2026 08:15 · Carlos Gómez · App móvil iOS · IP 190.85.x.x' },
    { kind: 'signed', icon: 'IconCheck', label: 'Firmado', detail: '02/05/2026 14:30 · Carlos Gómez (Rep. Legal) · Firma electrónica certificada' },
    { kind: 'pending', icon: 'IconClock', label: 'Pendiente · firma del colaborador', detail: 'Recordatorio enviado hace 4 horas' },
  ],
  'd-125': [
    { kind: 'generated', icon: 'IconDoc', label: 'Documento generado', detail: '20/04/2026 09:14 · Carolina Restrepo' },
    { kind: 'sent', icon: 'IconExternal', label: 'Enviado', detail: '20/04/2026 09:15' },
    { kind: 'viewed', icon: 'IconExternal', label: 'Visto', detail: '20/04/2026 16:18 · Diego Toro · IP 181.49.x.x' },
    { kind: 'signed', icon: 'IconCheck', label: 'Firmado', detail: '20/04/2026 16:22 · Diego Toro · Token SMS' },
    { kind: 'signed', icon: 'IconCheck', label: 'Firmado', detail: '20/04/2026 17:08 · Carlos Gómez (Rep. Legal)' },
    { kind: 'mailed', icon: 'IconMegaphone', label: 'Copia enviada', detail: '20/04/2026 17:09 · diego.toro@atica.co' },
  ],
};

const Documents = () => {
  const [tab, setTab] = _doc_useState('docs');
  const [viewRole, setViewRole] = _doc_useState('rrhh'); // rrhh | colaborador

  return (
    <div className="main" data-screen-label="Documentos">
      <div className="page-head" style={{ marginBottom: 12 }}>
        <div>
          <h1 className="page-title">Documentos y Firma electrónica</h1>
          <div className="page-subtitle"><b>2,184 documentos</b> · 18 pendientes de firma · 3 por vencer</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div className="to-view-toggle">
            <button className={viewRole === 'rrhh' ? 'active' : ''} onClick={() => setViewRole('rrhh')}>
              <IconShield size={13} /> Vista RRHH
            </button>
            <button className={viewRole === 'colaborador' ? 'active' : ''} onClick={() => { setViewRole('colaborador'); setTab('docs'); }}>
              <IconUsers size={13} /> Vista colaborador
            </button>
          </div>
          {viewRole === 'rrhh' && (
            <>
              <button className="btn"><IconExternal size={14} /> Auditoría</button>
              <button className="btn primary"><IconPlus size={14} /> Generar documento</button>
            </>
          )}
        </div>
      </div>

      <div className="doc-tabs">
        <button className={`doc-tab ${tab === 'docs' ? 'active' : ''}`} onClick={() => setTab('docs')}>
          <IconDoc size={14} /> Documentos generados
        </button>
        {viewRole === 'rrhh' && (
          <>
            <button className={`doc-tab ${tab === 'templates' ? 'active' : ''}`} onClick={() => setTab('templates')}>
              <IconBook size={14} /> Plantillas
            </button>
            <button className={`doc-tab ${tab === 'audit' ? 'active' : ''}`} onClick={() => setTab('audit')}>
              <IconShield size={14} /> Auditoría
            </button>
          </>
        )}
      </div>

      {tab === 'docs' && <DocList viewRole={viewRole} />}
      {tab === 'templates' && <DocTemplates />}
      {tab === 'audit' && <DocAudit />}
    </div>
  );
};

// ─── Documents list + side panel ─────────────────────────

const DocList = ({ viewRole }) => {
  const [selectedId, setSelectedId] = _doc_useState('d-127');
  const [signatureFor, setSignatureFor] = _doc_useState(null);
  const [filterType, setFilterType] = _doc_useState('Todos');
  const [filterState, setFilterState] = _doc_useState('Todos');
  const selected = DOCS.find(d => d.id === selectedId);

  const filtered = DOCS.filter(d =>
    (filterType === 'Todos' || DOC_TYPES[d.type].label === filterType) &&
    (filterState === 'Todos' || STATE_META_DOC[d.state].label === filterState) &&
    (viewRole !== 'colaborador' || d.emp.name === 'Andrés Felipe Mejía')
  );

  return (
    <>
      <div className="ob-toolbar" style={{ marginBottom: 14 }}>
        <div className="ob-search">
          <IconSearch size={15} />
          <input placeholder="Buscar por documento, empleado o ID…" />
        </div>
        <select value={filterType} onChange={(e) => setFilterType(e.target.value)}>
          <option>Todos</option>
          {Object.values(DOC_TYPES).map(t => <option key={t.label}>{t.label}</option>)}
        </select>
        <select value={filterState} onChange={(e) => setFilterState(e.target.value)}>
          <option>Todos</option>
          {Object.values(STATE_META_DOC).map(s => <option key={s.label}>{s.label}</option>)}
        </select>
        {viewRole !== 'colaborador' && (
          <select>
            <option>Todos los empleados</option>
            <option>María F. López</option>
            <option>Andrés Mejía</option>
            <option>Diego Toro</option>
          </select>
        )}
        <select>
          <option>Cualquier fecha</option>
          <option>Hoy</option>
          <option>Últimos 7 días</option>
          <option>Este mes</option>
        </select>
      </div>

      <div className="doc-grid">
        <div className="doc-list-card">
          <table className="doc-table">
            <thead>
              <tr>
                <th>Documento</th>
                <th>Empleado</th>
                <th>Generado</th>
                <th>Estado</th>
                <th>Firmantes</th>
                <th>Vigencia</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(d => {
                const t = DOC_TYPES[d.type];
                const s = STATE_META_DOC[d.state];
                const TIco = window[t.icon];
                return (
                  <tr key={d.id} className={selectedId === d.id ? 'selected' : ''} onClick={() => setSelectedId(d.id)}>
                    <td>
                      <div className="doc-cell-type">
                        <div className="doc-type-icon"><TIco size={15} /></div>
                        <div>
                          <div className="doc-name">{t.label}</div>
                          <div className="muted mono" style={{ fontSize: 11 }}>{d.id}</div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <div className="doc-cell-emp">
                        <div className="doc-avatar">{d.emp.initials}</div>
                        <span>{d.emp.name}</span>
                      </div>
                    </td>
                    <td className="mono muted" style={{ fontSize: 12 }}>{d.generated}</td>
                    <td>
                      <span className={`pill ${s.pill}`}>
                        <span className="status-dot" style={{ background: s.dot }} /> {s.label}
                      </span>
                    </td>
                    <td>
                      <div className="signer-chips">
                        {d.signers.map((sg, i) => (
                          <span key={i} className={`signer-chip ${sg.signed ? 'signed' : ''}`} title={sg.role}>
                            {sg.signed && <IconCheck size={10} />}
                            {sg.name.split(' ').slice(0, 2).join(' ')}
                          </span>
                        ))}
                      </div>
                    </td>
                    <td className="muted" style={{ fontSize: 12 }}>{d.validity}</td>
                    <td>
                      <div className="doc-actions">
                        <button className="icon-action" title="Ver PDF"><IconExternal size={14} /></button>
                        <button className="icon-action" title="Reenviar" onClick={(e) => { e.stopPropagation(); if (d.state === 'pending') setSignatureFor(d); }}><IconMegaphone size={14} /></button>
                        <button className="icon-action" title="Descargar"><IconDoc size={14} /></button>
                        <button className="icon-action danger" title="Anular"><IconAlert size={14} /></button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div className="doc-table-foot">
            <span className="muted" style={{ fontSize: 12 }}>Mostrando {filtered.length} de 2,184 documentos</span>
            <div className="pager">
              <button className="btn" style={{ padding: '5px 9px' }}><IconChevronLeft size={13} /></button>
              <span className="mono" style={{ fontSize: 12, padding: '0 8px' }}>1 / 184</span>
              <button className="btn" style={{ padding: '5px 9px' }}><IconChevronRight size={13} /></button>
            </div>
          </div>
        </div>

        <DocSidePanel doc={selected} onSign={() => setSignatureFor(selected)} viewRole={viewRole} />
      </div>

      {signatureFor && <SignatureFlow doc={signatureFor} onClose={() => setSignatureFor(null)} />}
    </>
  );
};

const DocSidePanel = ({ doc, onSign, viewRole }) => {
  if (!doc) return <div className="doc-side empty muted">Selecciona un documento</div>;
  const [hashCopied, setHashCopied] = _doc_useState(false);
  const t = DOC_TYPES[doc.type];
  const s = STATE_META_DOC[doc.state];
  const timeline = TIMELINE_BY_DOC[doc.id] || TIMELINE_BY_DOC['d-127'];

  const copyHash = () => {
    navigator.clipboard?.writeText(doc.hash);
    setHashCopied(true);
    setTimeout(() => setHashCopied(false), 1600);
  };

  return (
    <div className="doc-side">
      <div className="doc-side-head">
        <div className="doc-type-icon lg"><DocIcon name={t.icon} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="doc-side-name">{t.label}</div>
          <div className="muted mono" style={{ fontSize: 11.5, marginTop: 2 }}>{doc.id} · {doc.emp.name}</div>
        </div>
        <span className={`pill ${s.pill}`}><span className="status-dot" style={{ background: s.dot }} /> {s.label}</span>
      </div>

      <div className="doc-preview">
        <div className="doc-preview-pages">
          {[1,2,3].map(p => (
            <div key={p} className="doc-page-thumb">
              <div className="doc-page-lines">
                {Array.from({ length: 14 }).map((_, i) => (
                  <span key={i} style={{ width: `${65 + ((i * 7) % 30)}%` }} />
                ))}
              </div>
              <div className="doc-page-num">{p}</div>
            </div>
          ))}
        </div>
        <button className="btn" style={{ marginTop: 12, width: '100%' }}>
          <IconExternal size={14} /> Abrir PDF completo
        </button>
      </div>

      <div className="doc-side-section">
        <div className="muted-xs">Hash de integridad · SHA-256</div>
        <div className="hash-box">
          <span className="mono">{doc.hash.slice(0, 8)}…{doc.hash.slice(-8)}</span>
          <button className="hash-copy" onClick={copyHash}>
            {hashCopied ? <><IconCheck size={12} /> copiado</> : 'Copiar'}
          </button>
        </div>
      </div>

      <div className="doc-side-section">
        <div className="muted-xs">Línea de tiempo de firma</div>
        <div className="doc-timeline">
          {timeline.map((ev, i) => (
            <div key={i} className={`doc-tl-row doc-tl-${ev.kind}`}>
              <div className="doc-tl-rail">
                <div className="doc-tl-dot"><DocIcon name={ev.icon} size={11} /></div>
                {i < timeline.length - 1 && <div className="doc-tl-line" />}
              </div>
              <div className="doc-tl-body">
                <div className="doc-tl-label">{ev.label}</div>
                <div className="doc-tl-detail muted">{ev.detail}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {doc.state === 'pending' && viewRole === 'colaborador' && (
        <button className="btn primary" style={{ width: '100%', marginTop: 4 }} onClick={onSign}>
          <IconCheck size={14} /> Iniciar flujo de firma
        </button>
      )}
    </div>
  );
};

const DocIcon = ({ name, size = 14 }) => {
  const Ico = window[name] || IconDoc;
  return <Ico size={size} />;
};

// Stub for audit tab
const DocAudit = () => (
  <div className="empty-state">
    <IconShield size={32} />
    <div className="empty-title">Auditoría completa</div>
    <div className="empty-sub muted">Bitácora de eventos · cumplimiento · exportar evidencias para inspección.</div>
  </div>
);

window.Documents = Documents;
