// ─── Admin · Editar registros ────────────────────────────────────────────
// Lista admin de TODOS los registros (pendientes + entregados) con CTA "Editar".
// Para entregados muestra advertencias antes de permitir edición.

function AdminEditarScreen({ onBack, onNav, onEditTicket }) {
  const [query, setQuery] = React.useState('');
  const [filter, setFilter] = React.useState('todos'); // 'todos' | 'pendiente' | 'entregado'
  const [confirmTicket, setConfirmTicket] = React.useState(null);

  // Data
  const [savedTickets, setSavedTickets] = React.useState(loadPendientesSaved());
  const [entregados, setEntregados] = React.useState(loadEntregados());
  React.useEffect(() => {
    const refresh = () => { setSavedTickets(loadPendientesSaved()); setEntregados(loadEntregados()); };
    refresh();
    window.addEventListener('storage', refresh);
    window.addEventListener('focus', refresh);
    return () => {
      window.removeEventListener('storage', refresh);
      window.removeEventListener('focus', refresh);
    };
  }, []);

  const deliveredIds = new Set(entregados.map(e => e.ticketId));
  const pendientesAll = [...savedTickets, ...PENDIENTES_DEMO]
    .filter(t => !deliveredIds.has(t.id))
    .map(t => ({ ...t, _status: 'pendiente', _source: savedTickets.includes(t) ? 'pendiente-saved' : 'pendiente-demo' }));
  const entregadosAll = entregados.map(e => ({
    id: e.ticketId,
    codigo: e.codigo,
    placa: e.placa,
    idType: e.idType,
    fecha: e.fechaRecogido,
    fechaEntrega: e.fechaEntrega,
    horaEntrega: e.horaEntrega,
    aseguradora: e.aseguradora,
    taller: e.taller,
    sede: e.sede,
    items: e.items,
    factura: e.factura,
    recibePor: e.recibePor,
    _status: 'entregado',
    _source: 'entregado',
    _entrega: e,
  }));

  let all = [...pendientesAll, ...entregadosAll];
  all.sort((a, b) => {
    const da = parseFechaDDMMYYYY(a.fechaEntrega || a.fecha) || new Date(0);
    const db = parseFechaDDMMYYYY(b.fechaEntrega || b.fecha) || new Date(0);
    return db - da;
  });
  if (filter !== 'todos') all = all.filter(t => t._status === filter);
  const q = query.trim().toLowerCase();
  const filtered = q
    ? all.filter(t =>
        (t.placa || '').toLowerCase().includes(q) ||
        (t.codigo || '').toLowerCase().includes(q) ||
        (t.taller || '').toLowerCase().includes(q) ||
        (t.aseguradora || '').toLowerCase().includes(q) ||
        (t.sede || '').toLowerCase().includes(q) ||
        (t.factura || '').toLowerCase().includes(q)
      )
    : all;

  const totalPend = pendientesAll.length;
  const totalEntregados = entregadosAll.length;

  return (
    <div style={{ background: TOKENS.bg, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <AppHeader title="Editar registros" onBack={onBack} bell={false} right={
        <Chip tone="dark">ADMIN</Chip>
      } />
      <div style={{ padding: 16, flex: 1 }}>

        {/* Admin warning */}
        <div style={{
          background: TOKENS.warningBg, border: `1px solid ${TOKENS.warningBorder}`,
          borderRadius: 12, padding: '12px 14px', marginBottom: 14,
          display: 'flex', gap: 12, alignItems: 'flex-start',
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 999, background: TOKENS.warning,
            color: TOKENS.warningText, display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0, fontWeight: 700,
          }}>!</div>
          <div style={{ fontSize: 12, color: TOKENS.warningText, lineHeight: 1.5 }}>
            <b style={{ color: TOKENS.warningText }}>Acceso administrativo.</b> Puedes editar cualquier registro,
            incluso aquellos ya entregados. Los cambios sobre registros entregados quedarán auditados.
          </div>
        </div>

        {/* Totals */}
        <div style={{
          background: TOKENS.heroGradient, color: '#fff', borderRadius: 14,
          padding: '14px 16px', marginBottom: 14,
        }}>
          <div style={{ fontSize: 10, opacity: 0.7, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 8 }}>
            Registros disponibles
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
            <HeroStat n={totalPend + totalEntregados} label="Todos" tone="all" />
            <HeroStat n={totalPend} label="Pendientes" tone="pendiente" />
            <HeroStat n={totalEntregados} label="Entregados" tone="entregado" />
          </div>
        </div>

        {/* Search bar */}
        <div style={{ position: 'relative', marginBottom: 10 }}>
          <div style={{
            position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)',
            color: TOKENS.textMuted, pointerEvents: 'none', display: 'flex',
          }}>{I.consultar(16, TOKENS.textMuted)}</div>
          <input
            type="text"
            className="ad-search"
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Buscar por placa, orden, factura, taller…"
            style={{
              width: '100%', boxSizing: 'border-box',
              border: `1px solid ${TOKENS.borderInput}`,
              background: TOKENS.surface,
              borderRadius: 12, padding: '12px 40px 12px 38px',
              fontSize: 14, color: TOKENS.text, fontFamily: 'inherit', outline: 'none',
            }}
          />
          {query && (
            <button type="button" onClick={() => setQuery('')} style={{
              position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
              background: 'transparent', border: 'none', padding: 6, cursor: 'pointer',
              display: 'flex', color: TOKENS.textMuted,
            }} aria-label="Limpiar búsqueda">
              {I.x(16, TOKENS.textMuted)}
            </button>
          )}
        </div>

        {/* Filters */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 12, overflowX: 'auto' }}>
          <FilterChip active={filter === 'todos'} onClick={() => setFilter('todos')}>
            Todos · {totalPend + totalEntregados}
          </FilterChip>
          <FilterChip active={filter === 'pendiente'} onClick={() => setFilter('pendiente')} tone="pendiente">
            Pendientes · {totalPend}
          </FilterChip>
          <FilterChip active={filter === 'entregado'} onClick={() => setFilter('entregado')} tone="success">
            Entregados · {totalEntregados}
          </FilterChip>
        </div>

        <div style={{ marginBottom: 10, padding: '0 4px' }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: TOKENS.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            {filtered.length} {filtered.length === 1 ? 'resultado' : 'resultados'}
          </div>
        </div>

        {/* List */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {filtered.length === 0 && (
            <div style={{
              padding: 36, textAlign: 'center', color: TOKENS.textMuted, fontSize: 13,
              background: TOKENS.surfaceLow, borderRadius: 12, border: `1px dashed ${TOKENS.border}`,
            }}>Sin resultados.</div>
          )}
          {filtered.map(t => (
            <AdminEditRow key={t.id} ticket={t} onEdit={() => setConfirmTicket(t)} />
          ))}
        </div>
      </div>

      {confirmTicket && (
        <EditTicketConfirmModal
          ticket={confirmTicket}
          onDismiss={() => setConfirmTicket(null)}
          onConfirm={() => {
            const t = confirmTicket;
            setConfirmTicket(null);
            onEditTicket && onEditTicket(t);
          }}
        />
      )}
    </div>
  );
}

function AdminEditRow({ ticket, onEdit }) {
  const sum = ticketSummary(ticket);
  const isDelivered = ticket._status === 'entregado';
  return (
    <Card style={{ padding: '14px 14px', cursor: 'pointer' }}>
      <div onClick={onEdit} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{
          width: 42, height: 42, borderRadius: 10,
          background: isDelivered ? TOKENS.successBg : TOKENS.surfaceLow,
          color: isDelivered ? TOKENS.success : TOKENS.primary,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: `1px solid ${TOKENS.border}`, flexShrink: 0,
        }}>{I.pencil(20, isDelivered ? TOKENS.success : TOKENS.primary)}</div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontSize: 11, fontWeight: 700, color: TOKENS.primary,
            background: TOKENS.surfaceLow, padding: '3px 8px', borderRadius: 6,
            border: `1px solid ${TOKENS.border}`, letterSpacing: '0.04em',
            fontFamily: 'monospace', marginBottom: 6,
          }}>
            <span style={{ color: TOKENS.textMuted, fontWeight: 600 }}>N°</span>
            <span>{ticket.codigo}</span>
          </div>
          <div style={{
            fontSize: 18, fontWeight: 700, color: TOKENS.text,
            letterSpacing: '0.04em', wordBreak: 'break-all', lineHeight: 1.1,
          }}>
            {ticket.placa}
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 4 }}>
            {isDelivered
              ? <>Entregado: {ticket.fechaEntrega} · {window.formatHora12(ticket.horaEntrega)}</>
              : <>Recogido: {ticket.fecha}</>
            }
          </div>
          <div style={{ fontSize: 13, color: TOKENS.text, marginTop: 6, fontWeight: 600 }}>
            {ticket.taller} <span style={{ color: TOKENS.textMuted, fontWeight: 500 }}>· {ticket.sede}</span>
          </div>
          <div style={{ fontSize: 12, color: TOKENS.textMuted, marginTop: 2 }}>
            {ticket.aseguradora}
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
          <Chip tone={isDelivered ? 'success' : 'pendiente'}>
            {isDelivered ? 'ENTREGADO' : 'PENDIENTE'}
          </Chip>
          <div style={{
            fontSize: 13, fontWeight: 700, color: TOKENS.primary,
            background: TOKENS.surface, padding: '4px 10px', borderRadius: 6,
            border: `1px solid ${TOKENS.border}`, minWidth: 30, textAlign: 'center', fontFamily: 'monospace',
          }}>×{sum.total}</div>
          <button onClick={(e) => { e.stopPropagation(); onEdit(); }} style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '7px 12px', borderRadius: 8, fontSize: 11, fontWeight: 700,
            background: TOKENS.warning, color: TOKENS.warningText, border: 'none',
            cursor: 'pointer', fontFamily: 'inherit', letterSpacing: '0.02em',
          }}>
            {I.pencil(12, '#fff')} Editar
          </button>
        </div>
      </div>
    </Card>
  );
}

// Modal de confirmación con advertencia reforzada para entregados ──────
function EditTicketConfirmModal({ ticket, onConfirm, onDismiss }) {
  const isDelivered = ticket._status === 'entregado';
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(11,28,48,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,
      padding: 16,
    }}>
      <div style={{
        background: TOKENS.surface, borderRadius: 18, padding: 22, width: '100%', maxWidth: 380,
        boxShadow: '0 16px 40px rgba(0,0,0,0.2)',
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: 999,
          background: isDelivered ? TOKENS.dangerBg : `color-mix(in srgb, ${TOKENS.enCurso} 15%, #fff)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 14px', color: isDelivered ? TOKENS.danger : TOKENS.enCurso,
          fontWeight: 700, fontSize: 28,
        }}>!</div>
        <div style={{ fontSize: 17, fontWeight: 700, color: TOKENS.text, textAlign: 'center' }}>
          {isDelivered ? 'Editar registro entregado' : 'Editar registro'}
        </div>
        <div style={{ fontSize: 13, color: TOKENS.textMuted, textAlign: 'center', marginTop: 8, lineHeight: 1.5 }}>
          {isDelivered ? (
            <>
              Este registro ya fue <b style={{ color: TOKENS.danger }}>entregado</b> el{' '}
              <b style={{ color: TOKENS.text }}>{ticket.fechaEntrega}</b>.
              Modificarlo afectará el histórico y el comprobante impreso.
              Los cambios quedarán auditados.
            </>
          ) : (
            <>Vas a editar el registro <b style={{ color: TOKENS.text }}>{ticket.placa}</b> ({ticket.codigo}).
              Los cambios sobrescribirán la información actual.</>
          )}
        </div>

        <div style={{
          marginTop: 14, padding: '10px 12px',
          background: TOKENS.surfaceLow, borderRadius: 10,
          fontSize: 12, color: TOKENS.textMuted,
        }}>
          <Row k="Orden" v={'' + ticket.codigo} />
          <Row k={ticket.idType === 'vin' ? 'VIN' : 'Placa'} v={ticket.placa} mono />
          <Row k="Taller" v={ticket.taller} />
          <Row k="Estado" v={isDelivered ? 'Entregado' : 'Pendiente'} highlight={isDelivered ? TOKENS.danger : TOKENS.enCurso} last />
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <Button variant="outline" full onClick={onDismiss}>Cancelar</Button>
          <Button variant="primary" full onClick={onConfirm}
            style={{
              background: isDelivered ? TOKENS.danger : TOKENS.enCurso,
              borderColor: isDelivered ? TOKENS.danger : TOKENS.enCurso,
              color: '#fff',
            }}>
            {isDelivered ? 'Sí, editar entregado' : 'Sí, editar'}
          </Button>
        </div>
      </div>
    </div>
  );
}

function Row({ k, v, last, mono, highlight }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '4px 0', borderBottom: last ? 'none' : `1px dashed ${TOKENS.border}`,
      fontSize: 12,
    }}>
      <span>{k}</span>
      <span style={{
        fontWeight: 700, color: highlight || TOKENS.text,
        fontFamily: mono ? 'monospace' : 'inherit',
        letterSpacing: mono ? '0.04em' : '0',
      }}>{v}</span>
    </div>
  );
}

Object.assign(window, { AdminEditarScreen });
