/* Créapeiron maison — concierge (private inquiry) + footer. */
const CPDS2 = window.CrApeironELYSIENDesignSystem_f7a37f;
const { Eyebrow: CPEb, Button: CPB2, Field: CPField, Select: CPSelect, Divider: CPDiv2 } = CPDS2;
const WIDE2 = { maxWidth: 'var(--container-wide)', margin: '0 auto', padding: '0 var(--gutter)' };

function Concierge() {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const tsRef = React.useRef(null);   // widget container
  const tsId = React.useRef(null);    // rendered widget id

  React.useEffect(() => {
    let cancelled = false;
    (function mount() {
      if (cancelled || tsId.current != null || !tsRef.current) return;
      if (!window.turnstile) { setTimeout(mount, 200); return; } // script still loading
      tsId.current = window.turnstile.render(tsRef.current, {
        sitekey: window.TURNSTILE_SITEKEY,
        theme: 'dark',
        'error-callback': () => setError('Verification failed to load. Please retry.'),
        'expired-callback': () => { if (tsId.current != null) window.turnstile.reset(tsId.current); },
      });
    })();
    return () => { cancelled = true; if (tsId.current != null && window.turnstile) { window.turnstile.remove(tsId.current); tsId.current = null; } };
  }, []);

  async function handleSubmit(e) {
    e.preventDefault();
    const token = (window.turnstile && tsId.current != null) ? window.turnstile.getResponse(tsId.current) : '';
    if (!token) { setError('Please complete the verification.'); return; }
    setError(null);
    setSending(true);
    const payload = Object.fromEntries(new FormData(e.currentTarget).entries());
    payload.turnstileToken = token;
    try {
      const res = await fetch('/api/inquiry', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || 'Could not send your inquiry. Please try again.');
      }
      setSent(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setSending(false);
      if (window.turnstile && tsId.current != null) window.turnstile.reset(tsId.current); // token is single-use
    }
  }

  const preset = React.useMemo(() => {
    const p = new URLSearchParams(window.location.search);
    const finish = p.get('finish');
    const edition = p.get('edition');
    const build = p.get('build');
    return {
      hasPreset: !!(finish || edition || build),
      editionValue: (edition === 'signature' || build) ? 'ELYSIEN — Signature' : undefined,
      message: build ? build : (finish ? ('I would like to enquire about the ELYSIEN — Signature in the ' + finish + ' finish.') : undefined),
    };
  }, []);
  React.useEffect(() => {
    if (!preset.hasPreset) return;
    const el = document.getElementById('concierge');
    if (el) {
      const t = setTimeout(() => window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 40, behavior: 'smooth' }), 200);
      return () => clearTimeout(t);
    }
  }, [preset.hasPreset]);
  return (
    <section id="concierge" style={{ background: 'var(--surface-page)', padding: 'var(--section-y) 0', borderTop: '1px solid var(--border-hairline)' }}>
      <div style={WIDE2}>
        <div style={{ display: 'grid', gridTemplateColumns: '0.9fr 1.1fr', gap: 'var(--sp-10)' }} className="cp-split">
          <div data-reveal>
            <CPEb tick={true}>Private Inquiry</CPEb>
            <h2 style={{ margin: '26px 0 24px', fontFamily: 'var(--font-serif)', fontWeight: 300, fontSize: 'var(--fs-display-2)', lineHeight: 1.04, letterSpacing: 'var(--ls-display)', color: 'var(--text-primary)' }}>
              The Concierge
            </h2>
            <p className="cp-body" style={{ maxWidth: '40ch', marginBottom: 'var(--sp-7)', fontSize: 'var(--fs-body-lg)' }}>
              For acquisition, a private viewing, or a bespoke commission. Your message reaches our maison directly, and is held in confidence.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
              {[['Atelier', 'Brno, Czech Republic'], ['Correspondence', 'info@creapeiron.com']].map(([k, v]) => (
                <div key={k} style={{ display: 'flex', gap: '20px', alignItems: 'baseline' }}>
                  <span style={{ flex: '0 0 130px', fontFamily: 'var(--font-display)', fontSize: 'var(--fs-micro)', letterSpacing: 'var(--ls-wider)', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{k}</span>
                  <span style={{ fontFamily: 'var(--font-body)', fontWeight: 300, color: 'var(--text-secondary)' }}>{v}</span>
                </div>
              ))}
              <div style={{ display: 'flex', gap: '20px', alignItems: 'center', marginTop: '4px' }}>
                <span style={{ flex: '0 0 130px', fontFamily: 'var(--font-display)', fontSize: 'var(--fs-micro)', letterSpacing: 'var(--ls-wider)', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Follow</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: '18px' }}>
                  {[
                    ['Instagram', 'https://www.instagram.com/creapeiron', 'M7.5 2h9A5.5 5.5 0 0 1 22 7.5v9a5.5 5.5 0 0 1-5.5 5.5h-9A5.5 5.5 0 0 1 2 16.5v-9A5.5 5.5 0 0 1 7.5 2Zm0 1.8A3.7 3.7 0 0 0 3.8 7.5v9a3.7 3.7 0 0 0 3.7 3.7h9a3.7 3.7 0 0 0 3.7-3.7v-9a3.7 3.7 0 0 0-3.7-3.7h-9ZM12 7a5 5 0 1 1 0 10 5 5 0 0 1 0-10Zm0 1.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4ZM17.3 5.6a1.1 1.1 0 1 1 0 2.2 1.1 1.1 0 0 1 0-2.2Z'],
                    ['Facebook', 'https://www.facebook.com/share/1Dx7GnVRuZ/', 'M13.5 21v-8h2.7l.4-3.1h-3.1V7.9c0-.9.25-1.5 1.55-1.5h1.65V3.6A22 22 0 0 0 14.4 3.5c-2.4 0-4 1.45-4 4.1v2.3H7.7V13h2.7v8h3.1Z'],
                    ['YouTube', 'https://www.youtube.com/@Creapeiron', 'M22.5 8.2a3 3 0 0 0-2.1-2.1C18.5 5.6 12 5.6 12 5.6s-6.5 0-8.4.5A3 3 0 0 0 1.5 8.2 31 31 0 0 0 1 12a31 31 0 0 0 .5 3.8 3 3 0 0 0 2.1 2.1c1.9.5 8.4.5 8.4.5s6.5 0 8.4-.5a3 3 0 0 0 2.1-2.1A31 31 0 0 0 23 12a31 31 0 0 0-.5-3.8ZM10 15.1V8.9l5.3 3.1-5.3 3.1Z'],
                  ].map(([label, href, d]) => (
                    <a key={label} href={href} target="_blank" rel="noopener noreferrer" aria-label={label} className="cp-social" style={{ display: 'inline-flex', color: 'var(--text-secondary)', transition: 'color 240ms ease' }}>
                      <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d={d}></path></svg>
                    </a>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div data-reveal className="cp-form-card" style={{ background: 'var(--surface-card)', border: '1px solid var(--border-hairline)', borderRadius: 'var(--r-md)', padding: 'clamp(28px, 4vw, 52px)' }}>
            {sent ? (
              <div style={{ minHeight: '380px', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start', gap: '18px' }}>
                <span style={{ width: '48px', height: '1px', background: 'var(--accent)' }} />
                <h3 style={{ margin: 0, fontFamily: 'var(--font-serif)', fontWeight: 400, fontSize: 'var(--fs-display-3)', color: 'var(--text-primary)' }}>Thank you.</h3>
                <p className="cp-body" style={{ margin: 0, maxWidth: '34ch' }}>Your inquiry has reached the maison. A member of our concierge will respond to you personally.</p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '30px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '30px' }} className="cp-two">
                  <CPField label="Full name" name="name" required placeholder="" />
                  <CPField label="Email" name="email" type="email" required placeholder="" />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '30px' }} className="cp-two">
                  <CPSelect label="Nature of inquiry" name="inquiry" options={['Acquisition', 'Private viewing', 'Bespoke commission', 'Press']} />
                  <CPSelect label="Edition of interest" name="edition" defaultValue={preset.editionValue} options={['ELYSIEN — Signature', 'Meant for Gods', 'For Chosen Ones', 'Flare of Eternity', 'Seven Diamonds', 'Eagle — USA Edition', 'Undecided']} />
                </div>
                <CPField label="Message" name="message" as="textarea" required defaultValue={preset.message} hint="Every inquiry is held in confidence." placeholder="" />
                <div ref={tsRef} style={{ marginTop: '4px' }} />
                {error && (
                  <p style={{ margin: 0, color: 'var(--accent-garnet)', fontFamily: 'var(--font-body)', fontWeight: 300, fontSize: 'var(--fs-body-sm)' }}>{error}</p>
                )}
                <div style={{ marginTop: '6px' }}>
                  <CPB2 className="cp-form-submit" variant="champagne" size="lg" type="submit" disabled={sending}>{sending ? 'Sending…' : 'Send to the maison'}</CPB2>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function MaisonFooter() {
  const cols = [
    ['The Object', ['ELYSIEN', 'Craftsmanship', 'The Mechanism', 'Specifications', 'The Collection']],
    ['Editions', ['Flare of Eternity', 'Meant for Gods', 'For Chosen Ones', 'Seven Diamonds', 'Eagle — USA']],
    ['The Maison', ['Philosophy', 'Provenance', 'Collectors', 'Concierge']],
  ];
  return (
    <footer style={{ background: 'var(--surface-void)', paddingTop: 'var(--sp-10)' }}>
      <div style={WIDE2}>
        <div className="cp-meander" style={{ marginBottom: 'var(--sp-9)', opacity: 0.4 }}></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 'var(--sp-7)', paddingBottom: 'var(--sp-9)' }} className="cp-foot">
          <div>
            <Pic src="assets/logo/CREAPEIRON_white.png" alt="Créapeiron" style={{ height: '52px', width: 'auto', marginBottom: '22px' }} />
            <p className="cp-body" style={{ margin: 0, maxWidth: '30ch', fontSize: 'var(--fs-body-sm)' }}>
              Créapeiron s.r.o. — a Czech maison of collectible mechanical art. Created, not manufactured.
            </p>
          </div>
          {cols.map(([h, items]) => (
            <div key={h}>
              <h4 style={{ margin: '0 0 20px', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 'var(--fs-micro)', letterSpacing: 'var(--ls-wider)', textTransform: 'uppercase', color: 'var(--text-accent)' }}>{h}</h4>
              <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: '14px' }}>
                {items.map((it) => (
                  <li key={it}><a href="#" style={{ fontFamily: 'var(--font-body)', fontWeight: 300, fontSize: 'var(--fs-body-sm)', color: 'var(--text-secondary)' }}>{it}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ borderTop: '1px solid var(--border-hairline)', padding: '30px 0 40px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '20px' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--fs-micro)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--text-muted)' }}>© Créapeiron s.r.o. · ELYSIEN®</span>
          <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
            {[
              ['Instagram', 'https://www.instagram.com/creapeiron', 'M7.5 2h9A5.5 5.5 0 0 1 22 7.5v9a5.5 5.5 0 0 1-5.5 5.5h-9A5.5 5.5 0 0 1 2 16.5v-9A5.5 5.5 0 0 1 7.5 2Zm0 1.8A3.7 3.7 0 0 0 3.8 7.5v9a3.7 3.7 0 0 0 3.7 3.7h9a3.7 3.7 0 0 0 3.7-3.7v-9a3.7 3.7 0 0 0-3.7-3.7h-9ZM12 7a5 5 0 1 1 0 10 5 5 0 0 1 0-10Zm0 1.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4ZM17.3 5.6a1.1 1.1 0 1 1 0 2.2 1.1 1.1 0 0 1 0-2.2Z'],
              ['Facebook', 'https://www.facebook.com/share/1Dx7GnVRuZ/', 'M13.5 21v-8h2.7l.4-3.1h-3.1V7.9c0-.9.25-1.5 1.55-1.5h1.65V3.6A22 22 0 0 0 14.4 3.5c-2.4 0-4 1.45-4 4.1v2.3H7.7V13h2.7v8h3.1Z'],
              ['YouTube', 'https://www.youtube.com/@Creapeiron', 'M22.5 8.2a3 3 0 0 0-2.1-2.1C18.5 5.6 12 5.6 12 5.6s-6.5 0-8.4.5A3 3 0 0 0 1.5 8.2 31 31 0 0 0 1 12a31 31 0 0 0 .5 3.8 3 3 0 0 0 2.1 2.1c1.9.5 8.4.5 8.4.5s6.5 0 8.4-.5a3 3 0 0 0 2.1-2.1A31 31 0 0 0 23 12a31 31 0 0 0-.5-3.8ZM10 15.1V8.9l5.3 3.1-5.3 3.1Z'],
            ].map(([label, href, d]) => (
              <a key={label} href={href} target="_blank" rel="noopener noreferrer" aria-label={label} className="cp-social" style={{ display: 'inline-flex', color: 'var(--text-muted)', transition: 'color 240ms ease' }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d={d}></path></svg>
              </a>
            ))}
          </div>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--fs-micro)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Collectible mechanical art · Not for sale to the public</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Concierge, MaisonFooter });
