// Appointment terms window — shown every time someone taps a "Book" button.
// The visitor must acknowledge the terms before the Book Appointment button unlocks.
// Globals: React, Icon.

const TERMS_TEXT = {
  en: {
    title: 'Before you book',
    intro: 'Please read these appointment terms:',
    items: [
      'Appointments cannot be confirmed until proper release paperwork has been received from the lien holder.',
      'Appointments are confirmed beginning at 1 PM each day and take 1 to 3 hours to confirm.',
      'Your confirmation will include all fees and the pickup location.',
    ],
    ack: 'I have read and understand the appointment terms and conditions',
    book: 'Book Appointment',
    locked: 'Please confirm you’ve read the terms above to continue.',
    newTab: 'The booking page opens in a new tab.',
    close: 'Close',
  },
  es: {
    title: 'Antes de reservar',
    intro: 'Lea estos términos de la cita:',
    items: [
      'Las citas no pueden confirmarse hasta que se reciba la documentación de liberación correspondiente del acreedor prendario.',
      'Las citas se confirman a partir de la 1 PM cada día y tardan de 1 a 3 horas en confirmarse.',
      'Su confirmación incluirá todos los cargos y la ubicación de recogida.',
    ],
    ack: 'He leído y entiendo los términos y condiciones de la cita',
    book: 'Reservar cita',
    locked: 'Confirme que leyó los términos para continuar.',
    newTab: 'La página de reservas se abre en una nueva pestaña.',
    close: 'Cerrar',
  },
};

const BookingTermsModal = ({ lang, onClose, onContinue }) => {
  const T = TERMS_TEXT[lang === 'es' ? 'es' : 'en'];
  const [agreed, setAgreed] = React.useState(false);
  const closeRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    setTimeout(() => closeRef.current && closeRef.current.focus(), 0);
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, []);

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="jmac-terms-title" onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(0,0,0,0.72)', backdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16,
      }}>
      <style>{`
        .jmac-terms-card { animation: jmacTermsIn 200ms cubic-bezier(.2,.7,.2,1); }
        @keyframes jmacTermsIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
        @media (prefers-reduced-motion: reduce) { .jmac-terms-card { animation: none; } }
        .jmac-terms-card button:focus-visible { outline: none; box-shadow: var(--shadow-focus); }
      `}</style>
      <div className="jmac-terms-card" onClick={e => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 520, maxHeight: '92vh', overflowY: 'auto',
          background: '#141922', border: '1.5px solid #2c3a52', borderRadius: 14,
          boxShadow: '0 24px 60px rgba(0,0,0,.6)', color: '#EEF1F5',
        }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '18px 18px 14px 22px', borderBottom: '1px solid #232A35' }}>
          <span style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--mk-blue, #1673FF)',
                         display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <Icon name="calendar" size={22} color="#fff"/>
          </span>
          <h2 id="jmac-terms-title" style={{ margin: 0, flex: 1, fontFamily: 'var(--font-body)', fontStyle: 'normal',
                     fontStretch: '100%', fontWeight: 800, fontSize: 24, lineHeight: 1.2, color: '#fff' }}>
            {T.title}
          </h2>
          <button ref={closeRef} onClick={onClose} aria-label={T.close}
            style={{ background: 'none', border: 0, padding: 8, cursor: 'pointer', borderRadius: 8, display: 'inline-flex' }}>
            <Icon name="x" size={22} color="#fff"/>
          </button>
        </div>

        <div style={{ padding: '18px 22px 22px' }}>
          <p style={{ margin: 0, fontSize: 17, fontWeight: 600, color: '#fff' }}>{T.intro}</p>
          <ol style={{ listStyle: 'none', padding: 0, margin: '14px 0 0', display: 'grid', gap: 14 }}>
            {T.items.map((txt, i) => (
              <li key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 17, lineHeight: 1.5 }}>
                <span style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--mk-blue, #1673FF)', color: '#fff',
                               display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 14, flexShrink: 0, marginTop: 1 }}>
                  {i + 1}
                </span>
                <span>{txt}</span>
              </li>
            ))}
          </ol>

          <button type="button" role="checkbox" aria-checked={agreed} onClick={() => setAgreed(a => !a)}
            style={{
              marginTop: 22, width: '100%', display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left',
              padding: '14px 16px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
              background: agreed ? '#0e2318' : '#0C0F14', color: '#fff', fontSize: 16, fontWeight: 700, lineHeight: 1.4,
              border: agreed ? '2px solid #2fbf71' : '2px solid #3d4d68',
            }}>
            <span style={{
              width: 28, height: 28, borderRadius: 6, flexShrink: 0, display: 'grid', placeItems: 'center',
              background: agreed ? '#2fbf71' : 'transparent', border: agreed ? '2px solid #2fbf71' : '2px solid #8E97A3',
            }}>
              {agreed && <Icon name="check" size={18} color="#fff" strokeWidth={3}/>}
            </span>
            <span>{T.ack}</span>
          </button>

          <button type="button" disabled={!agreed} onClick={() => { onContinue(); onClose(); }}
            style={{
              marginTop: 14, width: '100%', minHeight: 60, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              borderRadius: 10, border: 0, fontFamily: 'inherit', fontSize: 19, fontWeight: 800,
              background: agreed ? 'var(--mk-blue, #1673FF)' : '#2a3140', color: agreed ? '#fff' : '#8E97A3',
              cursor: agreed ? 'pointer' : 'not-allowed', transition: 'background 160ms',
            }}>
            <Icon name="calendar" size={22} color={agreed ? '#fff' : '#8E97A3'}/> {T.book}
          </button>
          <div style={{ textAlign: 'center', marginTop: 10, fontSize: 15, color: '#B4BCC8' }}>
            {agreed ? T.newTab : T.locked}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { BookingTermsModal });
