/* global React */
const _useInView_k = window.useInView;
const { useState: _useState_k, useEffect: _useEffect_k } = React;

// Parse #kontakt?type=...&unit=... – the hash includes the section id
function parseHashParams() {
  const h = window.location.hash || '';
  const qIdx = h.indexOf('?');
  if (qIdx === -1) return {};
  const qs = h.substring(qIdx + 1);
  const out = {};
  for (const pair of qs.split('&')) {
    if (!pair) continue;
    const [k, v = ''] = pair.split('=');
    out[decodeURIComponent(k)] = decodeURIComponent(v.replace(/\+/g, ' '));
  }
  return out;
}

const INTENT_COPY = {
  waitlist: {
    h: 'Zápis do waitlistu',
    sub: 'Sedlčany jsou plně obsazené – dejte nám kontakt a ozveme se, jakmile se uvolní jednotka.',
  },
  prohlidka: {
    h: 'Domluvit prohlídku areálu',
    sub: 'Rádi vám areál ukážeme. Zanechte kontakt a navrhneme termín.',
  },
  'na-miru': {
    h: 'Poptat prostor na míru',
    sub: 'Postavíme vám prostor podle vašich potřeb. Napište, co plánujete – ozveme se s návrhem.',
  },
};

const TYPE_LABELS = {
  sklad: 'Sklad',
  vyroba: 'Výroba',
  kancelar: 'Kancelář',
};

const BUILDING_BY_UNIT = {
  'A-17': 'Budova A',
  'G1-70': 'Budova G1',
  'G-510': 'Budova G',
};

function ContactInfo() {
  return (
    <div className="kontakt-info">
      <div className="kontakt-person">
        <img
          className="kontakt-person-photo"
          src="assets/foto-ck-profil.jpg"
          alt="Ing. Čestmír Kříž, obchodní manažer"
          width="112"
          height="112"
          loading="lazy"
        />
        <div className="kontakt-person-text">
          <div className="kontakt-person-name-row">
            <h3 className="t-display kontakt-person-name">Ing. Čestmír Kříž</h3>
            <a
              href="https://www.linkedin.com/in/cestmirkriz/"
              className="kontakt-person-linkedin"
              target="_blank"
              rel="noopener noreferrer"
              aria-label="LinkedIn profil Ing. Čestmíra Kříže – otevře se v novém okně"
              title="LinkedIn"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                <path d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.86 0-2.14 1.45-2.14 2.95v5.66H9.34V9h3.42v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z"/>
              </svg>
            </a>
          </div>
          <div className="kontakt-person-role">Obchodní manažer · BUS real, s.r.o.</div>
        </div>
      </div>

      <div className="kontakt-channels">
        <a href="tel:+420720620718" className="kontakt-link kontakt-tel">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>
          </svg>
          +420 720 620 718
        </a>
        <a href="mailto:cestmirkriz@busreal.cz" className="kontakt-link kontakt-mail">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
            <polyline points="22,6 12,13 2,6"/>
          </svg>
          cestmirkriz@busreal.cz
        </a>
      </div>

      <div className="kontakt-addr">
        <div className="kontakt-addr-label">Adresa areálu</div>
        <address>
          K Podlesí 540<br />
          261 01 Příbram VI – Březové Hory
        </address>
      </div>

      <div className="kontakt-map">
        <iframe
          title="Mapa areálu BUS real – Mapy.cz"
          src="https://mapy.com/en/?x=13.9916222&y=49.6911717&z=17&base=ophoto&frame=1"
          width="100%"
          height="280"
          loading="lazy"
          referrerPolicy="no-referrer-when-downgrade"
          style={{ border: 0 }}
        />
        <a
          className="kontakt-map-link t-mono"
          href="https://mapy.cz/zakladni?source=coor&id=13.9916222%2C49.6911717&x=13.9916222&y=49.6911717&z=17&base=ophoto"
          target="_blank"
          rel="noopener noreferrer"
        >
          Otevřít v Mapy.cz →
        </a>
      </div>
    </div>
  );
}

function ContactForm() {
  const [submitted, setSubmitted] = _useState_k(false);
  const [submitting, setSubmitting] = _useState_k(false);
  const [submitError, setSubmitError] = _useState_k(null);
  const [errors, setErrors] = _useState_k({});
  const [params, setParams] = _useState_k({});
  const [form, setForm] = _useState_k({
    name: '',
    phone: '',
    email: '',
    areal: 'pribram',
    message: '',
    gdpr: false,
    website: '', // honeypot
  });

  // hash pre-fill on mount + on hashchange
  _useEffect_k(() => {
    const apply = () => {
      const h = window.location.hash || '';
      const p = parseHashParams();
      setParams(p);
      setForm((f) => {
        const next = { ...f };
        if (p.areal === 'pribram' || p.areal === 'sedlcany') next.areal = p.areal;
        const seeds = [];
        if (p.type && TYPE_LABELS[p.type]) {
          seeds.push(`Mám zájem o pronájem – ${TYPE_LABELS[p.type].toLowerCase()}.`);
        }
        if (p.unit && !f.message.includes(p.unit)) {
          const bld = BUILDING_BY_UNIT[p.unit] ? ` (${BUILDING_BY_UNIT[p.unit]})` : '';
          seeds.push(`Konkrétně mě zajímá jednotka ${p.unit}${bld}.`);
        }
        if (seeds.length && !seeds.some((s) => f.message.includes(s))) {
          next.message = seeds.join(' ') + (f.message ? '\n\n' + f.message : '');
        }
        return next;
      });
      // Browser doesn't auto-scroll to `#kontakt?type=sklad` because the fragment
      // (with the `?`) doesn't match any element id. Do it manually if hash
      // points to #kontakt with extra params.
      if (h.startsWith('#kontakt') && h.includes('?')) {
        const el = document.getElementById('kontakt');
        if (el) {
          // Small delay so React has time to mount, then smooth-scroll.
          setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'start' }), 50);
        }
      }
    };
    apply();
    window.addEventListener('hashchange', apply);
    return () => window.removeEventListener('hashchange', apply);
  }, []);

  const intent = params.intent;
  const copy = INTENT_COPY[intent] || {
    h: 'Mám zájem o pronájem',
    sub: 'Vyplňte základní údaje a my se vám ozveme s konkrétní nabídkou.',
  };

  const set = (k) => (e) => {
    const v = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm((f) => ({ ...f, [k]: v }));
    if (errors[k]) setErrors((er) => ({ ...er, [k]: undefined }));
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = 'Toto pole prosím vyplňte.';
    if (!form.phone.trim()) er.phone = 'Toto pole prosím vyplňte.';
    if (!form.email.trim()) er.email = 'Toto pole prosím vyplňte.';
    if (!form.gdpr) er.gdpr = 'Bez souhlasu vám nemůžeme odpovědět.';
    setErrors(er);
    if (Object.keys(er).length > 0) return;

    setSubmitting(true);
    setSubmitError(null);
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const j = await r.json().catch(() => ({}));
      if (!r.ok || !j.ok) throw new Error(j.error || 'Nepodařilo se odeslat.');
      setSubmitted(true);
    } catch (err) {
      setSubmitError(err.message || 'Nepodařilo se odeslat. Zavolejte prosím +420 720 620 718.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <div className="kontakt-success" role="status">
        <div className="kontakt-success-icon" aria-hidden="true">
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12"></polyline>
          </svg>
        </div>
        <h3 className="t-display kontakt-success-h">Děkujeme.</h3>
        <p className="t-body-l kontakt-success-body">
          Ozveme se vám během 24 hodin – obvykle ještě týž den. Pokud spěcháte, zavolejte rovnou na <a href="tel:+420720620718">+420 720 620 718</a>.
        </p>
        <button
          type="button"
          className="btn btn-outline"
          onClick={() => { setSubmitted(false); setErrors({}); }}
        >
          Odeslat další poptávku
        </button>
      </div>
    );
  }

  return (
    <form className="kontakt-form" onSubmit={onSubmit} noValidate>
      <h3 className="t-display kontakt-form-h">{copy.h}</h3>
      <p className="t-body kontakt-form-sub">{copy.sub}</p>

      <div className={`field ${errors.name ? 'has-error' : ''}`}>
        <label htmlFor="kf-name">Jméno a příjmení <span className="req">*</span></label>
        <input id="kf-name" className="input" type="text" placeholder="Např. Jan Novák" value={form.name} onChange={set('name')} />
        {errors.name && <div className="field-error">{errors.name}</div>}
      </div>

      <div className={`field ${errors.phone ? 'has-error' : ''}`}>
        <label htmlFor="kf-phone">Telefon <span className="req">*</span></label>
        <input id="kf-phone" className="input" type="tel" placeholder="+420 …" value={form.phone} onChange={set('phone')} />
        {errors.phone && <div className="field-error">{errors.phone}</div>}
      </div>

      <div className={`field ${errors.email ? 'has-error' : ''}`}>
        <label htmlFor="kf-email">E-mail <span className="req">*</span></label>
        <input id="kf-email" className="input" type="email" placeholder="vas@email.cz" value={form.email} onChange={set('email')} />
        {errors.email && <div className="field-error">{errors.email}</div>}
      </div>

      <div className="field" role="radiogroup" aria-labelledby="kf-areal-label">
        <span id="kf-areal-label" className="field-label-aria">Areál</span>
        <div className="field-radio-row">
          <label className="field-radio">
            <input
              type="radio"
              name="areal"
              value="pribram"
              checked={form.areal === 'pribram'}
              onChange={set('areal')}
            />
            <span>Příbram</span>
          </label>
          <label className="field-radio">
            <input
              type="radio"
              name="areal"
              value="sedlcany"
              checked={form.areal === 'sedlcany'}
              onChange={set('areal')}
            />
            <span>Sedlčany</span>
          </label>
        </div>
      </div>

      <div className="field">
        <label htmlFor="kf-msg">Zpráva</label>
        <textarea id="kf-msg" className="textarea" rows={4} placeholder="Co plánujete v prostoru dělat? Jakou velikost a typ potřebujete?" value={form.message} onChange={set('message')} />
      </div>

      <label className={`checkbox-row ${errors.gdpr ? 'has-error' : ''}`}>
        <input type="checkbox" checked={form.gdpr} onChange={set('gdpr')} />
        <span>
          Souhlasím se zpracováním osobních údajů podle <a href="zasady-ochrany-osobnich-udaju.html" target="_blank" rel="noopener">zásad ochrany osobních údajů</a>.
          {errors.gdpr && <span className="field-error" style={{ display: 'block' }}>{errors.gdpr}</span>}
        </span>
      </label>

      {/* honeypot — skrytý před lidmi i čtečkami; vyplňují ho jen boti */}
      <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, overflow: 'hidden' }}>
        <label htmlFor="kf-website">Web (nevyplňujte)</label>
        <input id="kf-website" type="text" tabIndex={-1} autoComplete="off" value={form.website} onChange={set('website')} />
      </div>

      {submitError && (
        <div role="alert" className="field-error" style={{ marginTop: 4, padding: '12px 14px', border: '1px solid hsl(0 70% 55% / 0.4)', background: 'hsl(0 70% 55% / 0.08)', borderRadius: 8 }}>
          {submitError}
        </div>
      )}

      <button type="submit" className="btn btn-primary kontakt-submit" disabled={submitting} aria-busy={submitting}>
        {submitting ? 'Odesílám…' : 'Odeslat poptávku'}
        {!submitting && (
          <svg className="arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>
        )}
      </button>
    </form>
  );
}

function SectionKontakt() {
  const [headRef, headIn] = _useInView_k(0.2);
  const [leftRef, leftIn] = _useInView_k(0.1);
  const [rightRef, rightIn] = _useInView_k(0.05);

  return (
    <section id="kontakt" className="sec sec-kontakt">
      <div className="container">
        <header ref={headRef} className={`kontakt-header ${headIn ? 'is-in' : ''}`}>
          <div className="t-eyebrow"><span className="dot"></span>Kontakt</div>
          <h2 className="t-display t-h2 kontakt-h2">Pojďme to probrat osobně.</h2>
          <p className="t-body-l kontakt-sub">
            Zavolejte, napište, nebo vyplňte formulář. Většinu poptávek řešíme do 24 hodin.
          </p>
        </header>

        <div className="kontakt-grid">
          <div ref={leftRef} className={`kontakt-col-left ${leftIn ? 'is-in' : ''}`}>
            <ContactInfo />
          </div>
          <div ref={rightRef} className={`kontakt-col-right ${rightIn ? 'is-in' : ''}`}>
            <ContactForm />
          </div>
        </div>
      </div>

      <div className="container about-rail-wrap">
        <div className="rail" />
      </div>
    </section>
  );
}

window.SectionKontakt = SectionKontakt;
