// ============================================
// CONTACT page
// ============================================

function ContactPage({ navigate }) {
  const { Placeholder, Reveal, SectionHeader, Icon } = window.LM_UI;
  const { t } = window.LM_CMS;
  const site = window.LM_CMS.site();

  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({ name: '', email: '', subject: 'algemeen', message: '' });

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setSending(true);
    try {
      await window.LM_SUBMIT('contact', form);
      setSent(true);
      setForm({ name: '', email: '', subject: 'algemeen', message: '' });
      setTimeout(() => setSent(false), 8000);
    } catch (err) {
      setError('Versturen mislukt — probeer opnieuw of mail ons rechtstreeks.');
    } finally {
      setSending(false);
    }
  };

  return (
    <div>
      <section className="section" style={{ paddingBottom: 32 }}>
        <div className="container">
          <SectionHeader
            eyebrow={t('contact.intro.eyebrow', 'Contact & locatie')}
            title={<>{t('contact.intro.title1', 'Spring binnen of')} <span className="grad-text">{t('contact.intro.title2', 'stuur een berichtje')}</span>{t('contact.intro.title3', '.')}</>}
            subtitle={t('contact.intro.subtitle', 'Vragen, suggesties of zin om langs te komen? We helpen je graag verder.')}
          />
        </div>
      </section>

      <section style={{ paddingBottom: 96 }}>
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.3fr)', gap: 56 }} className="contact-grid">

            {/* Left: details */}
            <Reveal>
              <div className="card" style={{ padding: 40, height: '100%' }}>
                <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--blue-600)', marginBottom: 12 }}>
                  {t('contact.info.eyebrow', 'Praktisch')}
                </div>
                <h3 className="display" style={{ fontSize: 28, margin: '0 0 32px', textTransform: 'none', letterSpacing: '-0.01em' }}>
                  {t('contact.info.title', 'Bezoek of bel ons.')}
                </h3>

                <ContactItem
                  icon={<Icon.Pin />}
                  label={t('contact.info.studios', 'Winkel')}
                  value={<>{site.addressLine1 || 'Winkel adres lijn 1'}<br />{site.addressLine2 || 'Postcode + Gemeente'}</>}
                />
                <ContactItem
                  icon={<Icon.Phone />}
                  label={t('contact.info.phone', 'Telefoon')}
                  value={site.contactPhone || '+32 (0)4XX XX XX XX'}
                />
                <ContactItem
                  icon={<Icon.Mail />}
                  label={t('contact.info.email', 'E-mail')}
                  value={site.contactEmail || 'demo@dance-suite.example'}
                />
                <ContactItem
                  icon={<Icon.Clock />}
                  label={t('contact.info.hoursLabel', 'Onthaal-uren')}
                  value={(t('contact.info.hoursValue', 'Ma–Vr · 16:00 – 21:00\nZat · 09:00 – 15:00')).split('\n').map((l, i, arr) => <React.Fragment key={i}>{l}{i < arr.length - 1 && <br/>}</React.Fragment>)}
                />

                <div style={{ marginTop: 32, paddingTop: 24, borderTop: '1px solid var(--border)' }}>
                  <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 12 }}>
                    {t('contact.info.followLabel', 'Volg ons')}
                  </div>
                  <div style={{ display: 'flex', gap: 10 }}>
                    {[
                      { Icon: Icon.Instagram, label: 'Instagram', href: site.socialInstagram || '#' },
                      { Icon: Icon.Facebook, label: 'Facebook', href: site.socialFacebook || '#' },
                    ].map(({ Icon: I, label, href }, i) => (
                      <a key={i} href={href} target="_blank" rel="noreferrer" style={{
                        width: 44, height: 44, borderRadius: 10,
                        background: 'var(--ink-100)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        color: 'var(--ink-700)',
                        transition: 'all .15s',
                      }}
                        onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--teal-500)'; e.currentTarget.style.color = 'white'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--ink-100)'; e.currentTarget.style.color = 'var(--ink-700)'; }}
                      ><I /></a>
                    ))}
                  </div>
                </div>
              </div>
            </Reveal>

            {/* Right: form */}
            <Reveal delay={100}>
              <form onSubmit={submit} className="card" style={{ padding: 40 }}>
                <h3 className="display" style={{ fontSize: 24, margin: '0 0 8px', textTransform: 'none', letterSpacing: '-0.01em' }}>{t('contact.form.title', 'Stuur ons een bericht')}</h3>
                <p style={{ color: 'var(--ink-500)', margin: '0 0 32px' }}>{t('contact.form.subtitle', 'We antwoorden meestal binnen 24u.')}</p>

                <div className="grid grid-2" style={{ marginBottom: 20 }}>
                  <div>
                    <label className="label">Naam</label>
                    <input className="input" required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="Je naam" />
                  </div>
                  <div>
                    <label className="label">E-mail</label>
                    <input className="input" type="email" required value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="naam@email.be" />
                  </div>
                </div>

                <div style={{ marginBottom: 20 }}>
                  <label className="label">{t('contact.form.subjectLabel', 'Onderwerp')}</label>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {[
                      { id: 'algemeen',    label: t('contact.form.subject1', 'Algemene vraag') },
                      { id: 'inschrijving',label: t('contact.form.subject2', 'Inschrijving') },
                      { id: 'auditie',     label: t('contact.form.subject3', 'Auditie / showteam') },
                      { id: 'g-dans',      label: t('contact.form.subject4', 'G-Dans') },
                    ].map(o => (
                      <button key={o.id} type="button" onClick={() => setForm({ ...form, subject: o.id })}
                        className={`chip ${form.subject === o.id ? 'active' : ''}`}
                      >{o.label}</button>
                    ))}
                  </div>
                </div>

                <div style={{ marginBottom: 24 }}>
                  <label className="label">{t('contact.form.messageLabel', 'Bericht')}</label>
                  <textarea className="textarea" rows="5" required value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} placeholder="Laat je vraag of bericht hier..." />
                </div>

                {sent && (
                  <div role="status" style={{ background: '#e6f7f1', color: '#0f5132', border: '1px solid #b7e4d2', padding: 14, borderRadius: 8, marginBottom: 12, fontSize: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ flexShrink: 0, display: 'flex' }}><Icon.Check /></span>
                    <span>{t('contact.form.successBanner', 'Bedankt! Je bericht is verzonden — we nemen zo snel mogelijk contact met je op (meestal binnen 24u).')}</span>
                  </div>
                )}

                {error && <div role="alert" style={{ background: '#fde8e8', color: '#9b1c1c', padding: 12, borderRadius: 8, marginBottom: 12, fontSize: 14 }}>{error}</div>}

                <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }} disabled={sending}>
                  {sent ? <><Icon.Check /> {t('contact.form.sent', 'Verstuurd!')}</> : <>{sending ? 'Versturen…' : t('contact.form.button', 'Verstuur bericht')} <Icon.ArrowRight /></>}
                </button>
              </form>
            </Reveal>
          </div>
        </div>
      </section>

      {/* Locaties — interactieve grid van studios */}
      <section style={{ paddingBottom: 96 }}>
        <div className="container">
          <Reveal>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
              <span className="stripe-accent"></span>
              <span className="eyebrow">{t('contact.locations.eyebrow', 'Onze locaties')}</span>
            </div>
            <p className="mono" style={{ fontSize: 11, color: 'var(--ink-500)', letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 24 }}>
              {t('contact.locations.hint', 'Klik op een kaartje voor meer info')}
            </p>
          </Reveal>

          <div className="lm-loc-grid" style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 24,
            alignItems: 'start',
          }}>
            {((window.LM_DATA?.LOCATIONS) || []).map((loc, i) => (
              <Reveal key={loc.id || i} delay={(i % 6) * 80}>
                <LocationCard location={loc} />
              </Reveal>
            ))}
            {(!window.LM_DATA?.LOCATIONS?.length) && (
              <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px 0', color: 'var(--ink-500)' }}>
                Geen locaties toegevoegd. Voeg ze toe in het controlepaneel onder <strong>Locaties</strong>.
              </div>
            )}
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 880px) {
          .contact-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function ContactItem({ icon, label, value }) {
  return (
    <div style={{ display: 'flex', gap: 16, marginBottom: 20, alignItems: 'flex-start' }}>
      <div style={{
        width: 40, height: 40, borderRadius: 10,
        background: 'var(--gradient-soft)',
        color: 'var(--blue-600)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{icon}</div>
      <div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)', marginBottom: 4 }}>{label}</div>
        <div style={{ fontSize: 15, fontWeight: 500, lineHeight: 1.4 }}>{value}</div>
      </div>
    </div>
  );
}

// ============================================
// LocationCard — uitklapbare 3D-getilte kaart met faux-map
// Geadapteerd van expand-map.tsx naar vanilla React + inline styles.
// ============================================
function LocationCard({ location }) {
  const { Icon } = window.LM_UI;
  const ref = React.useRef(null);
  const [hovered, setHovered] = React.useState(false);
  const [expanded, setExpanded] = React.useState(false);
  const [tilt, setTilt] = React.useState({ x: 0, y: 0 });

  const onMouseMove = (e) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const cx = r.left + r.width / 2;
    const cy = r.top + r.height / 2;
    const dx = (e.clientX - cx) / r.width;
    const dy = (e.clientY - cy) / r.height;
    setTilt({ x: dy * -10, y: dx * 10 });
  };
  const onMouseLeave = () => { setHovered(false); setTilt({ x: 0, y: 0 }); };

  const photoUrl = location.image ? location.image.replace(/^(?!\/|https?:\/\/|\/\/|data:)/, '/') : '';
  const hasMaps = !!(location.mapsUrl && location.mapsUrl.trim());

  return (
    <div
      ref={ref}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={onMouseLeave}
      onMouseMove={onMouseMove}
      onClick={(e) => {
        // Klik op een link binnen de kaart mag de toggle niet triggeren
        if (e.target.closest('a')) return;
        setExpanded(v => !v);
      }}
      style={{
        position: 'relative',
        cursor: 'pointer',
        userSelect: 'none',
        perspective: '1000px',
        minHeight: expanded ? 360 : 200,
        transition: 'min-height .35s cubic-bezier(.2,.7,.2,1)',
      }}
    >
      <div style={{
        position: 'relative',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 18,
        overflow: 'hidden',
        boxShadow: hovered ? 'var(--shadow-lg)' : 'var(--shadow-sm)',
        transform: `rotateX(${tilt.x}deg) rotateY(${tilt.y}deg)`,
        transformStyle: 'preserve-3d',
        transition: 'transform .25s ease, box-shadow .2s ease, height .4s cubic-bezier(.2,.7,.2,1)',
        height: expanded ? 360 : 200,
      }}>
        {/* Achtergrond: foto OF faux-map */}
        <div style={{ position: 'absolute', inset: 0 }}>
          {expanded ? (
            <FauxMap photoUrl={photoUrl} />
          ) : photoUrl ? (
            <>
              <img src={photoUrl} alt={location.name} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(12,12,15,0) 35%, rgba(12,12,15,.92) 100%)' }} />
            </>
          ) : (
            <div style={{
              width: '100%', height: '100%',
              background: `
                repeating-linear-gradient(0deg, rgba(45,111,165,.08) 0 1px, transparent 1px 30px),
                repeating-linear-gradient(90deg, rgba(45,111,165,.08) 0 1px, transparent 1px 30px),
                linear-gradient(135deg, var(--ink-50), var(--blue-50))
              `,
            }} />
          )}
        </div>

        {/* Content overlay */}
        <div style={{
          position: 'relative',
          zIndex: 2,
          height: '100%',
          padding: 20,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
        }}>
          {/* Top: tag + live-indicator */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              background: 'rgba(14,26,38,.08)',
              backdropFilter: 'blur(8px)',
              padding: '4px 10px',
              borderRadius: 999,
              fontSize: 11,
              color: 'var(--ink-700)',
              fontWeight: 600,
              transition: 'transform .2s',
              transform: hovered ? 'scale(1.04)' : 'scale(1)',
            }}>
              <span style={{
                width: 6, height: 6, borderRadius: '50%',
                background: 'var(--teal-500)',
                boxShadow: '0 0 8px var(--teal-500)',
                animation: 'lmPulse 2s ease-in-out infinite',
              }}></span>
              <span className="mono" style={{ letterSpacing: '0.1em', textTransform: 'uppercase', fontSize: 10 }}>
                {location.tag || 'Winkel'}
              </span>
            </div>
          </div>

          {/* Bottom: naam + adres */}
          <div>
            <h3 className="display" style={{
              fontSize: expanded ? 22 : 19,
              margin: '0 0 4px',
              textTransform: 'none',
              letterSpacing: '-0.01em',
              transition: 'transform .25s, font-size .3s',
              transform: hovered ? 'translateX(3px)' : 'translateX(0)',
              color: 'var(--ink-900)',
            }}>
              {location.name}
            </h3>
            <p style={{ fontSize: 13, color: 'var(--ink-500)', margin: 0, lineHeight: 1.45 }}>
              {location.addressLine1}{location.addressLine2 ? <><br />{location.addressLine2}</> : null}
            </p>

            {expanded && location.description && (
              <p style={{ fontSize: 13, color: 'var(--ink-700)', margin: '12px 0 0', lineHeight: 1.55, animation: 'lmFadeIn .3s ease .1s both' }}>
                {location.description}
              </p>
            )}

            {expanded && location.coordinates && (
              <p className="mono" style={{ fontSize: 11, color: 'var(--ink-500)', margin: '8px 0 0', letterSpacing: '0.04em', animation: 'lmFadeIn .3s ease .15s both' }}>
                {location.coordinates}
              </p>
            )}

            {/* Onderstreping */}
            <div style={{
              marginTop: 10,
              height: 2,
              background: 'linear-gradient(90deg, var(--teal-500), var(--blue-500), transparent)',
              transformOrigin: 'left',
              transform: hovered || expanded ? 'scaleX(1)' : 'scaleX(0.3)',
              transition: 'transform .4s ease',
              borderRadius: 2,
            }} />

            {expanded && (
              <div style={{ marginTop: 14, display: 'flex', gap: 8, flexWrap: 'wrap', animation: 'lmFadeIn .35s ease .2s both' }}>
                {hasMaps && (
                  <a href={location.mapsUrl} target="_blank" rel="noreferrer"
                    className="btn btn-sm btn-primary"
                    onClick={(e) => e.stopPropagation()}
                    style={{ textDecoration: 'none' }}>
                    Open in Maps <Icon.ArrowRight size={12} />
                  </a>
                )}
                <button type="button" className="btn btn-sm btn-ghost" onClick={(e) => { e.stopPropagation(); setExpanded(false); }}>
                  Inklappen
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Click hint */}
      {!expanded && (
        <p className="mono" style={{
          position: 'absolute',
          bottom: -22, left: '50%', transform: 'translateX(-50%)',
          fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase',
          color: 'var(--ink-400)',
          opacity: hovered ? 1 : 0,
          transition: 'opacity .2s',
          pointerEvents: 'none',
          whiteSpace: 'nowrap',
        }}>
          Klik om uit te klappen
        </p>
      )}

      <style>{`
        @keyframes lmPulse  { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
        @keyframes lmFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes lmDraw   { from { stroke-dashoffset: 100%; } to { stroke-dashoffset: 0; } }
        .lm-fauxmap-road  { stroke-dasharray: 100%; animation: lmDraw .9s ease forwards; }
        .lm-fauxmap-bld   { animation: lmFadeIn .5s ease forwards; opacity: 0; }
      `}</style>
    </div>
  );
}

// FauxMap — vector-illustratie met wegen, gebouwen en een pin (in stijl van de site)
function FauxMap({ photoUrl }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: photoUrl
        ? `linear-gradient(135deg, rgba(14,26,38,.55), rgba(14,26,38,.3)), url("${photoUrl}") center/cover`
        : 'linear-gradient(135deg, var(--ink-50), var(--blue-50))',
    }}>
      <svg width="100%" height="100%" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0 }}>
        {/* Hoofdwegen */}
        <line x1="0%" y1="35%" x2="100%" y2="35%" stroke="rgba(14,26,38,.22)" strokeWidth="4" className="lm-fauxmap-road" style={{ animationDelay: '.1s' }} />
        <line x1="0%" y1="65%" x2="100%" y2="65%" stroke="rgba(14,26,38,.22)" strokeWidth="4" className="lm-fauxmap-road" style={{ animationDelay: '.2s' }} />
        <line x1="30%" y1="0%" x2="30%" y2="100%" stroke="rgba(14,26,38,.18)" strokeWidth="3" className="lm-fauxmap-road" style={{ animationDelay: '.3s' }} />
        <line x1="70%" y1="0%" x2="70%" y2="100%" stroke="rgba(14,26,38,.18)" strokeWidth="3" className="lm-fauxmap-road" style={{ animationDelay: '.4s' }} />
        {/* Secundaire straten */}
        {[20, 50, 80].map((y, i) => (
          <line key={'h' + i} x1="0%" y1={`${y}%`} x2="100%" y2={`${y}%`} stroke="rgba(14,26,38,.08)" strokeWidth="1.5" className="lm-fauxmap-road" style={{ animationDelay: `${.5 + i * .08}s` }} />
        ))}
        {[15, 45, 55, 85].map((x, i) => (
          <line key={'v' + i} x1={`${x}%`} y1="0%" x2={`${x}%`} y2="100%" stroke="rgba(14,26,38,.08)" strokeWidth="1.5" className="lm-fauxmap-road" style={{ animationDelay: `${.6 + i * .08}s` }} />
        ))}
      </svg>

      {/* Gebouwen */}
      {[
        { top: '40%', left: '10%', w: '15%', h: '20%', delay: .5 },
        { top: '15%', left: '35%', w: '12%', h: '15%', delay: .55 },
        { top: '70%', left: '75%', w: '18%', h: '18%', delay: .6 },
        { top: '20%', right: '10%', w: '10%', h: '25%', delay: .65 },
        { top: '55%', left: '5%', w: '8%', h: '12%', delay: .7 },
        { top: '8%', left: '75%', w: '14%', h: '10%', delay: .75 },
      ].map((b, i) => (
        <div key={i} className="lm-fauxmap-bld" style={{
          position: 'absolute',
          top: b.top, left: b.left, right: b.right,
          width: b.w, height: b.h,
          background: 'rgba(14,26,38,.18)',
          border: '1px solid rgba(14,26,38,.1)',
          borderRadius: 3,
          animationDelay: `${b.delay}s`,
        }} />
      ))}

      {/* Pin in het midden */}
      <div style={{
        position: 'absolute',
        top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        animation: 'lmFadeIn .4s ease .25s both',
      }}>
        <svg width="38" height="38" viewBox="0 0 24 24" fill="none"
          style={{ filter: 'drop-shadow(0 0 12px rgba(63,168,158,.7))' }}>
          <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z" fill="#3fa89e"/>
          <circle cx="12" cy="9" r="2.5" fill="white"/>
        </svg>
      </div>
    </div>
  );
}

window.LM_PAGES = window.LM_PAGES || {};
window.LM_PAGES.Contact = ContactPage;
