// Automation modals: Registrar Evento + Cerrar Viaje

const { useState: useStateA, useEffect: useEffectA } = window.React;

// ── Modal shell ───────────────────────────────────────────────────
function Modal({ open, onClose, title, children, width }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(17,28,23,.55)',
      backdropFilter: 'blur(3px)', zIndex: 1000,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 16, width: width || 460,
        boxShadow: '0 24px 64px rgba(0,0,0,.18)', overflow: 'hidden',
        animation: 'modalIn .18s ease',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '18px 22px', borderBottom: '1px solid #f0f4f2' }}>
          <span style={{ fontSize: 15, fontWeight: 700, color: '#1a2e25' }}>{title}</span>
          <button onClick={onClose} style={{ border: 'none', background: 'none', cursor: 'pointer', color: '#5a7366', fontSize: 20, lineHeight: 1 }}>✕</button>
        </div>
        <div style={{ padding: '22px' }}>{children}</div>
      </div>
      <style>{`@keyframes modalIn { from{opacity:0;transform:scale(.96)} to{opacity:1;transform:scale(1)} }`}</style>
    </div>
  );
}

// ── Field helpers ─────────────────────────────────────────────────
function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6 }}>{label}</label>
      {children}
    </div>
  );
}

const inputStyle = {
  width: '100%', border: '1px solid #dde8e2', borderRadius: 8,
  padding: '9px 12px', fontSize: 13, color: '#1a2e25',
  background: '#f7faf8', outline: 'none', fontFamily: 'DM Sans, sans-serif',
};

// ── Registrar Evento Modal ────────────────────────────────────────
function RegisterEventModal({ open, onClose, trip, onSave }) {
  const now = new Date();
  const timeStr = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;

  const [form, setFormA] = useStateA({
    type: 'checkpoint', time: timeStr, label: '', detail: '',
  });
  const [saved, setSaved] = useStateA(false);

  const typeOpts = [
    { value: 'checkpoint', label: '● Checkpoint', color: '#3B82F6' },
    { value: 'parada',     label: '■ Parada',     color: '#8B5CF6' },
    { value: 'demora',     label: '! Demora',      color: '#d97706' },
    { value: 'llegada',    label: '★ Llegada',     color: '#10B981' },
  ];

  const labelSuggestions = {
    checkpoint: ['Checkpoint en ruta', 'Paso por peaje', 'Cruce de ciudad'],
    parada:     ['Parada de descanso', 'Parada de combustible', 'Espera en destino'],
    demora:     ['Demora por tráfico', 'Demora por accidente', 'Desvío por obras', 'Revisión de carga'],
    llegada:    ['Llegada al destino', 'Entrega completada'],
  };

  const set = (key, val) => setFormA(f => ({ ...f, [key]: val }));

  const handleSave = () => {
    if (!form.label.trim()) return;
    onSave({ ...form, label: form.label.trim(), detail: form.detail.trim() });
    setSaved(true);
    setTimeout(() => { setSaved(false); onClose(); setFormA({ type: 'checkpoint', time: timeStr, label: '', detail: '' }); }, 900);
  };

  return (
    <Modal open={open} onClose={onClose} title={`Registrar evento — ${trip?.id}`}>
      <Field label="Tipo de evento">
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {typeOpts.map(o => (
            <button key={o.value} onClick={() => set('type', o.value)}
              style={{
                border: `1px solid ${form.type === o.value ? o.color : '#dde8e2'}`,
                background: form.type === o.value ? `${o.color}18` : '#fff',
                color: form.type === o.value ? o.color : '#5a7366',
                borderRadius: 8, padding: '6px 12px', fontSize: 12, fontWeight: 600,
                cursor: 'pointer', transition: 'all .15s',
              }}>
              {o.label}
            </button>
          ))}
        </div>
      </Field>

      <Field label="Hora">
        <input type="time" value={form.time} onChange={e => set('time', e.target.value)} style={{ ...inputStyle, width: 'auto' }} />
      </Field>

      <Field label="Descripción">
        <input value={form.label} onChange={e => set('label', e.target.value)}
          placeholder="Describe el evento…" style={inputStyle} />
        {labelSuggestions[form.type]?.length > 0 && (
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
            {labelSuggestions[form.type].map(s => (
              <button key={s} onClick={() => set('label', s)}
                style={{ border: '1px solid #dde8e2', background: '#f7faf8', borderRadius: 6, padding: '3px 9px', fontSize: 11, color: '#5a7366', cursor: 'pointer' }}>
                {s}
              </button>
            ))}
          </div>
        )}
      </Field>

      <Field label="Detalle adicional (opcional)">
        <input value={form.detail} onChange={e => set('detail', e.target.value)}
          placeholder="Ubicación, causa, observación…" style={inputStyle} />
      </Field>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 4 }}>
        <Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
        <Btn onClick={handleSave} disabled={!form.label.trim()}>
          {saved ? '✓ Guardado' : 'Registrar evento'}
        </Btn>
      </div>
    </Modal>
  );
}

// ── Cerrar Viaje Modal ────────────────────────────────────────────
function CloseTripModal({ open, onClose, trip, onConfirm }) {
  const now = new Date();
  const [arrivalTime, setArrivalTime] = useStateA(
    `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`
  );
  const [note, setNote] = useStateA('');
  const [done, setDone] = useStateA(false);

  if (!trip) return null;

  const plannedTime = trip.etaPlanned?.split('T')[1];
  const [ph, pm] = plannedTime?.split(':').map(Number) || [0, 0];
  const [ah, am] = arrivalTime.split(':').map(Number);
  const diffMin = (ah * 60 + am) - (ph * 60 + pm);

  const handleConfirm = () => {
    onConfirm({ arrivalTime, note, delay: diffMin });
    setDone(true);
    setTimeout(() => { setDone(false); onClose(); }, 1000);
  };

  return (
    <Modal open={open} onClose={onClose} title={`Cerrar viaje — ${trip?.id}`}>
      <div style={{ background: '#f7faf8', borderRadius: 10, padding: '14px 16px', marginBottom: 20 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#1a2e25', marginBottom: 6 }}>{trip.route}</div>
        <div style={{ display: 'flex', gap: 20 }}>
          <div>
            <div style={{ fontSize: 10, color: '#5a7366', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em' }}>ETA planeado</div>
            <div style={{ fontSize: 16, fontWeight: 700, color: '#1a2e25' }}>{plannedTime}</div>
          </div>
          <div>
            <div style={{ fontSize: 10, color: '#5a7366', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em' }}>Hora de llegada real</div>
            <input type="time" value={arrivalTime} onChange={e => setArrivalTime(e.target.value)}
              style={{ ...inputStyle, width: 'auto', fontSize: 16, fontWeight: 700, padding: '4px 8px' }} />
          </div>
        </div>
        {diffMin !== 0 && (
          <div style={{ marginTop: 10 }}>
            <DelayBadge minutes={diffMin} />
          </div>
        )}
      </div>

      <Field label="Observación de cierre (opcional)">
        <input value={note} onChange={e => setNote(e.target.value)}
          placeholder="Sin novedades / entrega conforme…" style={inputStyle} />
      </Field>

      <div style={{ background: '#fef9c3', border: '1px solid #fde68a', borderRadius: 8, padding: '10px 14px', marginBottom: 18, fontSize: 12, color: '#92400e' }}>
        Esta acción cerrará el viaje y registrará la hora de llegada real. No se puede deshacer.
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
        <Btn variant="ghost" onClick={onClose}>Cancelar</Btn>
        <Btn onClick={handleConfirm}>
          {done ? '✓ Viaje cerrado' : '✓ Confirmar llegada'}
        </Btn>
      </div>
    </Modal>
  );
}

// ── Notification bell panel ───────────────────────────────────────
function NotificationPanel({ trips, open, onClose, onNavigate }) {
  const delayed = trips.filter(t => t.status === 'en_ruta' && t.delay > 60);
  const all = [
    ...delayed.map(t => ({ type: 'delay', trip: t, msg: `${t.id}: +${t.delay} min en ${t.route}` })),
    ...trips.filter(t => t.status === 'en_ruta' && t.delay > 0 && t.delay <= 60)
      .map(t => ({ type: 'warn', trip: t, msg: `${t.id}: retraso leve +${t.delay} min` })),
  ];

  if (!open) return null;
  return (
    <div style={{
      position: 'absolute', bottom: 70, left: 230, zIndex: 500,
      background: '#fff', borderRadius: 14, width: 300,
      boxShadow: '0 12px 40px rgba(0,0,0,.18)', border: '1px solid #dde8e2',
      animation: 'modalIn .15s ease',
    }}>
      <div style={{ padding: '14px 16px', borderBottom: '1px solid #f0f4f2', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: '#1a2e25' }}>Alertas activas</span>
        <button onClick={onClose} style={{ border: 'none', background: 'none', cursor: 'pointer', color: '#5a7366' }}>✕</button>
      </div>
      {all.length === 0 ? (
        <div style={{ padding: '20px 16px', textAlign: 'center', color: '#5a7366', fontSize: 13 }}>
          ✓ Todos los viajes en tiempo
        </div>
      ) : all.map((a, i) => (
        <div key={i} style={{ padding: '12px 16px', borderBottom: '1px solid #f7faf8', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <span style={{ fontSize: 16 }}>{a.type === 'delay' ? '🔴' : '🟡'}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, color: '#1a2e25', fontWeight: 600 }}>{a.msg}</div>
            <button onClick={() => { onNavigate('trip-detail', a.trip); onClose(); }}
              style={{ border: 'none', background: 'none', color: '#10B981', fontSize: 11, fontWeight: 700, cursor: 'pointer', padding: 0, marginTop: 4 }}>
              Ver viaje →
            </button>
          </div>
        </div>
      ))}
      <div style={{ padding: '10px 16px' }}>
        <button onClick={() => { onNavigate('chat'); onClose(); }}
          style={{ width: '100%', background: '#f7faf8', border: '1px solid #dde8e2', borderRadius: 8, padding: '8px', fontSize: 12, fontWeight: 600, color: '#1a2e25', cursor: 'pointer' }}>
          Consultar al asistente MCP →
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { Modal, RegisterEventModal, CloseTripModal, NotificationPanel });
