/* A small locator: Europe in hairline grey with Czechia filled from the brand
   gradient, and a dot on Brno. Same Natural Earth data as the about map. */
function EuropeLocator({ lang = 'en', label }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    let dead = false;
    (async () => {
      if (!window.d3 || !window.topojson || !ref.current) return;
      const topo = await d3.json('https://cdn.jsdelivr.net/npm/world-atlas@2.0.2/countries-110m.json');
      if (dead || !ref.current) return;
      const countries = topojson.feature(topo, topo.objects.countries).features;
      const W = 300, H = 190;
      const projection = d3.geoMercator().center([14, 51]).scale(520).translate([W / 2, H / 2]);
      const path = d3.geoPath(projection);
      const svg = d3.select(ref.current).attr('viewBox', `0 0 ${W} ${H}`).attr('preserveAspectRatio', 'xMidYMid meet');
      svg.selectAll('*').remove();
      const grad = svg.append('defs').append('linearGradient')
        .attr('id', 'sm-locator-grad').attr('gradientUnits', 'userSpaceOnUse')
        .attr('x1', W * 0.35).attr('y1', H * 0.2).attr('x2', W * 0.7).attr('y2', H * 0.8);
      [['0%', '#e64ba0'], ['55%', '#6b3fd6'], ['100%', '#3355d1']].forEach(([o, c]) => grad.append('stop').attr('offset', o).attr('stop-color', c));
      svg.append('g').selectAll('path').data(countries).join('path')
        .attr('d', path)
        .attr('fill', (f) => (+f.id === 203 ? 'url(#sm-locator-grad)' : 'var(--gray-150)'))
        .attr('stroke', (f) => (+f.id === 203 ? 'transparent' : 'var(--gray-300)')).attr('stroke-width', 0.7);
      /* Neighbours named, because the shape of Europe is not common knowledge
         everywhere the site is read. */
      const named = (id, fallback) => {
        const row = (window.MARKETS || []).find((m) => m.id === id);
        return (row && row['name' + (lang === 'cs' ? 'Cs' : 'En')]) || fallback;
      };
      const marks = [
        { id: 276, name: named(276, 'Germany'), at: [10.2, 51.2] },
        { id: 616, name: named(616, 'Poland'), at: [19.4, 52.2] },
        { id: 40, name: named(40, 'Austria'), at: [14.2, 47.6] },
        { id: 703, name: named(703, 'Slovakia'), at: [20.8, 48.4] },
      ];
      svg.append('g').selectAll('text').data(marks).join('text')
        .attr('x', (d) => projection(d.at)[0]).attr('y', (d) => projection(d.at)[1])
        .attr('text-anchor', 'middle')
        .attr('font-family', 'var(--font-mono)').attr('font-size', 7.5)
        .attr('letter-spacing', '0.08em').attr('fill', 'var(--gray-500)')
        .text((d) => d.name.toUpperCase());
      const [bx, by] = projection([16.607, 49.195]);
      const dx = bx + 2, dy = by - 2;
      svg.append('circle').attr('cx', dx).attr('cy', dy).attr('r', 4.6).attr('fill', 'var(--white)');
      svg.append('circle').attr('cx', dx).attr('cy', dy).attr('r', 3).attr('fill', 'var(--orange-500)');
      svg.append('circle').attr('cx', dx).attr('cy', dy).attr('r', 8).attr('fill', 'none').attr('stroke', 'var(--orange-500)').attr('stroke-width', 1).attr('opacity', 0.4);
    })();
    return () => { dead = true; };
  }, [lang]);
  return <svg ref={ref} style={{ width: '100%', height: 'auto', display: 'block', marginTop: 16 }} role="img" aria-label={label || 'Brno, Czechia on a map of Europe'} />;
}

/* Web3Forms backend. The access key is public by design (client-side use
   is the documented pattern); submissions are e-mailed to Martin. */
const FORM_ENDPOINT = 'https://api.web3forms.com/submit';
const WEB3FORMS_KEY = 'c35428b1-d6cb-4b7a-bfd3-04f67ec9c3e2';

function Contact({ s, t, onBack, backLabel }) {
  const { FormField, Button, Icon, SocialIconRow } = window.SevcikMarketingDesignSystem_3203fa;
  const c = s.contact;
  const [backHover, setBackHover] = React.useState(false);
  const [formStatus, setFormStatus] = React.useState('idle'); // idle | sending | sent | error
  const mono = { fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--gray-500)' };
  const wrap = { maxWidth: 1080, margin: '0 auto', padding: '0 32px' };

  return (
    <div className="sm-screen-layer" style={{ position: 'fixed', inset: 0, zIndex: 60, background: 'var(--paper)', boxSizing: 'border-box', overflowY: 'auto' }}>
      <div style={{ ...wrap, paddingTop: 28, paddingBottom: 96 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 20, marginBottom: 'clamp(40px, 8vh, 96px)' }}>
          <button onClick={onBack} onMouseEnter={() => setBackHover(true)} onMouseLeave={() => setBackHover(false)}
            style={{ display: 'flex', alignItems: 'center', gap: 10, minHeight: 44, border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, ...mono, color: backHover ? 'var(--black)' : 'var(--gray-600)', transition: 'color .25s ease' }}>
            <span style={{ width: 44, height: 44, borderRadius: 'var(--radius-card)', display: 'flex', alignItems: 'center', justifyContent: 'center', background: backHover ? 'var(--black)' : 'rgba(10,10,10,0.06)', transition: 'background-color .25s ease' }}>
              <Icon name="arrow-up-left" size={16} color={backHover ? 'var(--white)' : 'var(--black)'} />
            </span>
            {backLabel || t.backHome}
          </button>
          <span style={mono}>{t.nav[3].label}</span>
        </div>

        <h1 style={{ margin: 0, maxWidth: '16ch', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'clamp(34px, 5.2vw, 76px)', lineHeight: 1.02, letterSpacing: '-0.03em', color: 'var(--black)' }}>{c.headline}</h1>
        <p style={{ margin: '24px 0 0', maxWidth: '46ch', fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 'clamp(17px, 1.8vw, 21px)', lineHeight: 1.5, color: 'var(--gray-700)' }}>{c.lead}</p>

        <div className="sm-contact-grid" style={{ display: 'grid', gridTemplateColumns: '300px minmax(0, 1fr)', gap: 10, marginTop: 'clamp(36px, 6vh, 72px)', alignItems: 'start' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <a href={`mailto:${CONTACT.email}`} style={{ display: 'block', background: 'var(--white)', borderRadius: 'var(--radius-card)', padding: '22px 24px', textDecoration: 'none' }}>
              <span style={{ ...mono, display: 'block' }}>{c.emailLabel}</span>
              <span style={{ display: 'block', marginTop: 10, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: '-0.01em', color: 'var(--black)' }}>{CONTACT.email}</span>
            </a>
            <a href={`https://wa.me/${CONTACT.whatsapp.replace(/[^\d]/g, '')}`} target="_blank" rel="noopener noreferrer"
              style={{ display: 'block', background: 'var(--white)', borderRadius: 'var(--radius-card)', padding: '22px 24px', textDecoration: 'none' }}>
              <span style={{ ...mono, display: 'block' }}>{c.phoneLabel}</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: '-0.01em', color: 'var(--black)' }}>
                <Icon name="whatsapp" size={16} color="var(--black)" />{CONTACT.phone}
              </span>
            </a>
            <div style={{ background: 'var(--white)', borderRadius: 'var(--radius-card)', padding: '22px 24px' }}>
              <span style={{ ...mono, display: 'block' }}>{c.whereLabel}</span>
              <span style={{ display: 'block', marginTop: 10, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: '-0.01em', color: 'var(--black)' }}>{c.whereValue || 'Brno, Czechia'}</span>
              <EuropeLocator lang={s.htmlLang} label={c.mapAlt} />
              <div style={{ marginTop: 18 }}><SocialIconRow size={15} gap={16} note={s.socialNote} links={{ linkedin: CONTACT.linkedin }} /></div>
            </div>
            {/* The card scans into a phone's address book - the only page where
                that is worth the space, since this is where a visitor comes to
                write the details down. */}
            <div style={{ background: 'var(--white)', borderRadius: 'var(--radius-card)', padding: '22px 24px', display: 'flex', alignItems: 'center', gap: 18 }}>
              <img src="../../assets/qr/martin-vcard.svg" alt={c.qrAlt || ''} width="84" height="84" style={{ display: 'block', borderRadius: 6, flexShrink: 0 }} />
              <div>
                <span style={{ ...mono, display: 'block' }}>{c.qrLabel}</span>
                <span style={{ display: 'block', marginTop: 8, fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.5, color: 'var(--gray-600)' }}>{c.qrNote}</span>
              </div>
            </div>
            {/* Identification, not bank details: what a client needs before
                raising a purchase order, and nothing that helps anyone forge
                an invoice in his name. */}
            {c.billingLines && (
              <div style={{ borderTop: '1.5px solid var(--gray-200)', paddingTop: 18 }}>
                <span style={{ ...mono, display: 'block' }}>{c.billingLabel}</span>
                {c.billingLines.map((line) => (
                  <span key={line} style={{ display: 'block', marginTop: 4, fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.55, color: 'var(--gray-600)' }}>{line}</span>
                ))}
              </div>
            )}
          </div>

          <form
            style={{ background: 'var(--white)', borderRadius: 'var(--radius-card)', padding: 'clamp(26px, 3.4vw, 44px)', display: 'flex', flexDirection: 'column', gap: 28 }}
            onSubmit={(e) => {
              e.preventDefault();
              const f = new FormData(e.currentTarget);
              const get = (k) => (f.get(k) || '').toString().trim();
              if (FORM_ENDPOINT) {
                if (formStatus === 'sending') return;
                const form = e.currentTarget;
                f.append('access_key', WEB3FORMS_KEY);
                f.append('subject', (s.htmlLang === 'cs' ? 'Poptávka z webu – ' : 'Enquiry from the website – ') + get('name'));
                f.append('from_name', 'sevcikmarketing.com');
                setFormStatus('sending');
                fetch(FORM_ENDPOINT, { method: 'POST', body: f })
                  .then((r) => r.json())
                  .then((d) => { if (d && d.success) { setFormStatus('sent'); form.reset(); } else { setFormStatus('error'); } })
                  .catch(() => setFormStatus('error'));
                return;
              }
              const phone = [get('phonePrefix'), get('phone')].filter(Boolean).join(' ');
              const body = [get('name'), get('company'), get('email'), phone && `${c.fields.phone}: ${phone}`, get('service') && `${c.service}: ${get('service')}`, get('budget') && `${c.budget}: ${get('budget')}`, '', get('message')].filter(Boolean).join('\n');
              window.location.href = `mailto:${CONTACT.email}?subject=${encodeURIComponent(s.htmlLang === 'cs' ? 'Popt\u00e1vka z webu' : 'Enquiry from the website')}&body=${encodeURIComponent(body)}`;
            }}
          >
            <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off" style={{ display: 'none' }} aria-hidden="true" />
            <div>
              <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 26, lineHeight: 1.15, letterSpacing: '-0.02em', color: 'var(--black)' }}>{c.formTitle}</h2>
              <p style={{ margin: '10px 0 0', ...mono, textTransform: 'none', letterSpacing: 0, fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.6 }}>{c.formNote}</p>
            </div>
            <div className="sm-form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
              <FormField name="name" label={c.fields.name} placeholder={(c.fieldHints || {}).name} required />
              <FormField name="company" label={c.fields.company} placeholder={(c.fieldHints || {}).company} required />
            </div>
            <FormField name="email" type="email" label={c.fields.email} placeholder={(c.fieldHints || {}).email} required />
            {/* Dialling code beside the number rather than inside it: the Czech
                form arrives on +420, the English one empty, because a UK
                visitor reading a Czech prefix would have to notice and undo
                it. Phone is optional - email is the channel that has to work. */}
            {c.fields.phone && (
              <div className="sm-phone-row" style={{ display: 'grid', gridTemplateColumns: '132px minmax(0, 1fr)', gap: 14, alignItems: 'end' }}>
                <select name="phonePrefix" aria-label={c.phonePrefixLabel || c.fields.phone}
                  defaultValue={c.phonePrefixDefault || ''}
                  style={{ width: '100%', background: 'transparent', border: 'none', borderBottom: '1px solid var(--gray-200)', padding: '10px 0', fontFamily: 'var(--font-body)', fontSize: 16, color: 'var(--black)', outline: 'none', appearance: 'none' }}
                  onFocus={(e) => { e.currentTarget.style.borderBottomColor = 'var(--gray-500)'; }}
                  onBlur={(e) => { e.currentTarget.style.borderBottomColor = 'var(--gray-200)'; }}>
                  {!c.phonePrefixDefault && <option value="">—</option>}
                  {phoneGroups(s.htmlLang, c.phoneGroupLabels).map((g) => (
                    <optgroup key={g.label} label={g.label}>
                      {g.options.map((o) => <option key={g.label + o.value + o.label} value={o.value}>{o.label}</option>)}
                    </optgroup>
                  ))}
                </select>
                <FormField name="phone" type="tel" autoComplete="tel" label={c.fields.phone} placeholder={(c.fieldHints || {}).phone} />
              </div>
            )}
            <FormField as="select" name="service" label={c.service} placeholder={c.servicePick} options={c.serviceOptions} required />
            <FormField as="textarea" name="message" label={c.fields.message} placeholder={(c.fieldHints || {}).message} required />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
              <span style={mono}>{c.replyNote}</span>
              <Button variant="pill-dark" size="md" type="submit" disabled={formStatus === 'sending'}>{formStatus === 'sending' ? c.sending : c.send}</Button>
            </div>
            {formStatus === 'sent' && (
              <p role="status" style={{ margin: 0, fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.6, color: 'var(--black)' }}>{c.sentMsg}</p>
            )}
            {formStatus === 'error' && (
              <p role="alert" style={{ margin: 0, fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.6, color: 'var(--orange-500)' }}>{c.errorMsg}</p>
            )}
          </form>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Contact });
