/* global React */
/* =============================================================
   VzdelAI — SEKCIA: Kontakt (formulár cez Web3Forms)
   -------------------------------------------------------------
   Funkčný formulár: meno · e-mail · organizácia · správa.
   Validácia client-side (HTML5 + JS), odoslanie cez fetch
   na https://api.web3forms.com/submit. Honeypot proti botom.

   Kde nahradiť access key: konštanta WEB3FORMS_ACCESS_KEY nižšie.
   Kde upraviť texty hlášok: konštanta MESSAGES nižšie.
   ============================================================= */

/* ⬇⬇⬇ NAHRADIŤ PRED DEPLOYOM ⬇⬇⬇ */
const WEB3FORMS_ACCESS_KEY = 'effeb045-0777-4e06-afba-a19e8f90ed86';
/* ⬆⬆⬆ NAHRADIŤ PRED DEPLOYOM ⬆⬆⬆ */

const MESSAGES = {
  success: 'Ďakujeme za Vašu správu. Čo najskôr sa Vám ozveme.',
  error: 'Správu sa nepodarilo odoslať. Skúste to prosím neskôr, alebo nás kontaktujte priamo na vzdelai@uniza.sk.',
  required: 'Toto pole je povinné.',
  invalidEmail: 'Zadajte platnú e-mailovú adresu.',
  shortMessage: 'Správa musí mať aspoň 10 znakov.'
};

function V2_Contact() {
  const [form, setForm] = React.useState({ name: '', email: '', organization: '', message: '' });
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // 'idle' | 'sending' | 'success' | 'error'
  const feedbackRef = React.useRef(null);

  React.useEffect(() => {
    if ((status === 'success' || status === 'error') && feedbackRef.current) {
      feedbackRef.current.focus();
    }
  }, [status]);

  const fieldStyle = {
    width: '100%',
    padding: '14px 16px',
    border: '1px solid var(--border)',
    borderRadius: 8,
    background: '#fff',
    fontFamily: 'var(--font-body)',
    fontSize: 15, color: 'var(--vz-ink)',
    boxSizing: 'border-box'
  };
  const labelStyle = {
    display: 'block',
    fontFamily: 'var(--font-mono)',
    fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
    color: 'var(--vz-ink-60)', marginBottom: 8, fontWeight: 500
  };

  const validate = (data) => {
    const e = {};
    if (!data.name.trim() || data.name.trim().length < 2) e.name = MESSAGES.required;
    if (!data.email.trim()) e.email = MESSAGES.required;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email.trim())) e.email = MESSAGES.invalidEmail;
    if (!data.organization.trim()) e.organization = MESSAGES.required;
    if (!data.message.trim()) e.message = MESSAGES.required;
    else if (data.message.trim().length < 10) e.message = MESSAGES.shortMessage;
    return e;
  };

  const handleChange = (field) => (ev) => {
    const value = ev.target.value;
    setForm((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    }
  };

  const inputClass = (field) => `vz-input${errors[field] ? ' has-error' : ''}`;
  const errId = (field) => `vz-${field}-error`;
  const ariaProps = (field) => ({
    'aria-required': true,
    'aria-invalid': errors[field] ? true : undefined,
    'aria-describedby': errors[field] ? errId(field) : undefined
  });

  const handleSubmit = async (ev) => {
    ev.preventDefault();
    if (status === 'sending') return;

    const validationErrors = validate(form);
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      setStatus('idle');
      return;
    }

    // Honeypot — ak je vyplnený, ticho zlyháme bez odoslania (anti-bot)
    const honeypot = ev.target.elements.botcheck;
    if (honeypot && honeypot.value) return;

    setStatus('sending');
    setErrors({});

    try {
      const formData = new FormData(ev.target);
      // Reply-To header → kliknutie na "Odpovedať" pôjde priamo odosielateľovi formulára
      formData.set('replyto', form.email);
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        body: formData
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data && data.success) {
        setStatus('success');
        setForm({ name: '', email: '', organization: '', message: '' });
      } else {
        setStatus('error');
      }
    } catch (err) {
      setStatus('error');
    }
  };

  return (
    <section id="kontakt" className="vz-section vz-snap" style={{ background: 'var(--vz-mist)' }}>
      <div className="vz-container">
        <div className="vz-grid-2-eq">
          <div>
            <span className="vz-eyebrow" style={{ display: 'block', marginBottom: 16 }}>Kontakt</span>
            <h2 className="vz-fluid-h2" style={{
              fontFamily: 'var(--font-display)', fontWeight: 800,
              lineHeight: 1.05, letterSpacing: '-0.025em',
              color: 'var(--vz-ink)', margin: 0
            }}>
              Máte záujem o&nbsp;<span style={{
                background: 'var(--grad-ai)',
                WebkitBackgroundClip: 'text', backgroundClip: 'text',
                WebkitTextFillColor: 'transparent', color: 'transparent'
              }}>spoluprácu</span>?
            </h2>
            <p style={{ fontSize: 18, lineHeight: 1.6, color: 'var(--vz-ink-60)', marginTop: 24, maxWidth: 460 }}>Hľadáme univerzity, fakulty a partnerov z praxe, ktorí chcú integrovať VzdelAI do výučby, rozvíjať odbornú spoluprácu alebo sa zapojiť do ďalšieho výskumu.


            </p>
            <div style={{ marginTop: 40, display: 'grid', gap: 16 }}>
              <div>
                <div className="vz-mono" style={{
                  fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
                  color: 'var(--vz-ink-40)', marginBottom: 4
                }}>E-mail</div>
                <div style={{ color: 'var(--vz-ink)', fontWeight: 500 }}>vzdelai@uniza.sk</div>
              </div>
              <div>
                <div className="vz-mono" style={{
                  fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
                  color: 'var(--vz-ink-40)', marginBottom: 4
                }}>Adresa</div>
                <div style={{ color: 'var(--vz-ink)', fontWeight: 500 }}>
                  Žilinská univerzita v&nbsp;Žiline · FPEDAS<br />
                  Univerzitná 8215/1 · 010 26 Žilina
                </div>
              </div>
            </div>
          </div>
          <form
            onSubmit={handleSubmit}
            noValidate
            className="vz-form-card"
            style={{
              background: '#fff', borderRadius: 16,
              border: '1px solid var(--border)',
              boxShadow: '0 1px 2px rgba(15,10,51,0.04), 0 12px 32px -16px rgba(15,10,51,0.10)'
            }}>

            {/* Web3Forms — povinné a voliteľné polia (skryté) */}
            <input type="hidden" name="access_key" value={WEB3FORMS_ACCESS_KEY} />
            <input type="hidden" name="subject" value="Nová správa zo vzdelai.sk" />
            <input type="hidden" name="from_name" value="vzdelai.sk kontaktný formulár" />
            {/* Honeypot — skutoční ľudia ho nevidia, boti ho vyplnia */}
            <input type="text" name="botcheck" tabIndex="-1" autoComplete="off" style={{ display: 'none' }} />

            <div style={{ display: 'grid', gap: 20 }}>
              <div>
                <label htmlFor="vz-name" style={labelStyle}>Meno a priezvisko</label>
                <input
                  id="vz-name" name="name" type="text" autoComplete="name"
                  placeholder="Zadajte svoje meno a priezvisko"
                  className={inputClass('name')} style={fieldStyle}
                  value={form.name} onChange={handleChange('name')}
                  required minLength={2}
                  {...ariaProps('name')} />
                {errors.name && (
                  <span id={errId('name')} className="vz-form-error-msg">{errors.name}</span>
                )}
              </div>
              <div>
                <label htmlFor="vz-email" style={labelStyle}>E-mail</label>
                <input
                  id="vz-email" name="email" type="email" autoComplete="email"
                  placeholder="Zadajte e-mailovú adresu"
                  className={inputClass('email')} style={fieldStyle}
                  value={form.email} onChange={handleChange('email')}
                  required
                  {...ariaProps('email')} />
                {errors.email && (
                  <span id={errId('email')} className="vz-form-error-msg">{errors.email}</span>
                )}
              </div>
              <div>
                <label htmlFor="vz-org" style={labelStyle}>Organizácia</label>
                <input
                  id="vz-org" name="organization" type="text" autoComplete="organization"
                  placeholder="Názov univerzity, fakulty alebo organizácie"
                  className={inputClass('organization')} style={fieldStyle}
                  value={form.organization} onChange={handleChange('organization')}
                  required
                  {...ariaProps('organization')} />
                {errors.organization && (
                  <span id={errId('organization')} className="vz-form-error-msg">{errors.organization}</span>
                )}
              </div>
              <div>
                <label htmlFor="vz-msg" style={labelStyle}>Správa</label>
                <textarea
                  id="vz-msg" name="message" rows="5"
                  placeholder="Stručne opíšte, čo vás zaujíma alebo s čím vám vieme pomôcť"
                  className={inputClass('message')} style={{ ...fieldStyle, resize: 'vertical' }}
                  value={form.message} onChange={handleChange('message')}
                  required minLength={10}
                  {...ariaProps('message')} />
                {errors.message && (
                  <span id={errId('message')} className="vz-form-error-msg">{errors.message}</span>
                )}
              </div>

              <button
                type="submit"
                disabled={status === 'sending'}
                style={{
                  marginTop: 8,
                  padding: '16px 28px', borderRadius: 12, border: 'none',
                  background: 'var(--vz-violet)', color: '#fff',
                  fontFamily: 'var(--font-body)', fontSize: 16, fontWeight: 600,
                  cursor: status === 'sending' ? 'wait' : 'pointer',
                  opacity: status === 'sending' ? 0.7 : 1,
                  boxShadow: 'var(--shadow-violet)',
                  transition: 'opacity 160ms ease'
                }}>
                {status === 'sending' ? 'Odosielame...' : 'Odoslať správu'}
              </button>

              {status === 'success' && (
                <div
                  ref={feedbackRef}
                  tabIndex="-1"
                  role="status"
                  aria-live="polite"
                  className="vz-form-feedback is-success">
                  {MESSAGES.success}
                </div>
              )}
              {status === 'error' && (
                <div
                  ref={feedbackRef}
                  tabIndex="-1"
                  role="alert"
                  aria-live="assertive"
                  className="vz-form-feedback is-error">
                  {MESSAGES.error}
                </div>
              )}
            </div>
          </form>
        </div>
      </div>
    </section>);

}

/* ────── EXPORT ────── */
window.V2_Contact = V2_Contact;
