// Footer — contact form + links
const N8N_WEBHOOK_URL = 'https://YOUR-N8N-INSTANCE.hostinger.cloud/webhook/jk-contact';

function Footer({ lang }) {
  const t = (de, pl) => lang === 'de' ? de : pl;
  const waUrl = `https://wa.me/4917645186612?text=${encodeURIComponent(
    lang === 'de'
      ? 'Hi Kamil, ich interessiere mich für ein Projekt mit JK Media. Kannst du dich bitte kurz bei mir melden? Danke!'
      : 'Hej Kamil, mam pomysł na projekt — odezwij się, jak będziesz miał chwilę. Dzięki!'
  )}`;
  const [focused, setFocused] = React.useState('');
  const [form, setForm] = React.useState({ name: '', email: '', company: '', message: '', website: '' });
  const [status, setStatus] = React.useState('idle');
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;

  const update = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

  async function onSubmit(e) {
    e.preventDefault();
    if (form.website) return;
    if (!form.name.trim() || !form.email.trim() || !form.message.trim()) {
      setStatus('invalid');
      return;
    }
    setStatus('sending');
    try {
      const res = await fetch(N8N_WEBHOOK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          company: form.company,
          message: form.message,
          lang,
          source: 'jk-media-website',
          submittedAt: new Date().toISOString(),
        }),
      });
      if (!res.ok) throw new Error(String(res.status));
      setStatus('sent');
      setForm({ name: '', email: '', company: '', message: '', website: '' });
    } catch (err) {
      setStatus('error');
    }
  }

  const fields = [
    ['name', t('Name','Imię'), 'text'],
    ['email', t('E-Mail','E-Mail'), 'email'],
    ['company', t('Unternehmen','Firma'), 'text'],
  ];

  const btnLabel = {
    idle: t('Kostenlose Beratung anfragen','Zapytaj o bezpłatną konsultację') + ' →',
    invalid: t('Bitte alle Pflichtfelder ausfüllen','Wypełnij wszystkie wymagane pola'),
    sending: t('Wird gesendet…','Wysyłanie…'),
    sent: t('Danke! Wir melden uns.','Dziękujemy! Odezwiemy się.'),
    error: t('Fehler — bitte erneut versuchen','Błąd — spróbuj ponownie'),
  }[status];

  const btnBg = status === 'sent' ? '#1f7a3a' : status === 'error' ? '#a83232' : 'var(--gold)';
  const btnColor = (status === 'sent' || status === 'error') ? '#fff' : '#0A0A0A';

  return (
    <footer id="contact" className="section" style={{ borderTop: '1px solid rgba(212,175,55,.1)', paddingBottom: 48, padding: isMobile ? '72px 0 40px' : '120px 0 48px' }}>
      <div className="container">
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1.1fr 1fr',
          gap: isMobile ? 48 : 80,
          marginBottom: isMobile ? 56 : 80
        }}>
          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--gold)', letterSpacing: '.25em', textTransform: 'uppercase', marginBottom: 18 }}>— {t('Kontakt','Kontakt')}</div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: isMobile ? 'clamp(36px, 10vw, 48px)' : 56, lineHeight: 1.05, letterSpacing: '-0.03em', marginBottom: 28 }}>
              {t('Lass uns reden.','Porozmawiajmy.')}
            </h2>
            <p style={{ fontSize: 16, color: 'var(--text-2)', lineHeight: 1.7, maxWidth: 440, marginBottom: 40 }}>
              {t('Die Erstberatung ist komplett kostenlos — kein Risiko, nur Ergebnisse.',
                 'Pierwsza konsultacja jest całkowicie bezpłatna — bez ryzyka, tylko wyniki.')}
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14, fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-2)' }}>
              <a href="mailto:info@jk-media.eu">info@jk-media.eu</a>
              <a href={waUrl}>WhatsApp · +49 176 45186612</a>
              <div>Gubin (PL) &nbsp;·&nbsp; Guben (DE)</div>
            </div>
          </div>
          <form style={{ display: 'flex', flexDirection: 'column', gap: 18 }} onSubmit={onSubmit} noValidate>
            <input
              type="text"
              name="website"
              tabIndex="-1"
              autoComplete="off"
              value={form.website}
              onChange={update('website')}
              style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
              aria-hidden="true"
            />
            {fields.map(([k, l, type]) => (
              <div key={k}>
                <label style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 13, marginBottom: 8 }}>{l}</label>
                <input
                  type={type}
                  value={form[k]}
                  onChange={update(k)}
                  onFocus={()=>setFocused(k)}
                  onBlur={()=>setFocused('')}
                  required={k !== 'company'}
                  style={{
                    width: '100%', padding: '14px 18px', borderRadius: 12,
                    background: '#0A0A0A', color: 'var(--text)',
                    border: `1px solid rgba(212,175,55,${focused===k?.4:.1})`,
                    fontFamily: 'inherit', fontSize: 14, outline: 'none', transition: 'border-color .3s'
                  }}
                />
              </div>
            ))}
            <div>
              <label style={{ display: 'block', fontFamily: 'var(--font-display)', fontSize: 13, marginBottom: 8 }}>{t('Nachricht','Wiadomość')}</label>
              <textarea
                rows="4"
                value={form.message}
                onChange={update('message')}
                onFocus={()=>setFocused('msg')}
                onBlur={()=>setFocused('')}
                required
                style={{
                  width: '100%', padding: '14px 18px', borderRadius: 12,
                  background: '#0A0A0A', color: 'var(--text)',
                  border: `1px solid rgba(212,175,55,${focused==='msg'?.4:.1})`,
                  fontFamily: 'inherit', fontSize: 14, outline: 'none', resize: 'vertical'
                }}
              />
            </div>
            <button
              type="submit"
              disabled={status === 'sending' || status === 'sent'}
              style={{
                marginTop: 8, padding: '16px 28px', borderRadius: 10, background: btnBg, color: btnColor,
                fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, letterSpacing: '.01em',
                boxShadow: '0 4px 16px rgba(212,175,55,.2)',
                cursor: status === 'sending' || status === 'sent' ? 'default' : 'pointer',
                transition: 'background .3s, color .3s',
                border: 'none'
              }}
            >{btnLabel}</button>
          </form>
        </div>
        <div style={{
          paddingTop: 32,
          borderTop: '1px solid rgba(212,175,55,.08)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: isMobile ? 'flex-start' : 'center',
          flexDirection: isMobile ? 'column' : 'row',
          gap: isMobile ? 14 : 0,
          fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)', letterSpacing: '.05em'
        }}>
          <div>© 2026 JK MediaAI. {t('Alle Rechte vorbehalten.','Wszelkie prawa zastrzeżone.')}</div>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="#">Impressum</a>
            <a href="#">Datenschutz</a>
          </div>
        </div>
      </div>
    </footer>
  );
}
window.Footer = Footer;
